覆寫預設端點

Rust 用戶端程式庫會自動設定每項服務的端點。某些應用程式可能需要覆寫預設端點,原因可能是網路有特定需求,或需要使用區域版本的服務。本文說明如何覆寫預設值。

必要條件

本文件使用 Secret Manager API。如要啟用這個 API,請按照服務快速入門導覽課程操作。

如需 Rust 用戶端程式庫的完整設定操作說明,請參閱「開始使用 Rust」。

依附元件

您必須在 Cargo.toml 檔案中宣告依附元件:

cargo add google-cloud-secretmanager-v1 google-cloud-gax

預設端點

首先,請參閱如何搭配預設端點使用用戶端程式庫。首先,請編寫一些 use 宣告,簡化範例的其餘部分:

  1. 在接收專案 ID 做為參數的函式中編寫範例:

    /// # Parameters
    /// - `project_id`: the id of a Google Cloud project, or its numeric ID.
    ///   For example: `my-project`.
    pub async fn sample(project_id: &str) -> anyhow::Result<()> {

  2. 新增一些 use 宣告,簡化範例程式碼:

    pub use google_cloud_gax::paginator::ItemPaginator;
    pub use google_cloud_secretmanager_v1::client::SecretManagerService;

  3. 使用預設值初始化用戶端:

    let client = SecretManagerService::builder().build().await?;

  4. 然後照常使用這個用戶端:

    let mut items = client
        .list_secrets()
        .set_parent(format!("projects/{project_id}"))
        .by_item();
    println!("listing all secrets in project {project_id}");
    while let Some(secret) = items.next().await.transpose()? {
        println!("  {secret:?}");
    }
    println!("DONE");

覆寫預設端點

在本範例中,您會將用戶端程式庫設為使用 Secret Manager 的區域端點。您可以使用相同的覆寫設定,透過其中一個私人存取選項設定端點,或在支援位置端點的服務中設定。

  1. 和之前一樣,編寫一個範例,接收專案 ID 和區域做為參數:

    /// # Parameters
    /// - `project_id`: the id of a Google Cloud project, or its numeric ID.
    ///   For example: `my-project`.
    /// - `region`: the id of a Gooogle Cloud region. For example `us-central1`.
    pub async fn sample(project_id: &str, region: &str) -> anyhow::Result<()> {

  2. 新增一些 use 宣告,簡化程式碼:

    pub use google_cloud_gax::paginator::ItemPaginator;
    pub use google_cloud_secretmanager_v1::client::SecretManagerService;

  3. 使用目標端點初始化用戶端:

    let client = SecretManagerService::builder()
        .with_endpoint(format!("https://secretmanager.{region}.rep.googleapis.com"))
        .build()
        .await?;

  4. 然後照常使用這個用戶端:

    let mut items = client
        .list_secrets()
        .set_parent(format!("projects/{project_id}/locations/{region}"))
        .by_item();
    println!("listing all secrets in project {project_id} and region {region}");
    while let Some(secret) = items.next().await.transpose()? {
        println!("  {secret:?}");
    }
    println!("DONE");