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.
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
GOPATHe 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.
No RAM console, crie um usuário RAM com um Permanent AccessKey Pair. Salve o par de AccessKey e conceda a permissão
AliyunOSSFullAccessao usuário.-
Use o par de AccessKey do usuário RAM para configurar as variáveis de ambiente.
Linux
-
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 -
Execute o comando a seguir para aplicar as alterações.
source ~/.bashrc -
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
-
Execute o comando abaixo no terminal para identificar o tipo de shell padrão.
echo $SHELL -
Realize as operações correspondentes ao tipo de shell padrão.
Zsh
-
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 -
Execute o comando a seguir para aplicar as alterações.
source ~/.zshrc -
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
-
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 -
Execute o comando a seguir para aplicar as alterações.
source ~/.bash_profile -
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
-
Execute os comandos abaixo no CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
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
-
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) -
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.
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.
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
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 |
|
Hospedagem de site estático (back-to-origin baseado em espelhamento) (Go SDK V1) |
|
|
Obter a capacidade de armazenamento de um bucket (Go SDK V1) |
|
|
Upload de objetos, incluindo upload simples (Go SDK V1) e upload retomável (Go SDK V1) |
|
|
Download de objetos, incluindo download em streaming (Go SDK V1) e download condicional (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.
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.
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.
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
-
Configure as variáveis de ambiente usando o par de AccessKey de um usuário RAM.
Linux
-
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 -
Execute o comando a seguir para aplicar as alterações.
source ~/.bashrc -
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
-
Execute o comando abaixo no terminal para identificar o tipo de shell padrão.
echo $SHELL -
Realize as operações correspondentes ao tipo de shell padrão.
Zsh
-
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 -
Execute o comando a seguir para aplicar as alterações.
source ~/.zshrc -
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
-
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 -
Execute o comando a seguir para aplicar as alterações.
source ~/.bash_profile -
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
-
Execute os comandos abaixo no CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
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
-
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) -
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)
-
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.
-
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:
-
Instale a biblioteca go-ini.
go get -u github.com/go-ini/ini -
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> -
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.
Para obter rapidamente um token STS usando a OpenAPI, consulte AssumeRole - Obter credenciais de identidade temporárias para uma função RAM.
Para obter um token STS usando um SDK, consulte Usar um token STS para acessar o OSS.
Ao gerar um token STS, especifique um tempo de expiração. O token torna-se inválido após expirar e não pode ser reutilizado.
Para obter a lista de endpoints do STS, consulte Endpoints.
-
Defina as variáveis de ambiente usando as credenciais de identidade temporárias.
Mac OS/Linux/Unix
ImportanteUse 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
ImportanteUse 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> -
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.
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.
-
Adicione a dependência de credenciais.
go get github.com/aliyun/credentials-go/credentials -
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.
-
Adicione a dependência de credenciais.
go get github.com/aliyun/credentials-go/credentials -
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.
-
Adicione a dependência de credenciais.
go get github.com/aliyun/credentials-go/credentials -
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.
-
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 -
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.
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.
-
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" }
-
Adicione a dependência de credenciais.
go get github.com/aliyun/credentials-go/credentials -
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.
-
Adicione a dependência do cliente de credenciais.
go get -u github.com/aliyun/aliyun-secretsmanager-client-go -
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#"}] -
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:
Confirme o AccessKey ID e o AccessKey secret: Certifique-se de estar usando o AccessKey ID e o AccessKey secret corretos.
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.
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.
Para mais informações sobre como consultar outros tipos de erro e solucionar problemas comuns de controle de acesso, consulte Tratamento de erros.