Inicializar um cliente

As bibliotecas de cliente do Cloud para Rust usam structs de cliente como a interface principal para os serviços doGoogle Cloud , com métodos correspondentes a cada RPC oferecido pelo serviço. Antes de chamar um serviço, inicialize o cliente dele.

Neste documento, mostramos como inicializar um cliente do Secret Manager com a configuração padrão e chamar uma RPC. O mesmo padrão se aplica a todos os outros serviços do Google Cloud .

Antes de começar

Antes de executar o código neste documento, conclua os seguintes pré-requisitos:

Dependências

Adicione os crates necessários ao arquivo Cargo.toml:

cargo add google-cloud-secretmanager-v1 google-cloud-gax anyhow
cargo add tokio --features macros,rt-multi-thread

Inicializar um cliente e fazer uma RPC

Para inicializar um cliente, chame builder na estrutura do cliente para receber um ClientBuilder e, em seguida, chame build. Siga estas etapas para inicializar um cliente com as configurações padrão e chamar uma RPC:

  1. Importe o tipo de cliente SecretManagerService:

    use google_cloud_secretmanager_v1::client::SecretManagerService;

  2. Crie o cliente com a configuração padrão:

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

  3. Use o cliente inicializado para chamar list_locations, que lista os locais compatíveis com o Secret Manager para seu projeto:

    use google_cloud_gax::paginator::Paginator as _;
    let mut items = client
        .list_locations()
        .set_name(format!("projects/{project_id}"))
        .by_page();
    while let Some(page) = items.next().await {
        let page = page?;
        for location in page.locations {
            println!("{}", location.name);
        }
    }

A saída será assim:

projects/PROJECT_NUMBER/locations/europe-west8
projects/PROJECT_NUMBER/locations/europe-west9
projects/PROJECT_NUMBER/locations/us-east5

Nessa saída, PROJECT_NUMBER é o número do projeto numérico do projeto do Google Cloud .

Preencher código

O exemplo a seguir combina a inicialização do cliente e a chamada list_locations em um programa executável:

pub async fn initialize_client(project_id: &str) -> anyhow::Result<()> {
    use google_cloud_secretmanager_v1::client::SecretManagerService;

    // Initialize a client with the default configuration. This is an
    // asynchronous operation that may fail, as it requires acquiring an an
    // access token.
    let client = SecretManagerService::builder().build().await?;

    // Once initialized, use the client to make requests.
    use google_cloud_gax::paginator::Paginator as _;
    let mut items = client
        .list_locations()
        .set_name(format!("projects/{project_id}"))
        .by_page();
    while let Some(page) = items.next().await {
        let page = page?;
        for location in page.locations {
            println!("{}", location.name);
        }
    }

    Ok(())
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let project_id = std::env::args().nth(1).unwrap();

    initialize_client(&project_id).await
}