デフォルトのエンドポイントをオーバーライドする

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

デフォルトのエンドポイントをオーバーライドする

この例では、シークレット マネージャーのリージョン エンドポイントを使用するようにクライアント ライブラリを構成します。同じオーバーライドを使用して、プライベート アクセス オプションのいずれかを使用してエンドポイントを構成したり、それらをサポートするサービスのロケーション エンドポイントを構成したりできます。

  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. 使用宣言を追加してコードを簡素化します。

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