Todos los productos
Search
Centro de documentos

:Configurar un cliente (Go SDK V1)

Última actualización: Sep 25, 2026

El Client es el cliente de Go para Object Storage Service (OSS). Con él se gestionan los recursos de OSS, como buckets y archivos. Para enviar una solicitud a OSS con el SDK de Go, debe inicializar una instancia de Client. También puede modificar la configuración predeterminada según sus necesidades.

Requisitos previos

Antes de inicializar el SDK de OSS, configure sus credenciales de acceso. Para obtener más información, consulte Configure access credentials (Go SDK V1).

Crear un nuevo Client

Firma V4 (recomendada)

Se recomienda usar el algoritmo de firma V4, ya que es más seguro. Cuando inicialice el cliente con una firma V4, especifique el endpoint y el identificador de región de propósito general de Alibaba Cloud. Este identificador indica la región desde donde se origina la solicitud; por ejemplo, cn-hangzhou. Además, debe declarar oss.AuthV4. Las firmas V4 son compatibles con OSS Go SDK 3.0.2 y versiones posteriores.

A continuación se muestra cómo inicializar un cliente con firma V4 mediante un nombre de dominio de OSS. Puede adaptar este ejemplo a otros escenarios, como inicializar el cliente con un nombre de dominio 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)
}

Firma V1 (no recomendada)

Importante

A partir del 1 de marzo de 2025, Alibaba Cloud Object Storage Service (OSS) dejó de ofrecer la firma V1 a los nuevos usuarios (es decir, a los UID nuevos). Desde el 1 de septiembre de 2025, OSS dejará de actualizar y mantener la firma V1, y ya no estará available para los nuevos buckets de object storage. Cambie a la firma V4 lo antes posible para evitar interrupciones en el servicio. Para obtener más información, consulte Anuncio.

Crear un nuevo Client con un nombre de dominio de OSS

En el siguiente código se muestra cómo inicializar un cliente con un nombre de dominio de OSS. Para conocer los nombres de dominio de OSS correspondientes a cada región, 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)
}

Crear un nuevo Client con un nombre de dominio personalizado

En el siguiente código se muestra cómo crear un nuevo Client con un nombre de dominio personalizado. Para saber cómo acceder a OSS mediante un nombre de dominio personalizado, consulte Access OSS with a custom domain name.

Importante

No es posible usar el método ossClient.listBuckets con un nombre de dominio 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 el Client

Puede configurar diversos parámetros del Client, como el proxy, el tiempo de espera de conexión y el número máximo de conexiones.

Parámetro

Descripción

Método

MaxIdleConns

Número máximo de conexiones inactivas. Valor predeterminado: 100.

oss.MaxConns

MaxIdleConnsPerHost

Número máximo de conexiones inactivas por host. Valor predeterminado: 100.

oss.MaxConns

MaxConnsPerHost

Número máximo de conexiones por host. El valor predeterminado está vacío.

oss.MaxConns

ConnectTimeout

Tiempo de espera HTTP en segundos. Valor predeterminado: 10 segundos. Un valor de 0 significa que no hay límite de tiempo.

oss.Timeout

ReadWriteTimeout

Tiempo de espera HTTP de lectura o escritura en segundos. Valor predeterminado: 20 segundos. Un valor de 0 significa que no hay límite de tiempo.

oss.Timeout

IsCname

Indica si se usa un nombre de dominio personalizado como endpoint. Esta función está deshabilitada de forma predeterminada.

oss.UseCname

UserAgent

Establece el encabezado User-Agent para las solicitudes HTTP. Valor predeterminado: aliyun-sdk-go.

oss.UserAgent

ProxyHost

Indica si se habilita la dirección del host y el puerto del servidor proxy. Valores válidos:

  • true: habilita la dirección del host y el puerto del servidor proxy.

  • false (predeterminado): deshabilita la dirección del host y el puerto del servidor proxy.

oss.AuthProxy

ProxyUser

Nombre de usuario para la autenticación del servidor proxy.

oss.AuthProxy

ProxyPassword

Contraseña para la autenticación del servidor proxy.

oss.AuthProxy

RedirectEnabled

Indica si se habilita la redirección HTTP. Valores válidos:

  • true (predeterminado): habilita la redirección HTTP.

  • false: deshabilita la redirección HTTP.

oss.RedirectEnabled

InsecureSkipVerify

Indica si se habilita la validación del certificado SSL. Valores válidos:

  • true (predeterminado): omite la validación del certificado SSL.

  • false: habilita la validación del certificado SSL.

oss.InsecureSkipVerify

IsEnableCRC

Indica si se habilita la validación de datos CRC. Valores válidos:

  • true (predeterminado): habilita la validación de datos CRC.

  • false: deshabilita la validación de datos CRC.

    Importante

    No deshabilite la validación de datos CRC. Si deshabilita esta función, Alibaba Cloud no podrá garantizar la integridad de los datos durante las cargas y descargas.

oss.EnableCRC

LogLevel

Establece el modo de registro. Valores válidos:

  • oss.LogOff

  • oss.Debug

  • oss.Error

  • oss.Warn

  • oss.Info

oss.SetLogLevel

A continuación se muestra un ejemplo de configuración:

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)
}

Establecer el contexto de la solicitud

El contexto de la solicitud le permite controlar y gestionar su ciclo de vida, así como pasar información relacionada con dicho contexto.

En el siguiente código se muestra cómo establecer el contexto de la solicitud. Esta opción solo es compatible con OSS Go SDK 2.2.9 y versiones posteriores.

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!")
}