O Client é o cliente em Go para o Object Storage Service (OSS) e permite gerenciar recursos do OSS, como buckets e arquivos. Para enviar uma solicitação do OSS com o SDK em Go, inicialize uma instância do Client. Você também pode modificar as configurações padrão conforme necessário.
Pré-requisitos
Antes de inicializar o SDK do OSS, configure suas credenciais de acesso. Para mais informações, consulte Configure access credentials (Go SDK V1).
Crie um novo Client
V4 signature (Recommended)
Recomendamos usar o algoritmo de assinatura V4, que é mais seguro. Ao inicializar o cliente com uma assinatura V4, especifique o endpoint e o ID da região de uso geral da Alibaba Cloud. O ID da região indica a região de origem da solicitação, como cn-hangzhou. Você também deve declarar oss.AuthV4. O OSS Go SDK 3.0.2 e versões posteriores suportam assinaturas V4.
O exemplo a seguir mostra como inicializar um cliente com uma assinatura V4 usando um nome de domínio do OSS. Modifique o exemplo para outros cenários, como inicializar o cliente com um nome de domínio personalizado.
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// handleError handles unrecoverable errors, logs the error message, and terminates the program.
func handleError(err error) {
log.Fatalf("Error: %v", err)
}
// setupClient sets up and creates an OSS client instance.
// Parameters:
// endpoint - The endpoint corresponding to the Bucket.
// region - The region information corresponding to the endpoint.
//
// Returns the created OSS client instance.
func setupClient(endpoint, region string) (*oss.Client, error) {
// Obtain access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
return nil, err
}
// Create an OSSClient instance and use V4 signature.
client, err := oss.New(endpoint, "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region(region))
if err != nil {
return nil, err
}
return client, nil
}
func main() {
// Fill in yourEndpoint with the endpoint corresponding to the Bucket. For example, for China East 1 (Hangzhou), fill in https://oss-cn-hangzhou.aliyuncs.com. For other regions, fill in according to the actual situation.
endpoint := "yourEndpoint"
// Fill in yourRegion with the region information corresponding to the endpoint, for example, cn-hangzhou.
region := "yourRegion"
// Check if environment variables are set, checking both empty strings and placeholder values.
if endpoint == "" || region == "" || endpoint == "yourEndpoint" || region == "yourRegion" {
log.Fatal("Please set yourEndpoint and yourRegion with valid values.")
}
// Set up and create an OSS client instance.
client, err := setupClient(endpoint, region)
if err != nil {
handleError(err)
}
// Output client information.
log.Printf("Client: %#v\n", client)
}
V1 signature (Not recommended)
A partir de 1º de março de 2025, o Object Storage Service (OSS) da Alibaba Cloud não oferece mais a assinatura V1 para novos usuários (ou seja, novos UIDs). A partir de 1º de setembro de 2025, o OSS deixará de atualizar e manter a assinatura V1, além de não a oferecer mais para novos buckets de armazenamento de objetos. Migre para a assinatura V4 o mais rápido possível para evitar interrupções no serviço. Para mais informações, consulte Announcement.
Create a new Client using an OSS domain name
O código a seguir mostra como inicializar um cliente usando um nome de domínio do OSS. Para mais informações sobre os nomes de domínio do OSS para diferentes regiões, consulte Regions and Endpoints.
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// handleError handles unrecoverable errors, logs the error message, and terminates the program.
func handleError(err error) {
log.Fatalf("Error: %v", err)
}
// setupClient sets up and creates an OSS client instance.
// Parameters:
//
// endpoint - The endpoint corresponding to the Bucket.
//
// Returns the created OSS client instance.
func setupClient(endpoint string) (*oss.Client, error) {
// Obtain access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
return nil, err
}
// Create an OSSClient instance.
// Fill in yourRegion with the region where the Bucket is located. For example, for China East 1 (Hangzhou), fill in cn-hangzhou. For other regions, fill in according to the actual situation.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set signature version
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New(endpoint, "", "", clientOptions...)
if err != nil {
return nil, err
}
return client, nil
}
func main() {
// Fill in yourEndpoint with the endpoint corresponding to the Bucket. For example, for China East 1 (Hangzhou), fill in https://oss-cn-hangzhou.aliyuncs.com. For other regions, fill in according to the actual situation.
endpoint := "yourEndpoint"
// Check if environment variables are set.
if endpoint == "" {
log.Fatal("Please set yourEndpoint.")
}
// Set up and create an OSS client instance.
client, err := setupClient(endpoint)
if err != nil {
handleError(err)
}
// Output client information.
log.Printf("Client: %#v\n", client)
}
Create a new Client using a custom domain name
O código a seguir mostra como criar um novo Client com um nome de domínio personalizado. Para saber mais sobre como acessar o OSS usando um nome de domínio personalizado, consulte Access OSS with a custom domain name.
Você não pode usar o método ossClient.listBuckets com um nome de domínio personalizado.
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// handleError handles unrecoverable errors, logs the error message, and terminates the program.
func handleError(err error) {
log.Fatalf("Error: %v", err)
}
// setupClient sets up and creates an OSS client instance that supports CNAME.
// Parameters:
//
// endpoint - The custom domain name that is attached to the bucket.
//
// Returns the created OSS client instance.
func setupClient(endpoint string) (*oss.Client, error) {
// Obtain access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
return nil, err
}
// Create an OSSClient instance and enable CNAME support.
// Set yourRegion to the region where the bucket is located. For example, for China (Hangzhou), set it to cn-hangzhou. For other regions, use the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
clientOptions = append(clientOptions, oss.UseCname(true))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New(endpoint, "", "", clientOptions...)
if err != nil {
return nil, err
}
return client, nil
}
func main() {
// Set yourEndpoint to the custom domain name of the bucket.
// Example: "custom-domain-for-your-bucket.com".
endpoint := "yourEndpoint"
// Check if the environment variables are set.
if endpoint == "" {
log.Fatal("Please set yourEndpoint.")
}
// Set up and create an OSS client instance that supports CNAME.
client, err := setupClient(endpoint)
if err != nil {
handleError(err)
}
// Print the client information.
log.Printf("Client: %#v\n", client)
}
Configure o Client
Configure os parâmetros do Client, como proxy, tempo limite de conexão e número máximo de conexões.
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 HTTP em segundos. Valor padrão: 10 segundos. O valor 0 indica que não há tempo limite. | oss.Timeout |
ReadWriteTimeout | Tempo limite de leitura ou gravação HTTP em segundos. Valor padrão: 20 segundos. O valor 0 indica que não há tempo limite. | oss.Timeout |
IsCname | Define se um nome de domínio personalizado é usado como endpoint. Esse recurso é desativado por padrão. | oss.UseCname |
UserAgent | Define o cabeçalho User-Agent para solicitações HTTP. Valor padrão: aliyun-sdk-go. | oss.UserAgent |
ProxyHost | Define se o endereço do host e a porta do servidor proxy são ativados. Valores válidos:
| 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 é ativado. Valores válidos:
| oss.RedirectEnabled |
InsecureSkipVerify | Define se a validação de certificado SSL é ativada. Valores válidos:
| oss.InsecureSkipVerify |
IsEnableCRC | Define se a validação de dados CRC é ativada. Valores válidos:
| oss.EnableCRC |
LogLevel | Define o modo de log. Valores válidos:
| oss.SetLogLevel |
O código a seguir apresenta um exemplo de configuração:
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// handleError handles unrecoverable errors, logs the error message, and terminates the program.
func handleError(err error) {
log.Fatalf("Error: %v", err)
}
// setupClient sets up and creates an OSS client instance.
// Parameters:
//
// endpoint - The Endpoint of the bucket.
//
// Returns the created OSS client instance.
func setupClient(endpoint string) (*oss.Client, error) {
// Obtain access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
return nil, err
}
// Set the maximum number of connections to 10, the maximum number of idle connections per host to 20, and the maximum number of connections per host to 20.
conn := oss.MaxConns(10, 20, 20)
// Set the HTTP connection timeout to 20 seconds and the HTTP read/write timeout to 60 seconds.
time := oss.Timeout(20, 60)
// Specify whether to use a custom domain name as the Endpoint. The default value is false.
cname := oss.UseCname(true)
// Set the User-Agent header for HTTP requests. The default value is aliyun-sdk-go.
userAgent := oss.UserAgent("aliyun-sdk-go")
// Specify whether to enable HTTP redirection. The default value is true.
redirect := oss.RedirectEnabled(true)
// Specify whether to enable SSL certificate validation. The default value is to skip validation.
verifySsl := oss.InsecureSkipVerify(false)
// Set the address and port of the proxy server.
// proxy := oss.Proxy("yourProxyHost")
// Set the host address and port of the proxy server, and the username and password for proxy server authentication.
authProxy := oss.AuthProxy("yourProxyHost", "yourProxyUserName", "yourProxyPassword")
// Enable CRC data validation.
crc := oss.EnableCRC(true)
// Set the log mode.
logLevel := oss.SetLogLevel(oss.LogOff)
// Create an OSSClient instance.
// Set yourRegion to the region where the bucket is located. For example, for China (Hangzhou), set it to cn-hangzhou. For other regions, use the actual region.
client, err := oss.New(endpoint, "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4),
conn, time, cname, userAgent, authProxy, verifySsl, redirect, crc, logLevel)
if err != nil {
return nil, err
}
return client, nil
}
func main() {
// Set yourEndpoint to the Endpoint of the bucket. For example, for China (Hangzhou), set it to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
endpoint := "yourEndpoint"
// Check if the environment variables are set.
if endpoint == "" {
log.Fatal("Please set yourEndpoint.")
}
// Set up and create an OSS client instance.
client, err := setupClient(endpoint)
if err != nil {
handleError(err)
}
// Print the client information.
log.Printf("Client: %#v\n", client)
}
Defina o contexto da solicitação
Use o contexto da solicitação para controlar e gerenciar o ciclo de vida da solicitação e transmitir informações relacionadas ao contexto.
O código a seguir mostra como definir o contexto da solicitação. O OSS Go SDK 2.2.9 e versões posteriores suportam a definição do contexto da solicitação.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// handleError handles unrecoverable errors, logs the error message, and terminates the program.
func handleError(err error) {
log.Fatalf("Error: %v", err)
}
// uploadFile uploads a local file to an OSS bucket.
// Parameters:
//
// bucketName - The name of the bucket.
// objectName - The full path of the object. The full path does not include the bucket name.
// localFileName - The full path of the local file.
// endpoint - The Endpoint of the bucket.
//
// If the upload is successful, a success log is recorded. Otherwise, an error is returned.
func uploadFile(bucketName, objectName, localFileName, endpoint string) error {
// Obtain access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
return err
}
// Create an OSSClient instance.
// Set yourRegion to the region where the bucket is located. For example, for China (Hangzhou), set it to cn-hangzhou. For other regions, use the actual region.
client, err := oss.New(endpoint, "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
if err != nil {
return err
}
// Get the bucket.
bucket, err := client.Bucket(bucketName)
if err != nil {
return err
}
// Set the request context.
ctx := context.Background()
// Specify a timeout for the request context.
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Upload the local file to OSS.
err = bucket.PutObjectFromFile(objectName, localFileName, oss.WithContext(ctx))
if err != nil {
select {
case <-ctx.Done():
return fmt.Errorf("Request cancelled or timed out")
default:
return err
}
}
// After the file is uploaded, record the log.
log.Printf("File uploaded successfully: %s/%s", bucketName, objectName)
return nil
}
func main() {
// Set yourEndpoint to the Endpoint of the bucket. For example, for China (Hangzhou), set it to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
endpoint := "yourEndpoint"
// Specify the bucket name, for example, examplebucket.
bucketName := "examplebucket"
// Set yourObjectName to the full path of the object. The full path does not include the bucket name.
objectName := "yourObjectName"
// Set yourLocalFile to the full path of the local file.
localFileName := "yourLocalFile"
// Check if the environment variables are set.
if endpoint == "" || bucketName == "" || objectName == "" || localFileName == "" {
log.Fatal("Please set yourEndpoint, bucketName, objectName, and localFileName.")
}
// Try to upload the file. If the upload fails, handle the error.
if err := uploadFile(bucketName, objectName, localFileName, endpoint); err != nil {
handleError(err)
}
// Print a message indicating that the upload is successful.
log.Println("Upload Success!")
}