覆寫預設端點

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. 新增一些用途聲明,簡化範例程式碼:

    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");