快速入門導覽課程:透過 Rust 使用 Cloud Storage

Google Cloud Storage 是用來儲存非結構化資料的代管服務。

Rust 用戶端程式庫提供慣用 API,可存取這項服務。用戶端程式庫會繼續下載及上傳中斷的作業,並自動對資料執行完整性檢查。對於中繼資料作業,用戶端程式庫可以重試失敗的要求,並自動輪詢長時間執行的作業。

本指南說明如何建立 Cloud Storage bucket、將物件上傳至這個 bucket,然後讀取該物件。

開始閱讀本指南前,請先建立已啟用計費功能Google Cloud 專案

新增用戶端程式庫依附元件

cargo add google-cloud-storage

建立儲存空間值區

用來對 bucket 和物件中繼資料執行作業的用戶端稱為 StorageControl

    use google_cloud_storage::model::{Bucket, bucket::IamConfig, bucket::iam_config::UniformBucketLevelAccess};
    use google_cloud_storage::client::StorageControl;
    let control = StorageControl::builder().build().await?;

如要建立 bucket,必須提供專案名稱和 bucket ID。

    let bucket = control
        .create_bucket()
        .set_parent("projects/_")
        .set_bucket_id(bucket_id)
        .set_bucket(
            gcs::model::Bucket::new()
                .set_project(format!("projects/{project_id}"))
        )

您也可以提供值區的其他屬性。舉例來說,如要讓值區中的所有物件使用相同權限,可以啟用「統一值區層級存取權」

    Bucket::new()
        .set_project(format!("projects/{project_id}"))
        .set_iam_config(
            IamConfig::new()
                .set_uniform_bucket_level_access(
                    UniformBucketLevelAccess::new()
                        .set_enabled(true),
            ),
        ),

然後傳送這項要求,等待回應。

        .send()
        .await?;
    println!("bucket successfully created {bucket:?}");

上傳物件

用來對物件資料執行作業的用戶端稱為「Storage」。

    use google_cloud_storage::client::Storage;
    let client = Storage::builder().build().await?;

在本例中,您會建立名為 hello.txt 的物件,其中含有招呼語「Hello World!」

    let object = client
        .upload_object(&bucket.name, "hello.txt", "Hello World!")
        .send_buffered()
        .await?;
    println!("object successfully uploaded {object:?}");

下載物件

如要下載物件內容,請使用 read_object() 方法。

    let mut reader = client.read_object(&bucket.name, "hello.txt").send().await?;
    let mut contents = Vec::new();
    while let Some(chunk) = reader.next().await.transpose()? {
        contents.extend_from_slice(&chunk);
    }
    println!(
        "object contents successfully downloaded {:?}",
        bytes::Bytes::from_owner(contents)
    );

清除所用資源

最後,請移除物件和 bucket,清除本指南中使用的資源。

    control
        .delete_object()
        .set_bucket(&bucket.name)
        .set_object(&object.name)
        .set_generation(object.generation)
        .send()
        .await?;
    control
        .delete_bucket()
        .set_name(&bucket.name)
        .send()
        .await?;