O Client é o cliente Go para o Object Storage Service (OSS) e permite gerenciar recursos do OSS, como buckets e arquivos. Para enviar uma solicitação ao OSS com o Go SDK, inicialize uma instância de Client. Você também pode modificar as configurações padrão conforme necessário.
Pré-requisitos
Antes de inicializar o OSS SDK, configure suas credenciais de acesso. Para mais informações, consulte Configurar credenciais de acesso (Go SDK V1).
Criar um novo Client
V4 signature (Recommended)
Recomendamos o uso do algoritmo de assinatura V4, que oferece maior segurança. Ao inicializar o cliente com a assinatura V4, especifique o Endpoint e o ID da região de uso geral da Alibaba Cloud. O ID da região indica a origem da solicitação, por exemplo, cn-hangzhou. Declare também oss.AuthV4. As assinaturas V4 têm suporte no OSS Go SDK 3.0.2 e versões posteriores.
O exemplo a seguir demonstra como inicializar um cliente com assinatura V4 usando um nome de domínio do OSS. Adapte o exemplo para outros cenários, como a inicialização do 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)
Criar um novo Client usando um nome de domínio do OSS
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 em diferentes regiões, consulte Regiões e 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)
}
Criar um novo Client usando um nome de domínio personalizado
O código a seguir ilustra a criação de um novo Client com um nome de domínio personalizado. Para obter detalhes sobre como acessar o OSS com um nome de domínio personalizado, consulte Acessar o OSS com um nome de domínio personalizado.
Não é possível 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)
}
Configurar o Client
Defina parâmetros para o Client, incluindo 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 | Limite de conexões ociosas por host. Valor padrão: 100. | oss.MaxConns |
MaxConnsPerHost | Quantidade máxima de conexões por host. O valor padrão é vazio. | oss.MaxConns |
ConnectTimeout | Tempo limite HTTP em segundos. Valor padrão: 10 segundos. O valor 0 indica ausência de tempo limite. | oss.Timeout |
ReadWriteTimeout | Duração máxima para leitura ou escrita HTTP, em segundos. Valor padrão: 20 segundos. Defina como 0 para desativar o tempo limite. | oss.Timeout |
IsCname | Define se um nome de domínio personalizado será usado como Endpoint. Este recurso vem desativado por padrão. | oss.UseCname |
UserAgent | Configura o cabeçalho User-Agent nas solicitações HTTP. Valor padrão: aliyun-sdk-go. | oss.UserAgent |
ProxyHost | Indica se o endereço e a porta do servidor proxy devem ser ativados. Valores válidos:
| oss.AuthProxy |
ProxyUser | Nome de usuário para autenticação no servidor proxy. | oss.AuthProxy |
ProxyPassword | Senha necessária para autenticar no servidor proxy. | oss.AuthProxy |
RedirectEnabled | Controla a ativação do redirecionamento HTTP. Valores válidos:
| oss.RedirectEnabled |
InsecureSkipVerify | Determina se a validação de certificado SSL deve ser aplicada. Valores válidos:
| oss.InsecureSkipVerify |
IsEnableCRC | Especifica se a verificação de dados CRC estará ativa. Valores válidos:
| oss.EnableCRC |
LogLevel | Define o modo de log. Valores válidos:
| oss.SetLogLevel |
Veja abaixo 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)
}
Definir o contexto da solicitação
Use o contexto da solicitação para controlar e gerenciar seu ciclo de vida, além de transmitir informações relacionadas ao contexto.
O trecho de código a seguir mostra como configurar o contexto da solicitação. Essa funcionalidade está disponível apenas no OSS Go SDK 2.2.9 ou superior.
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!")
}