Todos os produtos
Search
Central de documentação

Object Storage Service:OSS Go SDK V1

Última atualização: Jul 01, 2026

Recomendamos o uso do OSS Go SDK V2 mais recente (alibabacloud-oss-go-sdk-v2), que oferece melhorias arquiteturais significativas em relação à V1 (aliyun-oss-go-sdk). A versão V2 simplifica a verificação de identidade, as novas tentativas de requisição e o tratamento de erros, além de adicionar interfaces avançadas como paginadores, gerenciadores de transferência e interfaces semelhantes a arquivos. Para fazer upgrade, consulte o Guia de migração do Go SDK V1 para V2.

Integração rápida

Siga as etapas abaixo para integrar o OSS Go SDK V1.

image

Prepare o ambiente

Baixe e instale o ambiente de compilação e execução do Go. Para mais informações, consulte Instalar o Go. Use a versão 1.13 ou superior do Go.

  • A partir da versão 1.13, o modo de módulo é ativado por padrão para gerenciar dependências de pacotes. Não é necessário definir manualmente a variável GOPATH.

  • Para o Go 1.12 e versões anteriores, defina a variável de ambiente do sistema GOPATH e aponte-a para o diretório do seu código.

Execute o comando go version para verificar a versão instalada do Go.

Instale o SDK

Escolha um método de instalação adequado ao seu ambiente de desenvolvimento. Recomendamos usar a versão mais recente do SDK.

go mod (Recommended)

Adicione a seguinte dependência ao arquivo go.mod. Este exemplo usa a versão 3.0.2. Substitua-a pela versão desejada.

require (
    github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible
)

From source code

Execute o comando abaixo para instalar o SDK:

go get github.com/aliyun/aliyun-oss-go-sdk/oss

O processo de instalação não exibe mensagens. Caso ocorra timeout, execute o comando novamente.

Configure as credenciais de acesso

Configure as credenciais de acesso usando um par de AccessKey de um usuário RAM.

  1. No RAM console, crie um usuário RAM com um Permanent AccessKey Pair. Salve o par de AccessKey e conceda a permissão AliyunOSSFullAccess ao usuário.

  2. Use o par de AccessKey do usuário RAM para configurar as variáveis de ambiente.

    Linux

    1. Execute os comandos abaixo na interface de linha de comando para anexar as definições das variáveis de ambiente ao arquivo ~/.bashrc .

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
    2. Execute o comando a seguir para aplicar as alterações.

      source ~/.bashrc
    3. Execute os comandos abaixo para verificar se as variáveis de ambiente foram configuradas corretamente.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Execute o comando abaixo no terminal para identificar o tipo de shell padrão.

      echo $SHELL
    2. Realize as operações correspondentes ao tipo de shell padrão.

      Zsh

      1. Execute os comandos abaixo para anexar as definições das variáveis de ambiente ao arquivo ~/.zshrc.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
      2. Execute o comando a seguir para aplicar as alterações.

        source ~/.zshrc
      3. Execute os comandos abaixo para verificar se as variáveis de ambiente foram configuradas corretamente.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Execute os comandos abaixo para anexar as definições das variáveis de ambiente ao arquivo ~/.bash_profile.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
      2. Execute o comando a seguir para aplicar as alterações.

        source ~/.bash_profile
      3. Execute os comandos abaixo para verificar se as variáveis de ambiente foram configuradas corretamente.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Execute os comandos abaixo no CMD.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. Execute os comandos abaixo para verificar se as variáveis de ambiente foram configuradas corretamente.

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Execute os comandos abaixo no PowerShell.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
    2. Execute os comandos abaixo para verificar se as variáveis de ambiente foram configuradas corretamente.

      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Inicialize o cliente

O código de exemplo a seguir inicializa um cliente usando o endpoint público da região China (Hangzhou) e lista os buckets da conta atual. Para obter a lista completa de regiões e endpoints, consulte Regiões e endpoints.

package main

// Sample code for initializing a client in OSS Go SDK V1

import (
	"fmt"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {

	// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, _ := oss.NewEnvironmentVariableCredentialsProvider()

	// Create an OSS client instance.
	client, _ := oss.New(
		"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
		"",
		"",
		oss.SetCredentialsProvider(&provider),
		oss.AuthVersion(oss.AuthV4),
		oss.Region("cn-hangzhou"),
	)

	// List all buckets.
	buckets, err := client.ListBuckets()
	if err != nil {
		fmt.Printf("Failed to list buckets: %v\n", err)
		return
	}

	// Print the bucket list.
	fmt.Printf("Found %d buckets:\n", len(buckets.Buckets))

	for _, bucket := range buckets.Buckets {
		fmt.Printf("%s\n", bucket.Name)
	}
}

Configuração do cliente

Ao inicializar um cliente, personalize parâmetros como tipo de endpoint, tempo limite e tamanho do pool de conexões para atender aos seus requisitos de rede e desempenho.

Clique para visualizar os parâmetros configuráveis do cliente

Parâmetro

Descrição

Método

MaxIdleConns

Número máximo de conexões ociosas. Valor padrão: 100.

oss.MaxConns

MaxIdleConnsPerHost

Número máximo de conexões ociosas por host. Valor padrão: 100.

oss.MaxConns

MaxConnsPerHost

Número máximo de conexões por host. Valor padrão: vazio.

oss.MaxConns

ConnectTimeout

Tempo limite de conexão HTTP em segundos. Valor padrão: 10. O valor 0 indica ausência de tempo limite.

oss.Timeout

ReadWriteTimeout

Tempo limite de leitura ou gravação HTTP em segundos. Valor padrão: 20. O valor 0 indica ausência de tempo limite.

oss.Timeout

IsCname

Define se um nome de domínio personalizado será usado como endpoint. O valor padrão é false.

oss.UseCname

UserAgent

Cabeçalho User-Agent para requisições HTTP. Valor padrão: aliyun-sdk-go.

oss.UserAgent

ProxyHost

Define se o endereço e a porta do servidor proxy serão ativados. Valores válidos:

  • true: ativa o endereço e a porta do servidor proxy.

  • false (padrão): desativa o endereço e a porta do servidor proxy.

oss.AuthProxy

ProxyUser

Nome de usuário para autenticação no servidor proxy.

oss.AuthProxy

ProxyPassword

Senha para autenticação no servidor proxy.

oss.AuthProxy

RedirectEnabled

Define se o redirecionamento HTTP será ativado. Valores válidos:

  • true (padrão): ativa o redirecionamento HTTP.

  • false: desativa o redirecionamento HTTP.

oss.RedirectEnabled

InsecureSkipVerify

Define se a verificação de certificado SSL será ativada. Valores válidos:

  • true (padrão): ignora a verificação de certificado SSL.

  • false: ativa a verificação de certificado SSL.

oss.InsecureSkipVerify

IsEnableCRC

Define se a validação de dados CRC será ativada. Valores válidos:

  • true (padrão): ativa a validação de dados CRC.

  • false: desativa a validação de dados CRC.

oss.EnableCRC

LogLevel

Nível de log. Valores válidos:

  • oss.LogOff

  • oss.Debug

  • oss.Error

  • oss.Warn

  • oss.Info

oss.SetLogLevel

Use um endpoint interno

Para acessar o OSS via rede interna, especifique um endpoint interno ao inicializar o cliente OSS.

// Create an OSS client instance.
client, _ := oss.New(
	"oss-cn-hangzhou-internal.aliyuncs.com", // The internal endpoint of China (Hangzhou) is used as an example.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
)

Use um nome de domínio personalizado

Para acessar o OSS usando um nome de domínio personalizado, especifique-o como endpoint e ative a opção CNAME com oss.UseCname(true) durante a inicialização do cliente.

Antes de usar um nome de domínio personalizado, certifique-se de mapeá-lo para um bucket. Para mais informações, consulte Acessar o OSS por meio de um nome de domínio personalizado .
// Specify whether to use a custom domain name as the endpoint. The default value is false.
cname := oss.UseCname(true)

// Create an OSS client instance.
client, _ := oss.New(
	"http://kitkat-cloud.cn", // A custom domain name.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
	cname,
)

Controle de tempo limite

Use o parâmetro oss.Timeout para definir o tempo limite de conexão HTTP e o tempo limite de leitura/gravação em segundos.

// Set the HTTP connection timeout period to 20 seconds and the HTTP read or write timeout period to 60 seconds.
time := oss.Timeout(20, 60)

// Create an OSS client instance.
client, _ := oss.New(
	"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
	time,
)

Defina o tamanho do pool de conexões

Use o parâmetro oss.MaxConns para ajustar o tamanho do pool de conexões.

// Set the maximum number of idle connections (MaxIdleConns) to 10. The default value is 100.
// Set the maximum number of idle connections per host (MaxIdleConnsPerHost) to 20. The default value is 100.
// Set the maximum number of connections per host (MaxConnsPerHost) to 50. The default value is empty.
conn := oss.MaxConns(10, 20, 50)

// Create an OSS client instance.
client, _ := oss.New(
	"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
	conn,
)

Desative a validação de dados CRC

Defina oss.EnableCRC(false) para desativar a validação de dados CRC.

Importante

Recomendamos fortemente manter a validação de dados CRC ativada. Se você desativar esse recurso, o OSS não poderá garantir a integridade dos dados durante uploads e downloads.

// Disable CRC data validation.
crc := oss.EnableCRC(false)

// Create an OSS client instance.
client, _ := oss.New(
	"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
	crc,
)

Versão da assinatura

Importante

As assinaturas V1 do Alibaba Cloud Object Storage Service serão descontinuadas conforme o cronograma abaixo. Faça upgrade para assinaturas V4 o quanto antes para evitar impactos nos seus serviços.

  • A partir de 1º de março de 2025, novos usuários não poderão usar assinaturas V1.

  • A partir de 1º de setembro de 2025, a manutenção e as atualizações das assinaturas V1 serão gradualmente descontinuadas, e buckets recém-criados não poderão usar assinaturas V1.

O código de exemplo a seguir inicializa um cliente com uma assinatura V1. Para inicialização com assinatura V4, consulte Inicialize o cliente.

package main

// Sample code for initializing a client with a V1 signature in OSS Go SDK V1

import (
	"fmt"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {

	// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, _ := oss.NewEnvironmentVariableCredentialsProvider()

	// Create an OSS client instance.
	client, _ := oss.New(
		"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
		"",
		"",
		oss.SetCredentialsProvider(&provider),
	)

	// List all buckets.
	buckets, err := client.ListBuckets()
	if err != nil {
		fmt.Printf("Failed to list buckets: %v\n", err)
		return
	}

	// Print the bucket list.
	fmt.Printf("Found %d buckets:\n", len(buckets.Buckets))

	for _, bucket := range buckets.Buckets {
		fmt.Printf("%s\n", bucket.Name)
	}
}

Defina o contexto da requisição

Use o contexto da requisição para controlar o ciclo de vida das requisições.

Apenas o OSS Go SDK 2.2.9 e versões posteriores suportam a definição do contexto da requisição.
package main

// Sample code for setting the request context in OSS Go SDK V1

import (
	"context"
	"fmt"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {

	// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, _ := oss.NewEnvironmentVariableCredentialsProvider()

	// Create an OSS client instance.
	client, _ := oss.New(
		"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
		"",
		"",
		oss.SetCredentialsProvider(&provider),
		oss.AuthVersion(oss.AuthV4),
		oss.Region("cn-hangzhou"),
	)

	// Get the bucket object.
	bucket, _ := client.Bucket("example-bucket-hz")

	// Configure object information.
	key := "oss-browser2-mac-arm64-2.1.0.dmg"       // The path of the object in OSS.
	file_path := "oss-browser2-mac-arm64-2.1.0.dmg" // The local path to save the object.

	// Set the request context.
	ctx := context.Background()

	// Specify that the request context expires in 5 seconds.
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	// Download the object from OSS to the specified local path and set the request context.
	err := bucket.GetObjectToFile(key, file_path, oss.WithContext(ctx))
	if err != nil {
		select {
		case <-ctx.Done():
			fmt.Printf("Request canceled or timed out: %v\n", err)
		default:
			fmt.Printf("Download failed: %v\n", err)
		}
		return
	}

	fmt.Printf("Object downloaded: %s -> %s\n", key, file_path)
}

Tratamento de erros

Quando ocorre um erro durante o acesso ao OSS, o SDK retorna detalhes que incluem o código de status HTTP, mensagem de erro, ID da requisição e código de erro EC. O código de erro EC identifica a causa específica e ajuda a solucionar o problema rapidamente. Por exemplo, ao tentar baixar um objeto inexistente, a seguinte mensagem de erro é retornada:

oss: service returned error: StatusCode=404, ErrorCode=NoSuchKey, ErrorMessage="The specified key does not exist.", RequestId=69030EDB2E5F223030953167, Ec=0026-00000001

Na mensagem de erro, 'EC': '0026-00000001' representa o código de erro EC. Use esse código para identificar a causa do problema e a solução correspondente.

Códigos de exemplo

O OSS Go SDK V1 fornece códigos de exemplo que abrangem recursos essenciais, como gerenciamento de buckets, operações de objetos, controle de acesso e transferência criptografada. A tabela a seguir lista os exemplos disponíveis:

Código de exemplo no GitHub

Código de exemplo na documentação oficial

new_bucket.go

Inicializar um cliente

create_bucket.go

Criar um bucket (Go SDK V1)

bucket_acl.go

Gerenciar ACLs de bucket (Go SDK V1)

bucket_policy.go

Política de autorização

bucket_referer.go

Proteção contra hotlink (Go SDK V1)

bucket_lifecycle.go

Ciclo de vida

bucket_logging.go

Log de acesso

bucket_cors.go

Acesso cross-origin

bucket_website.go

Hospedagem de site estático (back-to-origin baseado em espelhamento) (Go SDK V1)

bucket_encryption.go

Criptografia no lado do servidor (Go SDK V1)

bucket_requestpayment.go

Pagamento pelo solicitante (Go SDK V1)

bucket_inventory.go

Inventário de bucket (Go SDK V1)

bucket_accessmonitor.go

Rastreamento de acesso (Go SDK V1)

bucket_metaquery.go

Indexação de dados (Go SDK V1)

list_buckets.go

Listar buckets (Go SDK V1)

bucket_stat.go

Obter a capacidade de armazenamento de um bucket (Go SDK V1)

bucket_tagging.go

Tags de bucket (Go SDK V1)

put_object.go

Upload de objetos, incluindo upload simples (Go SDK V1) e upload retomável (Go SDK V1)

append_object.go

Upload por anexação

get_object.go

Download de objetos, incluindo download em streaming (Go SDK V1) e download condicional (Go SDK V1)

delete_object.go

Excluir objetos (Go SDK V1)

copy_object.go

Copiar objetos (Go SDK V1)

list_objects.go

Listar objetos (Go SDK V1)

archive.go

Restaurar objetos (Go SDK V1)

object_acl.go

Gerenciar ACLs de objeto

sign_url.go

Fazer upload de objetos usando URLs assinadas (Go SDK V1)

object_tagging.go

Tags de objeto

select_object.go

Consultar objetos (Go SDK V1)

object_meta.go

Gerenciar metadados de objeto (Go SDK V1)

livechannel.go

Gerenciamento de LiveChannel (Go SDK V1)

Consulte informações de endpoint

O OSS Go SDK V1 permite consultar informações de endpoint para todas as regiões ou para regiões específicas, incluindo endpoints públicos (IPv4), endpoints internos (rede clássica ou VPC) e endpoints de aceleração.

Nota

O Go SDK 2.2.8 e versões posteriores suportam a consulta de informações de endpoint.

package main

// Sample code for querying endpoint information in OSS Go SDK V1

import (
	"fmt"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {

	fmt.Println("=== Query endpoint information for all supported regions ===\n")

	// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, _ := oss.NewEnvironmentVariableCredentialsProvider()

	// Create an OSS client instance.
	client, err := oss.New(
		"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
		"",
		"",
		oss.SetCredentialsProvider(&provider),
		oss.AuthVersion(oss.AuthV4),
		oss.Region("cn-hangzhou"),
	)
	if err != nil {
		fmt.Printf("Failed to create client: %v\n", err)
		return
	}

	// Query endpoint information for all supported regions.
	result, err := client.DescribeRegions()
	if err != nil {
		fmt.Printf("Failed to query endpoint information: %v\n", err)
		return
	}

	// Traverse all region information.
	for _, region := range result.Regions {
		fmt.Printf("Region: %s\n", region.Region)
		fmt.Printf("  Public endpoint (IPv4): %s\n", region.InternetEndpoint)
		fmt.Printf("  Internal endpoint (classic network or VPC): %s\n", region.InternalEndpoint)
		fmt.Printf("  Acceleration endpoint (global upload and download acceleration): %s\n", region.AccelerateEndpoint)
		fmt.Println("--------------------------------------------------------------------------------")
	}

	// Print statistics.
	fmt.Printf("\nFound endpoint information for %d regions\n", len(result.Regions))
}

Para consultar informações de endpoint de uma região específica, especifique o ID da região do OSS no método DescribeRegions.

result, err := client.DescribeRegions(oss.AddParam("regions", "oss-cn-hangzhou"))

Configuração de credenciais de acesso

O OSS suporta diversos métodos de inicialização de credenciais. Escolha o método adequado aos seus requisitos de autenticação e autorização.

Clique para visualizar como selecionar credenciais de acesso

Método de inicialização do provedor de credenciais

Cenários

Requer par de AccessKey ou token STS pré-configurado

Credencial subjacente

Validade da credencial

Método de rotação ou renovação da credencial

Usar o par de AccessKey de um usuário RAM

Aplicações implantadas em ambientes seguros e estáveis, menos suscetíveis a ataques externos, que exigem acesso de longo prazo aos serviços da Alibaba Cloud sem rotação frequente de credenciais.

Sim

Par de AccessKey

Longo prazo

Rotação manual

Usar credenciais de acesso temporárias do STS

Aplicações implantadas em ambientes não confiáveis que necessitam de controle sobre o período de validade e as permissões de acesso.

Sim

Token do Security Token Service

Temporária

Renovação manual

Usar um ARN de função RAM

Aplicações que requerem acesso autorizado aos serviços da Alibaba Cloud, como acesso entre contas.

Sim

Token do Security Token Service

Temporária

Renovação automática

Usar uma função RAM de instância ECS

Aplicações implantadas em instâncias ECS da Alibaba Cloud, instâncias ECI ou nós de trabalho do Container Service for Kubernetes.

Não

Token do Security Token Service

Temporária

Renovação automática

Usar um ARN de função OIDC

Aplicações não confiáveis implantadas em nós de trabalho do Alibaba Cloud Container Service for Kubernetes.

Não

Token do Security Token Service

Temporária

Renovação automática

Usar credenciais do contexto do Function Compute

Funções de aplicações implantadas no Alibaba Cloud Function Compute.

Não

Token do Security Token Service

Temporária

Renovação desnecessária

Usar um CredentialsURI

Aplicações que precisam obter credenciais de acesso de um sistema externo.

Não

Token do Security Token Service

Temporária

Renovação automática

Usar um par de AccessKey com rotação automática

Aplicações implantadas em ambientes com risco de vazamento de par de AccessKey, que exigem rotação frequente de credenciais para acesso de longo prazo aos serviços da Alibaba Cloud.

Não

Par de AccessKey

Longo prazo

Rotação automática

Usar credenciais de acesso personalizadas

Caso nenhum dos métodos anteriores atenda aos seus requisitos, personalize a forma de obtenção de credenciais.

Personalizado

Personalizado

Personalizado

Personalizado

Use o par de AccessKey de um usuário RAM

Indicado para aplicações implantadas em ambientes seguros que necessitam de acesso prolongado ao OSS sem rotação frequente de credenciais. Inicialize o provedor de credenciais com o par de AccessKey (AccessKey ID e AccessKey secret) de uma conta Alibaba Cloud ou de um usuário RAM. Esse método exige manutenção manual do par de AccessKey, o que pode introduzir riscos de segurança.

Importante
  • Uma conta Alibaba Cloud possui permissões totais sobre os recursos. O vazamento do par de AccessKey representa um risco significativo para o seu sistema. Não recomendamos o uso do par de AccessKey de uma conta Alibaba Cloud. Use o par de AccessKey de um usuário RAM com as permissões mínimas necessárias.

  • Para criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey. O AccessKey ID e o AccessKey secret de um usuário RAM são exibidos apenas no momento da criação do par. Caso os esqueça, crie um novo par de AccessKey para substituir o antigo.

Environment variables

  1. Configure as variáveis de ambiente usando o par de AccessKey de um usuário RAM.

    Linux

    1. Execute os comandos abaixo na interface de linha de comando para anexar as definições das variáveis de ambiente ao arquivo ~/.bashrc .

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
    2. Execute o comando a seguir para aplicar as alterações.

      source ~/.bashrc
    3. Execute os comandos abaixo para verificar se as variáveis de ambiente foram configuradas corretamente.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Execute o comando abaixo no terminal para identificar o tipo de shell padrão.

      echo $SHELL
    2. Realize as operações correspondentes ao tipo de shell padrão.

      Zsh

      1. Execute os comandos abaixo para anexar as definições das variáveis de ambiente ao arquivo ~/.zshrc.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
      2. Execute o comando a seguir para aplicar as alterações.

        source ~/.zshrc
      3. Execute os comandos abaixo para verificar se as variáveis de ambiente foram configuradas corretamente.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Execute os comandos abaixo para anexar as definições das variáveis de ambiente ao arquivo ~/.bash_profile.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
      2. Execute o comando a seguir para aplicar as alterações.

        source ~/.bash_profile
      3. Execute os comandos abaixo para verificar se as variáveis de ambiente foram configuradas corretamente.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Execute os comandos abaixo no CMD.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. Execute os comandos abaixo para verificar se as variáveis de ambiente foram configuradas corretamente.

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Execute os comandos abaixo no PowerShell.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
    2. Execute os comandos abaixo para verificar se as variáveis de ambiente foram configuradas corretamente.

      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Após modificar as variáveis de ambiente do sistema, reinicie ou atualize o ambiente de compilação e execução. Isso inclui IDEs, interfaces de linha de comando, outros aplicativos de desktop e serviços de backend, garantindo que as variáveis de ambiente mais recentes sejam carregadas.

  3. Use variáveis de ambiente para transmitir as informações de credenciais.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    func main() {
    	// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Create an OSSClient instance.
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Static credentials

Para evitar codificar credenciais diretamente no código-fonte, referencie-as por meio de variáveis que leiam de variáveis de ambiente, arquivos de configuração ou outras fontes externas em tempo de execução. O exemplo abaixo usa um arquivo de configuração:

  1. Instale a biblioteca go-ini.

    go get -u github.com/go-ini/ini
  2. Crie um arquivo de configuração chamado config.ini.

    [credentials]
    alibaba_cloud_access_key_id = <ALIBABA_CLOUD_ACCESS_KEY_ID>
    alibaba_cloud_access_key_secret = <ALIBABA_CLOUD_ACCESS_KEY_SECRET>
  3. Escreva o código para ler as informações de credenciais do arquivo de configuração e inicializar o cliente OSS.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"gopkg.in/ini.v1"
    )
    
    type defaultCredentials struct {
    	config *oss.Config
    }
    
    func (defCre *defaultCredentials) GetAccessKeyID() string {
    	return defCre.config.AccessKeyID
    }
    
    func (defCre *defaultCredentials) GetAccessKeySecret() string {
    	return defCre.config.AccessKeySecret
    }
    
    func (defCre *defaultCredentials) GetSecurityToken() string {
    	return defCre.config.SecurityToken
    }
    
    type defaultCredentialsProvider struct {
    	config *oss.Config
    }
    
    func (defBuild *defaultCredentialsProvider) GetCredentials() oss.Credentials {
    	return &defaultCredentials{config: defBuild.config}
    }
    func NewDefaultCredentialsProvider(accessID, accessKey, token string) (defaultCredentialsProvider, error) {
    	var provider defaultCredentialsProvider
    	if accessID == "" {
    		return provider, fmt.Errorf("access key id is empty!")
    	}
    	if accessKey == "" {
    		return provider, fmt.Errorf("access key secret is empty!")
    	}
    	config := &oss.Config{
    		AccessKeyID:     accessID,
    		AccessKeySecret: accessKey,
    		SecurityToken:   token,
    	}
    	return defaultCredentialsProvider{
    		config,
    	}, nil
    }
    
    func main() {
    	cfg, err := ini.Load("config.ini")
    	if err != nil {
    		fmt.Println("Error loading config file:", err)
    		return
    	}
    	accessKeyID := cfg.Section("credentials").Key("alibaba_cloud_access_key_id").String()
    	accessKeySecret := cfg.Section("credentials").Key("alibaba_cloud_access_key_secret").String()
    	provider, err := NewDefaultCredentialsProvider(accessKeyID, accessKeySecret, "")
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Use credenciais de acesso temporárias do STS

Indicado para aplicações que necessitam de acesso temporário ao OSS. Inicialize o provedor de credenciais com credenciais temporárias (AccessKey ID, AccessKey secret e Security Token) obtidas via STS. Esse método exige manutenção manual do token STS. Para acessar o OSS múltiplas vezes, renove o token manualmente antes que ele expire.

Importante
  1. Defina as variáveis de ambiente usando as credenciais de identidade temporárias.

    Mac OS/Linux/Unix

    Importante
    • Use as credenciais de identidade temporárias (AccessKey ID, AccessKey secret e Security Token) obtidas via STS, e não o par de AccessKey (AccessKey ID e AccessKey secret) de um usuário RAM.

    • O AccessKey ID obtido via STS começa com "STS.", por exemplo, "STS.".

    export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>

    Windows

    Importante
    • Use as credenciais de identidade temporárias (AccessKey ID, AccessKey secret e Security Token) obtidas via STS, e não o par de AccessKey (AccessKey ID e AccessKey secret) de um usuário RAM.

    • O AccessKey ID obtido via STS começa com "STS.", por exemplo, "STS.".

    set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
  2. Transmita as informações de credenciais por meio de variáveis de ambiente.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    func main() {
    	// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are set.
    	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Create an OSSClient instance.
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Use um ARN de função RAM

Indicado para aplicações que requerem acesso autorizado ao OSS, como acesso entre contas. Inicialize o provedor de credenciais especificando o ARN de uma função RAM. A ferramenta Credentials obtém automaticamente tokens STS e os renova antes da expiração chamando a operação AssumeRole. Você também pode atribuir uma policy para restringir a função a um conjunto menor de permissões.

Importante
  • Uma conta Alibaba Cloud possui permissões totais sobre os recursos. O vazamento do par de AccessKey representa um risco significativo para o seu sistema. Não recomendamos o uso do par de AccessKey de uma conta Alibaba Cloud. Use o par de AccessKey de um usuário RAM com as permissões mínimas necessárias.

  • Para criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey. O AccessKey ID e o AccessKey secret de um usuário RAM são exibidos apenas no momento da criação do par. Salve-os imediatamente. Caso os esqueça, crie um novo par de AccessKey para substituir o antigo.

  • Para obter um ARN de função RAM, consulte Criar uma função RAM.

  1. Adicione a dependência de credenciais.

    go get github.com/aliyun/credentials-go/credentials
  2. Configure o par de AccessKey e o ARN da função RAM como credenciais de acesso.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    type Credentials struct {
    	AccessKeyId     string
    	AccessKeySecret string
    	SecurityToken   string
    }
    
    type defaultCredentialsProvider struct {
    	cred credentials.Credential
    }
    
    func (credentials *Credentials) GetAccessKeyID() string {
    	return credentials.AccessKeyId
    }
    
    func (credentials *Credentials) GetAccessKeySecret() string {
    	return credentials.AccessKeySecret
    }
    
    func (credentials *Credentials) GetSecurityToken() string {
    	return credentials.SecurityToken
    }
    
    func (defBuild *defaultCredentialsProvider) GetCredentials() oss.Credentials {
    	cred, _ := defBuild.cred.GetCredential()
    	return &Credentials{
    		AccessKeyId:     *cred.AccessKeyId,
    		AccessKeySecret: *cred.AccessKeySecret,
    		SecurityToken:   *cred.SecurityToken,
    	}
    }
    
    func NewRamRoleArnCredentialsProvider(credential credentials.Credential) defaultCredentialsProvider {
    	return defaultCredentialsProvider{
    		cred: credential,
    	}
    }
    
    func main() {
    	config := new(credentials.Config).
    		// The credential type. Set the value to ram_role_arn.
    		SetType("ram_role_arn").
    		// The AccessKey ID and AccessKey secret of the RAM user. The values are obtained from environment variables.
    		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
    		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
    		// The following operations directly use parameter values. You can also add environment variables and use os.Getenv("<variable_name>") to set the corresponding parameters.
    		// The ARN of the RAM role to assume. The value is obtained from an environment variable. Format: acs:ram::$accountID:role/$roleName.
    		SetRoleArn("ALIBABA_CLOUD_ROLE_ARN"). // The standard environment variable name for RoleArn is ALIBABA_CLOUD_ROLE_ARN.
    		// A custom name for the role session to distinguish different tokens.
    		SetRoleSessionName("ALIBABA_CLOUD_ROLE_SESSION_NAME"). // The standard environment variable name for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME.
    		// (Optional) Restrict the permissions of the STS token.
    		SetPolicy("").
    		// (Optional) Limit the validity period of the STS token.
    		SetRoleSessionExpiration(3600)
    
    	arnCredential, err := credentials.NewCredential(config)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    
    	provider := NewRamRoleArnCredentialsProvider(arnCredential)
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    
    	fmt.Printf("client:%#v\n", client)
    }

Use uma função RAM de instância ECS

Recomendado para aplicações executadas em instâncias ECS, instâncias ECI ou nós de trabalho do Container Service for Kubernetes. Uma função RAM de instância ECS associa uma função à instância, permitindo a renovação automática do token STS sem a necessidade de fornecer um par de AccessKey ou token STS. Para saber como obter uma função RAM de instância ECS, consulte Criar uma função RAM. Para saber como associar uma função a uma instância ECS, consulte Funções RAM de instância.

  1. Adicione a dependência de credenciais.

    go get github.com/aliyun/credentials-go/credentials
  2. Configure a função RAM da instância ECS como credencial de acesso.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    type Credentials struct {
    	AccessKeyId     string
    	AccessKeySecret string
    	SecurityToken   string
    }
    
    type CredentialsProvider struct {
    	cred credentials.Credential
    }
    
    func (credentials *Credentials) GetAccessKeyID() string {
    	return credentials.AccessKeyId
    }
    
    func (credentials *Credentials) GetAccessKeySecret() string {
    	return credentials.AccessKeySecret
    }
    
    func (credentials *Credentials) GetSecurityToken() string {
    	return credentials.SecurityToken
    }
    
    func (defBuild CredentialsProvider) GetCredentials() oss.Credentials {
    	cred, _ := defBuild.cred.GetCredential()
    	return &Credentials{
    		AccessKeyId:     *cred.AccessKeyId,
    		AccessKeySecret: *cred.AccessKeySecret,
    		SecurityToken:   *cred.SecurityToken,
    	}
    }
    
    func NewEcsCredentialsProvider(credential credentials.Credential) CredentialsProvider {
    	return CredentialsProvider{
    		cred: credential,
    	}
    }
    
    func main() {
    	config := new(credentials.Config).
    		// The credential type. Set the value to ecs_ram_role.
    		SetType("ecs_ram_role").
    		// (Optional) The role name. If you do not specify this parameter, OSS automatically obtains the role. We recommend that you specify the role name to reduce the number of requests.
    		SetRoleName("RoleName")
    
    	ecsCredential, err := credentials.NewCredential(config)
    	if err != nil {
    		return
    	}
    	provider := NewEcsCredentialsProvider(ecsCredential)
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    
    }

Use um ARN de função OIDC

Para aplicações não confiáveis implantadas em nós de trabalho do Container Service for Kubernetes, o recurso RAM Roles for Service Accounts (RRSA) oferece isolamento de credenciais no nível do pod. Em vez de compartilhar a função RAM da instância do nó de trabalho via serviço de metadados global, o RRSA monta um arquivo de token OIDC da conta de serviço em cada pod e injeta a configuração nas variáveis de ambiente. A ferramenta Credentials então chama a operação AssumeRoleWithOIDC para trocar o token OIDC por um token STS. Nenhum par de AccessKey ou token STS é necessário. Para mais informações, consulte Configurar permissões RAM para um ServiceAccount usando RRSA para alcançar isolamento de permissões no nível do pod.

  1. Adicione a dependência de credenciais.

    go get github.com/aliyun/credentials-go/credentials
  2. Configure a função RAM OIDC como credencial de acesso.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    type Credentials struct {
    	AccessKeyId     string
    	AccessKeySecret string
    	SecurityToken   string
    }
    
    type CredentialsProvider struct {
    	cred credentials.Credential
    }
    
    func (credentials *Credentials) GetAccessKeyID() string {
    	return credentials.AccessKeyId
    }
    
    func (credentials *Credentials) GetAccessKeySecret() string {
    	return credentials.AccessKeySecret
    }
    
    func (credentials *Credentials) GetSecurityToken() string {
    	return credentials.SecurityToken
    }
    
    func (defBuild CredentialsProvider) GetCredentials() oss.Credentials {
    	cred, _ := defBuild.cred.GetCredential()
    	return &Credentials{
    		AccessKeyId:     *cred.AccessKeyId,
    		AccessKeySecret: *cred.AccessKeySecret,
    		SecurityToken:   *cred.SecurityToken,
    	}
    }
    
    func NewOIDCRoleARNCredentialsProvider(credential credentials.Credential) CredentialsProvider {
    	return CredentialsProvider{
    		cred: credential,
    	}
    }
    
    func main() {
    	config := new(credentials.Config).
    		// The file path of the OIDC token.
    		SetOIDCTokenFilePath(os.Getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE")).
    		// The following operations directly use parameter values. You can also add environment variables and use os.Getenv("<variable_name>") to set the corresponding parameters.
    		// The credential type. Set the value to oidc_role_arn.
    		SetType("oidc_role_arn").
    		// The ARN of the OIDC provider. Format: acs:ram::account-id:oidc-provider/provider-name.
    		SetOIDCProviderArn("acs:ram::113511544585****:oidc-provider/TestOidcProvider"). // The standard environment variable name for OIDCProviderArn is ALIBABA_CLOUD_OIDC_PROVIDER_ARN.
    		// A custom name for the role session to distinguish different tokens.
    		SetRoleSessionName("role_session_name"). // The standard environment variable name for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME.
    		// The ARN of the role to assume. Format: acs:ram::113511544585****:oidc-provider/TestOidcProvider
    		SetRoleArn("acs:ram::113511544585****:role/testoidc"). // The standard environment variable name for RoleArn is ALIBABA_CLOUD_ROLE_ARN.
    		// (Optional) The policy to use when assuming the role.
    		SetPolicy("").
    		SetSessionExpiration(3600)
    	oidcCredential, err := credentials.NewCredential(config)
    	if err != nil {
    		return
    	}
    	provider := NewOIDCRoleARNCredentialsProvider(oidcCredential)
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Use credenciais do contexto do Function Compute

Indicado para funções de aplicações implantadas no Function Compute. O Function Compute obtém um token STS assumindo a função de serviço configurada para a função e o transmite através do parâmetro Credentials no contexto. Esse token STS é válido por 36 horas e não expira durante a execução da função (máximo de 24 horas), portanto, não requer renovação. Nenhum par de AccessKey ou token STS é necessário. Para obter informações sobre como conceder permissões ao Function Compute para acessar o OSS, consulte Usar uma função de papel para conceder permissões ao Function Compute para acessar outros serviços da Alibaba Cloud.

  1. Adicione as dependências do contexto do Function Compute.

    go get github.com/aliyun/fc-runtime-go-sdk/fc
    go get github.com/aliyun/fc-runtime-go-sdk/fccontext
  2. Inicialize o provedor de credenciais usando as credenciais do contexto do Function Compute.

    package main
    
    import (
    	"context"
    	"fmt"
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/fc-runtime-go-sdk/fc"
    	"github.com/aliyun/fc-runtime-go-sdk/fccontext"
    )
    
    type GetObjectContext struct {
    	OutputRoute string `json:"outputRoute"`
    	OutputToken string `json:"outputToken"`
    	InputOssUrl string `json:"inputOssUrl"`
    }
    
    type StructEvent struct {
    	GetObjectContext GetObjectContext `json:"getObjectContext"`
    }
    
    func HandleRequest(ctx context.Context, event StructEvent) error {
    	endpoint := event.GetObjectContext.OutputRoute
    	fctx, _ := fccontext.FromContext(ctx)
    	client, err := oss.New(endpoint, fctx.Credentials.AccessKeyId, fctx.Credentials.AccessKeySecret, oss.SecurityToken(fctx.Credentials.SecurityToken))
    	if err != nil {
    		return fmt.Errorf("client new error: %v", err)
    	}
    	fmt.Printf("client:%#v\n", client)
    	return nil
    }
    
    func main() {
    	fc.Start(HandleRequest)
    }

Use um CredentialsURI

Indicado para aplicações que obtêm credenciais de um sistema externo. A ferramenta Credentials recupera tokens STS da URI especificada e os renova automaticamente. Nenhum par de AccessKey ou token STS é necessário.

Importante
  • O CredentialsURI é o endereço do servidor de onde o token STS é obtido.

  • O serviço de backend que fornece a resposta do CredentialsURI deve implementar a lógica de renovação automática do token STS para garantir que a aplicação sempre obtenha credenciais válidas.

  1. Para que a ferramenta Credentials analise e use corretamente o token STS, a URI deve seguir o protocolo de resposta abaixo:

    • Código de status da resposta: 200

    • Estrutura do corpo da resposta:

      {
          "Code": "Success",
          "AccessKeySecret": "AccessKeySecret",
          "AccessKeyId": "AccessKeyId",
          "Expiration": "2021-09-26T03:46:38Z",
          "SecurityToken": "SecurityToken"
      }
  2. Adicione a dependência de credenciais.

    go get github.com/aliyun/credentials-go/credentials
  3. Configure o CredentialsURI como credencial de acesso.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    type Credentials struct {
    	AccessKeyId     string
    	AccessKeySecret string
    	SecurityToken   string
    }
    
    type CredentialsProvider struct {
    	cred credentials.Credential
    }
    
    func (credentials *Credentials) GetAccessKeyID() string {
    	return credentials.AccessKeyId
    }
    
    func (credentials *Credentials) GetAccessKeySecret() string {
    	return credentials.AccessKeySecret
    }
    
    func (credentials *Credentials) GetSecurityToken() string {
    	return credentials.SecurityToken
    }
    
    func (defBuild CredentialsProvider) GetCredentials() oss.Credentials {
    	cred, _ := defBuild.cred.GetCredential()
    	return &Credentials{
    		AccessKeyId:     *cred.AccessKeyId,
    		AccessKeySecret: *cred.AccessKeySecret,
    		SecurityToken:   *cred.SecurityToken,
    	}
    }
    
    func NewCredentialsUriCredentialsProvider(credential credentials.Credential) CredentialsProvider {
    	return CredentialsProvider{
    		cred: credential,
    	}
    }
    
    func main() {
    	config := new(credentials.Config).
    		// The credential type. Set the value to credentials_uri.
    		SetType("credentials_uri").
    		// Specify the URL address. You can also set an environment variable and use os.Getenv("<variable_name>") to pass the parameter.
    		// The standard environment variable name for URLCredential is ALIBABA_CLOUD_CREDENTIALS_URI.
    		SetURLCredential("http://127.0.0.1")
    	uriCredential, err := credentials.NewCredential(config)
    	if err != nil {
    		return
    	}
    	provider := NewCredentialsUriCredentialsProvider(uriCredential)
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Use um par de AccessKey com rotação automática

Indicado para aplicações que exigem acesso prolongado ao OSS, mas estão implantadas em ambientes com risco de vazamento de par de AccessKey. Inicialize o provedor de credenciais com uma ClientKey. O Key Management Service (KMS) rotaciona automaticamente o par de AccessKey do usuário RAM gerenciado em um cronograma periódico, transformando uma credencial estática em dinâmica. O KMS também suporta rotação imediata para substituição rápida em caso de vazamento. Para saber como obter uma ClientKey, consulte Criar um ponto de acesso de aplicação.

  1. Adicione a dependência do cliente de credenciais.

    go get -u github.com/aliyun/aliyun-secretsmanager-client-go
  2. Crie um arquivo de configuração chamado secretsmanager.properties.

    # Access credential type
    credentials_type=client_key
    
    # The password used to decrypt the client key. The password can be read from an environment variable or a file.
    client_key_password_from_env_variable=#your client key private key password environment variable name#
    client_key_password_from_file_path=#your client key private key password file path#
    
    # The path of the client key's private key file.
    client_key_private_key_path=#your client key private key file path#
    
    # The region of the associated KMS service.
    cache_client_region_id=[{"regionId":"#regionId#"}]
  3. Use o arquivo de configuração para transmitir as informações de credenciais.

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/aliyun-secretsmanager-client-go/sdk"
    )
    
    type defaultCredentials struct {
    	config *oss.Config
    }
    
    func (defCre *defaultCredentials) GetAccessKeyID() string {
    	return defCre.config.AccessKeyID
    }
    
    func (defCre *defaultCredentials) GetAccessKeySecret() string {
    	return defCre.config.AccessKeySecret
    }
    
    func (defCre *defaultCredentials) GetSecurityToken() string {
    	return defCre.config.SecurityToken
    }
    
    type defaultCredentialsProvider struct {
    	config *oss.Config
    }
    
    func (defBuild *defaultCredentialsProvider) GetCredentials() oss.Credentials {
    	return &defaultCredentials{config: defBuild.config}
    }
    func NewDefaultCredentialsProvider(accessID, accessKey, token string) (defaultCredentialsProvider, error) {
    	var provider defaultCredentialsProvider
    	if accessID == "" {
    		return provider, fmt.Errorf("access key id is empty!")
    	}
    	if accessKey == "" {
    		return provider, fmt.Errorf("access key secret is empty!")
    	}
    	config := &oss.Config{
    		AccessKeyID:     accessID,
    		AccessKeySecret: accessKey,
    		SecurityToken:   token,
    	}
    	return defaultCredentialsProvider{
    		config,
    	}, nil
    }
    
    func main() {
    	client, err := sdk.NewClient()
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	secretInfo, err := client.GetSecretInfo("#secretName#")
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("SecretValue:%s\n", secretInfo.SecretValue)
    	var m map[string]string
    	err = json.Unmarshal([]byte(secretInfo.SecretValue), &m)
    	if err != nil {
    		fmt.Println("Error decoding JSON:", err)
    		os.Exit(-1)
    	}
    	accessKeyId := m["AccessKeyId"]
    	accessKeySecret := m["AccessKeySecret"]
    	provider, err := NewDefaultCredentialsProvider(accessKeyId, accessKeySecret, "")
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	ossClient, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", ossClient)
    }

Use credenciais de acesso personalizadas

Se nenhum dos métodos anteriores atender aos seus requisitos, implemente um provedor de credenciais personalizado usando a interface Credential Providers. Se as credenciais subjacentes forem baseadas em STS, gerencie a renovação do token.

package main

import (
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type CustomerCredentialsProvider struct {
	config *oss.Config
}

func NewCustomerCredentialsProvider() CustomerCredentialsProvider {
	return CustomerCredentialsProvider{}
}

func (s CustomerCredentialsProvider) GetCredentials() oss.Credentials {
	// Return long-term credentials.
	config := &oss.Config{
		AccessKeyID:     "id",
		AccessKeySecret: "secret",
	}
	return &CustomerCredentialsProvider{
		config,
	}
	// Return temporary credentials.
	//config := &oss.Config{
	//    AccessKeyID:     "id",
	//    AccessKeySecret: "secret",
	//    SecurityToken:   "token",
	//}
	//return &CustomerCredentialsProvider{
	//    config,
	//}
}

func (s *CustomerCredentialsProvider) GetAccessKeyID() string {
	return s.config.AccessKeyID
}

func (s *CustomerCredentialsProvider) GetAccessKeySecret() string {
	return s.config.AccessKeySecret
}

func (s *CustomerCredentialsProvider) GetSecurityToken() string {
	return s.config.SecurityToken
}

func main() {
	provider := NewCustomerCredentialsProvider()
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.Printf("client:%#v\n", client)
}

Perguntas frequentes

Como solucionar o erro AccessDenied ao usar o SDK?

O erro AccessDenied geralmente indica permissões insuficientes. Siga estas etapas para solucionar o problema:

  1. Confirme o AccessKey ID e o AccessKey secret: Certifique-se de estar usando o AccessKey ID e o AccessKey secret corretos.

  2. Verifique as permissões do usuário RAM: Confirme se o usuário RAM possui as permissões necessárias para operações de bucket ou objeto.

  3. Verifique a política do bucket: Se a mensagem de erro mencionar "Access denied by bucket policy", significa que o acesso foi negado por uma política de bucket.

  4. Para mais informações sobre como consultar outros tipos de erro e solucionar problemas comuns de controle de acesso, consulte Tratamento de erros.

Referências