GitHub | Guia do desenvolvedor do OSS Go SDK V2 | API do OSS SDK for Go
Início rápido
Preparação do ambiente
Requer Go 1,18 ou versão posterior.
Verifique sua versão do Go com go -version . Se o Go não estiver instalado ou for anterior à versão 1,18, instale o Go .
Instalar o SDK
-
Crie um diretório de projeto e inicialize o módulo Go.
mkdir oss-go-example && cd oss-go-example && go mod init oss-go-example -
Instale o pacote do SDK (recomenda-se a versão mais recente).
go get github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss -
Importe o pacote do SDK.
import "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
Configurar credenciais de acesso
Use o AccessKey de um usuário RAM para configurar as credenciais de acesso.
No console do RAM, crie um usuário RAM com Access By Using Permanent AccessKey, salve o par de AccessKey e conceda a permissão
AliyunOSSFullAccess.-
Use o AccessKey do usuário RAM para configurar as variáveis de ambiente.
Linux
-
Anexe as 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-
Aplique as alterações.
source ~/.bashrc -
Verifique se as variáveis de ambiente foram definidas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Verifique seu shell padrão.
echo $SHELL-
Configure as variáveis de ambiente conforme o seu shell.
Zsh
-
Anexe as 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 -
Aplique as alterações.
source ~/.zshrc -
Verifique se as variáveis de ambiente foram definidas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Anexe as 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 -
Aplique as alterações.
source ~/.bash_profile -
Verifique se as variáveis de ambiente foram definidas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Execute os comandos a seguir no CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Verifique se as variáveis de ambiente foram definidas.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
Execute os comandos a seguir 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)-
Verifique se as variáveis de ambiente foram definidas.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
Inicializar o cliente
Devido a uma alteração de política para melhorar a conformidade e a segurança, a partir de 20 de março de 2025, novos usuários do OSS devem usar um nome de domínio personalizado (CNAME) para executar operações de API de dados em buckets do OSS localizados em regiões da China continental. Os endpoints públicos padrão têm restrições para essas operações. Consulte o anúncio oficial para obter a lista completa das operações afetadas. Se você acessar seus dados via HTTPS, é obrigatório vincular um certificado SSL válido ao seu domínio personalizado. Isso é obrigatório para acesso ao Console do OSS, pois o console impõe o uso de HTTPS.
Antes de executar o código de exemplo, substitua os espaços reservados, como<region-id>, pelos valores reais de regiões e endpoints , por exemplo,ap-southeast-1.
package main
import (
"context"
"log"
"strings"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
/*
Go SDK V2 client initialization configuration:
1. Signature version: Go SDK V2 uses v4 signatures by default to provide enhanced security.
2. Region configuration: You must specify an Alibaba Cloud region ID to identify the request region.
3. Endpoint configuration:
- You can use the endpoint parameter to specify a custom domain name for service requests.
- If this parameter is not specified, the SDK automatically constructs a public endpoint based on the region information.
4. Protocol configuration:
- The SDK uses the HTTPS protocol by default to construct endpoints.
- To use HTTP, you must specify an endpoint that starts with http://.
*/
func main() {
// Method 1: Specify only the region (recommended).
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>") // Specify the region where the bucket is located.
// Method 2: Specify both the region and the endpoint.
// cfg := oss.LoadDefaultConfig().
// WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
// WithRegion("<region-id>"). // Specify the region where the bucket is located.
// WithEndpoint("<endpoint>") // Specify the public endpoint of the region where the bucket is located.
// Create an OSS client.
client := oss.NewClient(cfg)
// Create the upload body.
body := strings.NewReader("hi oss")
// Create a request to upload the object.
request := &oss.PutObjectRequest{
Bucket: oss.Ptr("Your Bucket Name"), // The name of the bucket.
Key: oss.Ptr("Your Object Key"), // The name of the object.
Body: body, // The string content to upload.
}
// Send the request to upload the object.
result, err := client.PutObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put object %v", err)
}
// Print the result of the upload operation.
log.Printf("Status: %#v\n", result.Status)
log.Printf("RequestId: %#v\n", result.ResultCommon.Headers.Get("X-Oss-Request-Id"))
log.Printf("ETag: %#v\n", *result.ETag)
}
Saída esperada em caso de sucesso:
Status: "200 OK"
RequestId: "68746C5FE001B434303B90B6"
ETag: "B22E0DC370A7F7067FACF5F75D7FA385"
Configuração do cliente
Nomes de domínio personalizados
Vincule um nome de domínio personalizado para habilitar a pré-visualização de arquivos baseada em navegador e a aceleração de CDN.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pela sua região e endpoint , como ouap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Specify the region where the bucket is located.
// Specify your custom domain name, for example, https://www.example-***.com
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>").
WithEndpoint("https://www.example-***.com").
WithUseCName(true) // Set this parameter to true to use a custom domain name via CNAME.
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client to perform subsequent operations...
}
Controle de tempo limite
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pela sua região e endpoint , como ouap-southeast-1.
package main
import (
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>"). // The region where your bucket is located.
WithConnectTimeout(10 * time.Second). // Connection timeout. Defaults to 5s.
WithReadWriteTimeout(30 * time.Second) // Read/write timeout. Defaults to 10s.
// Create the OSS client.
client := oss.NewClient(cfg)
// Use the client to perform further operations...
}
Número máximo de tentativas
Por padrão, o OSSClient tenta novamente solicitações com falha 3 vezes.
Use WithRetryMaxAttempts para aumentar as tentativas em cenários de alta concorrência ou rede instável.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pela região e endpoint , como ouap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>"). // Specifies the bucket's region.
WithRetryMaxAttempts(5) // Sets the maximum number of retry attempts. The default is 3.
// Create an OSSClient instance.
client := oss.NewClient(cfg)
// Use the client for subsequent operations...
}
Protocolo HTTP/HTTPS
Use WithDisableSSL(true) para alternar de HTTPS para HTTP.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pela região e endpoint reais, como ouap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>"). // Specify the region where the bucket is located.
WithDisableSSL(true) // Disable the HTTPS protocol, which is enabled by default.
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client for subsequent operations...
}
Servidor proxy
Use WithProxyHost para rotear solicitações por um servidor proxy.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pela região e endpoint , comoap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>"). // Specify the region where the bucket is located.
WithUserAgent("aliyun-sdk-go"). // Set the user agent for the HTTP User-Agent header.
WithProxyHost("http://user:passswd@proxy.example-***.com") // Set the proxy server, e.g., "http://user:passswd@proxy.example-***.com".
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client to perform subsequent operations...
}
Endpoint interno
Use um endpoint interno quando sua aplicação for executada em uma instância ECS na mesma região do bucket para reduzir custos e latência.
Antes de executar o código de exemplo, substitua espaços reservados como<region-id>pela sua Região e Endpoint , como ouap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main()
// Method 1: Specify the region and set WithUseInternalEndpoint to true.
// Specify the region where the bucket is located.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>").
WithUseInternalEndpoint(true)
// Method 2: Directly specify the region and endpoint.
// Specify the internal endpoint corresponding to the bucket's region.
// cfg := oss.LoadDefaultConfig().
// WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
// WithRegion("<region-id>").
// WithEndpoint("<endpoint>")
// Create an OSS client.
client := oss.NewClient(cfg)
// Use this client for further operations.
}
Endpoint acelerado
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pelo ID da sua região e endpoint , comoap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Method 1: Specify the region and set WithUseAccelerateEndpoint to true.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>").
WithUseAccelerateEndpoint(true)
// Method 2: Directly specify the region and endpoint.
// cfg := oss.LoadDefaultConfig().
// WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
// WithRegion("<region-id>").
// WithEndpoint("https://oss-accelerate.aliyuncs.com").
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client to perform operations...
}
Domínio privado
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pelo ID correto com base na sua região e endpoint , comoap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Specify the region that contains the bucket.
// Specify your private domain. Example: https://service.corp.example.com
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>").
WithEndpoint("https://service.corp.example.com")
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client to perform subsequent operations...
}
Endpoints da nuvem governamental
O exemplo a seguir mostra como configurar o cliente OSS para usar endpoints da nuvem governamental.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Specify the region where the bucket is located and its corresponding internal endpoint.
// For example, for the China North 2 Ali Gov 1 region, set Region to "cn-north-2-gov-1" and Endpoint to "https://oss-cn-north-2-gov-1-internal.aliyuncs.com".
// To use the HTTP protocol, use the HTTP endpoint: "http://oss-cn-north-2-gov-1-internal.aliyuncs.com".
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("cn-north-2-gov-1").
WithEndpoint("https://oss-cn-north-2-gov-1-internal.aliyuncs.com")
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client to perform further operations...
}
Acessar buckets do CloudBox
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pela região e endpoint reais, comoap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Method 1: Automatically detect the CloudBox ID.
// Specify the region where the bucket is located.
// Set the endpoint to the data domain name of the CloudBox bucket. Example: http://cb-xxxxxx.<region-id>.oss-cloudbox.aliyuncs.com
// Set WithEnableAutoDetectCloudBoxId to true to automatically detect the CloudBox ID.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithEndpoint("http://cb-xxxxxx.<region-id>.oss-cloudbox.aliyuncs.com").
WithEnableAutoDetectCloudBoxId(true)
// Method 2: Manually set the CloudBox ID.
// Specify the region where the bucket is located.
// Set the endpoint to the data domain name of the CloudBox bucket. Example: http://cb-xxxxxx.<region-id>.oss-cloudbox.aliyuncs.com
// Specify the CloudBox ID manually. Example: cb-xxxxxx
// cfg := oss.LoadDefaultConfig().
// WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
// WithEndpoint("http://cb-xxxxxx.<region-id>.oss-cloudbox.aliyuncs.com").
// WithCloudBoxId("cb-xxxxxx")
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client for OSS operations...
}
Personalizar o cliente HTTP
Use WithHTTPClient para substituir o cliente HTTP padrão quando os parâmetros padrão forem insuficientes.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pela sua região e endpoint reais, como ouap-southeast-1.
package main
import (
"crypto/tls"
"net/http"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/transport"
)
func main() {
// Common timeout or other settings.
transConfig := transport.Config{
// The connection timeout. Default: 5 seconds.
ConnectTimeout: oss.Ptr(10 * time.Second),
// The timeout for reading data from and writing data to a connection. Default: 10 seconds.
ReadWriteTimeout: oss.Ptr(20 * time.Second),
// The idle connection timeout. Default: 50 seconds.
IdleConnectionTimeout: oss.Ptr(40 * time.Second),
// The keep-alive timeout for a network connection. Default: 30 seconds.
KeepAliveTimeout: oss.Ptr(40 * time.Second),
// Enables HTTP redirection. Disabled by default.
EnabledRedirect: oss.Ptr(true),
}
// http.Transport settings.
var transports []func(*http.Transport)
// The maximum number of connections. Default: 100.
transports = append(transports, transport.MaxConnections(200))
// The maximum time to wait for a server's first response header after the request headers are written if the request has an 'Expect: 100-Continue' header. Default: 1 second.
transports = append(transports, transport.ExpectContinueTimeout(2*time.Second))
// The minimum TLS version. Default: TLS 1.2.
transports = append(transports, transport.TLSMinVersion(tls.VersionTLS13))
// Skips certificate verification. The default is false (certificates are verified).
transports = append(transports, transport.InsecureSkipVerify(true))
// For more transport parameters, see https://pkg.go.dev/net/http#Transport.
// Create a custom HTTP client.
customClient := transport.NewHttpClient(&transConfig, transports...)
cfg := oss.LoadDefaultConfig().
WithHttpClient(customClient).
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>")
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client to perform subsequent operations...
}
Configuração de credenciais de acesso
Escolha um método de credencial adequado às suas necessidades de autenticação.
Usar o AK de um usuário RAM
Para acesso de longo prazo em ambientes seguros, inicialize um provedor de credenciais com o par de AccessKey de um usuário RAM (AccessKey ID e AccessKey secret). O gerenciamento manual de chaves aumenta os riscos de segurança.
Uma conta Alibaba Cloud possui permissões totais. Um par de AccessKey vazado representa um grande risco de segurança. Use o par de AccessKey de um usuário RAM com as permissões mínimas necessárias.
Crie um AccessKey para o usuário RAM. O AccessKey ID e o secret são exibidos apenas no momento da criação. Salve-os imediatamente — se perdidos, crie um novo par.
Variáveis de ambiente
-
Defina as variáveis de ambiente usando o par de AccessKey de um usuário RAM.
Após definir as variáveis de ambiente, reinicie sua IDE, terminal e quaisquer aplicações em execução para carregá-las.
-
Carregue as credenciais a partir das variáveis de ambiente.
Antes de executar este código de exemplo, substitua o espaço reservado
<region-id>pela sua região e endpoint reais, como ouap-southeast-1.package main import ( "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) func main() { // Set the region based on your requirements. region := "<region-id>" // Load access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. provider := credentials.NewEnvironmentVariableCredentialsProvider() // Load the default configuration, and then set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Credenciais estáticas
Codifique as credenciais estáticas diretamente na sua aplicação.
Não incorpore credenciais de acesso no código da aplicação para ambientes de produção. Este método destina-se apenas a fins de teste.
Antes de executar este código de exemplo, substitua o espaço reservado<region-id>pela sua região e endpoint reais, como ouap-southeast-1.
package main
import (
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Set the region based on your requirements.
region := "<region-id>"
// Specify the AccessKey ID and AccessKey secret of the RAM user.
accessKeyID := "yourAccessKeyID"
accessKeySecret := "yourAccessKeySecret"
// Use the NewStaticCredentialsProvider method to directly set the AccessKey ID and AccessKey secret.
provider := credentials.NewStaticCredentialsProvider(accessKeyID, accessKeySecret)
// Load the default configuration, and then set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(provider).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
log.Printf("ossclient: %v", client)
}
Credenciais de acesso temporário STS
Para acesso temporário ao OSS, inicialize um provedor de credenciais com credenciais STS (AccessKey ID, AccessKey secret e token de segurança). Você deve gerenciar a atualização do token manualmente.
Obtenha credenciais de acesso temporário chamando AssumeRole - Obter credenciais de acesso temporário para uma função.
Obtenha credenciais de acesso temporário com um SDK: Usar credenciais de acesso temporário STS para acessar o OSS.
Os tokens STS expiram após a duração especificada por você. Tokens expirados não podem ser utilizados.
Para obter uma lista de endpoints do serviço STS, consulte Endpoints de Serviço.
Variáveis de ambiente
-
Defina as variáveis de ambiente com suas credenciais de acesso temporário.
Mac OS X/Linux/Unix
AvisoEssas credenciais são as credenciais de acesso temporário STS (AccessKey ID, AccessKey secret e token de segurança), não o par de AccessKey de um usuário RAM.
Um AccessKey ID proveniente do 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
AvisoEssas credenciais são as credenciais de acesso temporário STS (AccessKey ID, AccessKey secret e token de segurança), não o par de AccessKey de um usuário RAM.
Um AccessKey ID proveniente do 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> -
Carregue as credenciais a partir das variáveis de ambiente.
Antes de executar o código de exemplo, substitua o espaço reservado
<region-id>por uma região e endpoint reais, como ouap-southeast-1.package main import ( "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) func main() { // Set the region based on your requirements. region := "<region-id>" // Load access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are set. provider := credentials.NewEnvironmentVariableCredentialsProvider() // Load the default configuration, and then set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Credenciais estáticas
Você pode codificar credenciais de acesso temporário diretamente na sua aplicação.
Não incorpore credenciais de acesso no código de produção. Este método destina-se apenas a testes.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>por uma região e endpoint reais, como ouap-southeast-1.
package main
import (
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Set the region based on your requirements.
region := "<region-id>"
// Use the temporary access credentials (AccessKey ID, AccessKey secret, and security token) from STS.
// Do not use the credentials of a RAM user.
// Note that an AccessKey ID from STS starts with `STS.`.
accessKeyID := "STS.****************"
accessKeySecret := "yourAccessKeySecret"
// Specify the STS security token.
stsToken := "yourSecurityToken"
// Use the NewStaticCredentialsProvider method to directly set the AccessKey ID, AccessKey secret, and STS token.
provider := credentials.NewStaticCredentialsProvider(accessKeyID, accessKeySecret, stsToken)
// Load the default configuration, and then set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(provider).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
log.Printf("ossclient: %v", client)
}
Usar RAMRoleARN
Para acesso entre contas ou delegado ao OSS, use RAMRoleARN. A ferramenta Credentials obtém e atualiza automaticamente os tokens STS via AssumeRole. Use o parâmetro policy para restringir permissões.
Uma conta Alibaba Cloud possui permissões totais. Uma chave de acesso vazada representa um grande risco de segurança. Use a chave de acesso de um usuário RAM com as permissões mínimas necessárias.
Crie uma chave de acesso para o usuário RAM. O ID e o secret da chave de acesso são exibidos apenas no momento da criação. Salve-os imediatamente — se perdidos, crie um novo par.
Crie uma função para obter um RAMRoleARN.
-
Adicione a dependência de credenciais.
go get github.com/aliyun/credentials-go/credentials -
Configure as credenciais de acesso.
Antes de executar o código de exemplo, substitua o espaço reservado
<region-id>por uma região real, como ouap-southeast-1.package main import ( "context" "log" "os" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" openapicred "github.com/aliyun/credentials-go/credentials" ) func main() { // Set the region based on your requirements. region := "<region-id>" config := new(openapicred.Config). // Specify the credential type. This value must be ram_role_arn. SetType("ram_role_arn"). // Obtain the access key ID and access key secret for the RAM user from environment variables. SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")). SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")). // The following parameters are set with placeholder strings. In a production environment, you should load these values from a secure source, such as environment variables. // Specify the ARN of the RAM role to assume. The format is acs:ram::$accountID:role/$roleName. SetRoleArn("ALIBABA_CLOUD_ROLE_ARN"). // The conventional environment variable for RoleArn is ALIBABA_CLOUD_ROLE_ARN. // Specify a custom role session name to distinguish between different tokens. SetRoleSessionName("ALIBABA_CLOUD_ROLE_SESSION_NAME"). // The conventional environment variable for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME. // (Optional) Restrict the permissions of the STS token. SetPolicy("Policy"). // (Optional) Specify the validity period of the STS token. SetRoleSessionExpiration(3600) arnCredential, gerr := openapicred.NewCredential(config) provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) { if gerr != nil { return credentials.Credentials{}, gerr } cred, err := arnCredential.GetCredential() if err != nil { return credentials.Credentials{}, err } return credentials.Credentials{ AccessKeyID: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, }, nil }) // Load the default configuration, and set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Usar um ECSRAMRole
Para aplicações em ECS, ECI ou nós de trabalho do Container Service for Kubernetes, use ECSRAMRole. Ele atualiza automaticamente os tokens STS para ECS, ECI ou nós de trabalho do Container Service for Kubernetes, eliminando o gerenciamento manual de credenciais. Crie uma função antes de prosseguir.
-
Adicione a dependência de credenciais.
go get github.com/aliyun/credentials-go/credentials -
Configure as credenciais de acesso.
Antes de executar o código de exemplo, substitua o espaço reservado
<region-id>pela sua região e endpoint , como ouap-southeast-1.package main import ( "context" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" openapicred "github.com/aliyun/credentials-go/credentials" ) func main() { // Set the region. region := "<region-id>" config := new(openapicred.Config). // Specify the credential type. Set the value to ecs_ram_role. SetType("ecs_ram_role"). // (Optional) Specify the role name. If omitted, the OSS client automatically discovers one. Specifying the role name is recommended to reduce requests. SetRoleName("RoleName") arnCredential, gerr := openapicred.NewCredential(config) provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) { if gerr != nil { return credentials.Credentials{}, gerr } cred, err := arnCredential.GetCredential() if err != nil { return credentials.Credentials{}, err } return credentials.Credentials{ AccessKeyID: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, }, nil }) // Load the default configuration and set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Usar OIDCRoleARN
Para aplicações não confiáveis em nós de trabalho do Container Service for Kubernetes (ACK), use RRSA baseado em OIDC para impor o princípio do menor privilégio no nível do pod. O ACK monta um arquivo de token OIDC por pod, e a ferramenta Credentials chama AssumeRoleWithOIDC para obter tokens STS automaticamente. Use RRSA para configurar permissões RAM para uma conta de serviço e isolar permissões de pods.
-
Adicione a dependência de credenciais.
go get github.com/aliyun/credentials-go/credentials -
Configure as credenciais de acesso.
Antes de executar o código de exemplo, substitua o espaço reservado
<region-id>pela sua região e endpoint , como ouap-southeast-1.package main import ( "context" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" openapicred "github.com/aliyun/credentials-go/credentials" ) func main() { // Specify the region. region := "<region-id>" config := new(openapicred.Config). // The credential type. Must be "oidc_role_arn". SetType("oidc_role_arn"). // Specify the ARN of the OIDC provider. The format is acs:ram::account-id:oidc-provider/provider-name. SetOIDCProviderArn("OIDCProviderArn"). // Specify the path to the OIDC token file. SetOIDCTokenFilePath("OIDCTokenFilePath"). // Specify a custom role session name to distinguish between tokens. SetRoleSessionName("RoleSessionName"). // The default environment variable for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME. // (Optional) Specify the policy to use when assuming the role. SetPolicy("Policy"). // The ARN of the ram role to assume, in the format acs:ram::account-id:role/role-name. SetRoleArn("RoleArn"). // The session duration in seconds. SetSessionExpiration(3600) arnCredential, gerr := openapicred.NewCredential(config) provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) { if gerr != nil { return credentials.Credentials{}, gerr } cred, err := arnCredential.GetCredential() if err != nil { return credentials.Credentials{}, err } return credentials.Credentials{ AccessKeyID: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, }, nil }) // Load the default configuration and set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Provedor de credenciais personalizado
Implemente um provedor personalizado se os métodos padrão não atenderem aos seus requisitos.
-
Use a interface credentials.CredentialsProviderFunc
Antes de executar o código de exemplo, substitua o espaço reservado
<region-id>por uma região e endpoint válidos, comoap-southeast-1.package main import ( "context" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) func main() { // Set the region based on your requirements. region := "<region-id>" // Create a custom credential provider. provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) { // Return long-term credentials. return credentials.Credentials{AccessKeyID: "id", AccessKeySecret: "secret"}, nil // Return temporary credentials. //return credentials.Credentials{AccessKeyID: "id", AccessKeySecret: "secret", SecurityToken: "token"}, nil }) // Load the default configuration and set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) } -
Implemente a interface credentials.CredentialsProvider
Antes de executar o código de exemplo, substitua o espaço reservado
<region-id>por uma região e endpoint válidos, comoap-southeast-1.package main import ( "context" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) type CustomerCredentialsProvider struct { // TODO } func NewCustomerCredentialsProvider() CustomerCredentialsProvider { return CustomerCredentialsProvider{} } func (s CustomerCredentialsProvider) GetCredentials(_ context.Context) (credentials.Credentials, error) { // Return long-term credentials. return credentials.Credentials{AccessKeyID: "id", AccessKeySecret: "secret"}, nil // Return temporary credentials. //return credentials.Credentials{AccessKeyID: "id", AccessKeySecret: "secret", SecurityToken: "token"}, nil } func main() { // Set the region based on your requirements. region := "<region-id>" // Create a custom credential provider. provider := NewCustomerCredentialsProvider() // Load the default configuration and set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Usar a cadeia de provedores de credenciais padrão
Se nenhum parâmetro for fornecido, o SDK usa a cadeia de provedores de credenciais padrão para encontrar credenciais automaticamente.
Antes de executar o código de exemplo, substitua o espaço reservado<region-id>pela sua região e endpoint , como ouap-southeast-1.
package main
import (
"context"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
osscred "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
"github.com/aliyun/credentials-go/credentials"
)
func main() {
// Set the region based on your requirements.
region := "<region-id>"
// Passing nil uses the default credential provider chain to find credentials.
arnCredential, gerr := credentials.NewCredential(nil)
provider := osscred.CredentialsProviderFunc(func(ctx context.Context) (osscred.Credentials, error) {
if gerr != nil {
return osscred.Credentials{}, gerr
}
cred, err := arnCredential.GetCredential()
if err != nil {
return osscred.Credentials{}, err
}
return osscred.Credentials{
AccessKeyID: *cred.AccessKeyId,
AccessKeySecret: *cred.AccessKeySecret,
SecurityToken: *cred.SecurityToken,
}, nil
})
// Load the default configuration and set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(provider).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
log.Printf("ossclient: %v", client)
}
Solução de problemas
Os erros do OSS incluem um código de status HTTP, mensagem, ID de solicitação e código de erro EC. Use o código EC para identificar a causa raiz.
-
Por exemplo, ao usar o código abaixo para baixar um objeto inexistente:
package main import ( "context" "flag" "io" "log" "os" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) // Define global variables. var ( region string // The region where the bucket is located. bucketName string // The name of the bucket. objectName string // The name of the object. ) // The init function initializes command-line parameters. func init() { flag.StringVar(®ion, "region", "", "The region in which the bucket is located.") flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.") flag.StringVar(&objectName, "object", "", "The name of the object.") } func main() { // Parse command-line parameters. flag.Parse() // Check if the bucket name is empty. if len(bucketName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, bucket name required") } // Check if the region is empty. if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region required") } // Check if the object name is empty. if len(objectName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, object name required") } // Define the output file path. outputFile := "downloaded.txt" // Replace this with the desired file path. // Load the default configuration and set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) // Create a request to get the object. request := &oss.GetObjectRequest{ Bucket: oss.Ptr(bucketName), // The name of the bucket. Key: oss.Ptr(objectName), // The name of the object. } // Get the object and process the result. result, err := client.GetObject(context.TODO(), request) if err != nil { log.Fatalf("failed to get object %v", err) } defer result.Body.Close() // Ensure the response body is closed when the function finishes. // Read the entire object content at once. data, err := io.ReadAll(result.Body) if err != nil { log.Fatalf("failed to read object %v", err) } // Write the content to the file. err = os.WriteFile(outputFile, data, 0644) if err != nil { log.Fatalf("failed to write to output file %v", err) } log.Printf("file downloaded successfully to %s", outputFile) } -
A seguir, um exemplo de mensagem de erro retornada. Ela inclui o código de erro EC 'EC': '0026-00000001', que identifica exclusivamente a causa do erro.
2025/03/07 15:13:46 failed to get object operation error GetObject: Error returned by Service. Http Status Code: 404. Error Code: NoSuchKey. Request Id: 67CA9CAADC44E03938AD91F0. Message: The specified key does not exist.. EC: 0026-00000001. Timestamp: 2025-03-07 07:13:46 +0000 UTC. Request Endpoint: GET https://xxx.oss-cn-hangzhou.aliyuncs.com/asdgkhfk. -
Para solucionar o erro usando o código de erro EC do exemplo, siga estas etapas:
Na caixa de pesquisa, insira o código de erro EC, como 0026-00000001. Em seguida, cole a mensagem de erro que contém o ID da solicitação na caixa de texto e clique em Diagnose.
O diagnóstico mostra a causa do erro e a solução. Para o código de erro EC
0026-00000001: o objeto alvo não existe. As possíveis causas incluem falha no upload, exclusão por regra de ciclo de vida, exclusão por outro usuário ou sincronização de replicação entre regiões. Verifique o objeto com HeadObject, confira as versões com ListObjectVersions e revise as convenções de nomenclatura, regras de ciclo de vida, permissões e regras de replicação. Erros relacionados: NoSuchKey e NoSuchVersion.
Código de exemplo
Códigos de exemplo e arquivos fonte disponíveis:
|
Descrição |
Arquivo de exemplo |
|
- |
|
|
- |
|
|
- |
|
|
- |