The Client is the Go client for Object Storage Service (OSS), which you can use to manage OSS resources such as buckets and files. To send an OSS request with the Go SDK, you must initialize a Client instance. You can also modify the default configurations as needed.
Prerequisites
Before you initialize the OSS SDK, you must configure your access credentials. For more information, see Configure access credentials (Go SDK V1).
Create a new Client
V4 signature (Recommended)
We recommend that you use the more secure V4 signature algorithm. When you initialize the client with a V4 signature, you must specify the Endpoint and the general-purpose Alibaba Cloud region ID. The region ID specifies the region where the request is initiated, for example, cn-hangzhou. You must also declare oss.AuthV4. V4 signatures are supported in OSS Go SDK 3.0.2 and later.
The following example shows how to initialize a client with a V4 signature using an OSS domain name. You can modify the example for other scenarios, such as initializing the client with a custom domain name.
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.
// region - The region information that corresponds 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() {
// 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"
// Set yourRegion to the region that corresponds to the Endpoint, for example, cn-hangzhou.
region := "yourRegion"
// Check if the environment variables are set.
if endpoint == "" || region == "" {
log.Fatal("Please set yourEndpoint and yourRegion.")
}
// Set up and create an OSS client instance.
client, err := setupClient(endpoint, region)
if err != nil {
handleError(err)
}
// Print the client information.
log.Printf("Client: %#v\n", client)
}
V1 signature (Not recommended)
From March 1, 2025, the V1 signature algorithm of OSS is no longer available to new customers with new UIDs. From September 1, 2025, OSS no longer updates and maintains the V1 signature algorithm, and the V1 signature algorithm is no longer available for new buckets. Upgrade V1 signatures to V4 signatures at the earliest opportunity to prevent impact on your business.
Create a new Client using an OSS domain name
The following code shows how to initialize a client using an OSS domain name. For more information about OSS domain names for different regions, see 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 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
}
// 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.
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(endpoint, "", "", clientOptions...)
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)
}
Create a new Client using a custom domain name
The following code shows how to create a new Client using a custom domain name. For more information about how to access OSS using a custom domain name, see Access OSS with a custom domain name.
You cannot use the ossClient.listBuckets method with a custom domain name.
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 the Client
You can configure parameters for the Client, such as the proxy, connection timeout, and maximum connections.
Parameter | Description | Method |
MaxIdleConns | The maximum number of idle connections. Default value: 100. | oss.MaxConns |
MaxIdleConnsPerHost | The maximum number of idle connections per host. Default value: 100. | oss.MaxConns |
MaxConnsPerHost | The maximum number of connections per host. The default value is empty. | oss.MaxConns |
ConnectTimeout | The HTTP timeout period in seconds. Default value: 10 seconds. A value of 0 means no timeout. | oss.Timeout |
ReadWriteTimeout | The HTTP read or write timeout period in seconds. Default value: 20 seconds. A value of 0 means no timeout. | oss.Timeout |
IsCname | Specifies whether to use a custom domain name as the Endpoint. This feature is disabled by default. | oss.UseCname |
UserAgent | Sets the User-Agent header for HTTP requests. Default value: aliyun-sdk-go. | oss.UserAgent |
ProxyHost | Specifies whether to enable the proxy server host address and port. Valid values:
| oss.AuthProxy |
ProxyUser | The username for proxy server authentication. | oss.AuthProxy |
ProxyPassword | The password for proxy server authentication. | oss.AuthProxy |
RedirectEnabled | Specifies whether to enable HTTP redirection. Valid values:
| oss.RedirectEnabled |
InsecureSkipVerify | Specifies whether to enable SSL certificate validation. Valid values:
| oss.InsecureSkipVerify |
IsEnableCRC | Specifies whether to enable CRC data validation. Valid values:
| oss.EnableCRC |
LogLevel | Sets the log mode. Valid values:
| oss.SetLogLevel |
The following code provides a configuration example:
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)
}
Set the request context
You can use the request context to control and manage the request lifecycle and pass context-related information.
The following code shows how to set the request context. Setting the request context is supported only in OSS Go SDK 2.2.9 and later.
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!")
}