All Products
Search
Document Center

:Initialize OSS SDK for Go

Last Updated:Nov 07, 2024

OSSClient is the Go client of Object Storage Service (OSS). It is used to manage OSS resources, such as buckets and objects. When you use OSS SDK for Go to initiate a request, you must initialize an OSSClient instance and modify the default configuration items based on your business requirements.

Prerequisites

Access credentials are configured. For more information, see Configure access credentials.

Create an OSSClient instance

(Recommended) Use the V4 signature algorithm

We recommend that you use the V4 signature algorithm which provides better security. If you use the V4 signature algorithm, specify the region parameter. The region must be an Alibaba Cloud Region ID. Example: cn-Hangzhou. You must also declare oss.AuthV4. OSS SDK for Go 3.0.2 and later support V4 signatures.

The following sample code provides an example on how to use an OSS endpoint to create an OSSClient instance by using the V4 signature algorithm. If you want to use other methods to create an OSSClient instance by using the V4 signature algorithm, refer to the following sample code and change the variables.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

// Call handleError to handle unrecoverable errors and terminate the program after recording the error messages.
func handleError(err error) {
	log.Fatalf("Error: %v", err)
}

// Use setupClient to create and configure an OSSClient instance.
// Parameters:
//
//	endpoint: endpoint of the region in which the bucket is located.
//	region: the region in which the bucket is located.
//
// Return the created OSSClient 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 the signature algorithm V4.
	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() {
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
	endpoint := "yourEndpoint"

	// Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou.
	region := "yourRegion"

	// Check whether the environment variables are configured.
	if endpoint == "" || region == "" {
		log.Fatal("Please set yourEndpoint and yourRegion.")
	}

	// Create and configure an OSSClient instance.
	client, err := setupClient(endpoint, region)
	if err != nil {
		handleError(err)
	}

	// Display the client information.
	log.Printf("Client: %#v\n", client)
}

(Not recommended) Use the V1 signature algorithm

Important

From December 1, 2024, the V1 signature algorithm of OSS is no longer available to new customers with new UIDs. From June 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 an OSSClient instance by using an OSS endpoint

The following sample code provides an example on how to create an OSSClient instance by using an OSS endpoint. For more information about the OSS endpoints of different regions, see Regions, endpoints and open ports.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

// Call handleError to handle unrecoverable errors and terminate the program after recording the error messages.
func handleError(err error) {
	log.Fatalf("Error: %v", err)
}

// Use setupClient to create and configure an OSSClient instance.
// Parameters:
//
//	endpoint: endpoint of the region in which the bucket is located.
//
// Return the created OSSClient 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. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New(endpoint, "", "", clientOptions...)
	if err != nil {
		return nil, err
	}

	return client, nil
}

func main() {
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
	endpoint := "yourEndpoint"

	// Check whether the environment variables are configured.
	if endpoint == "" {
		log.Fatal("Please set yourEndpoint.")
	}

	// Create and configure an OSSClient instance.
	client, err := setupClient(endpoint)
	if err != nil {
		handleError(err)
	}

	// Display the client information.
	log.Printf("Client: %#v\n", client)
}

Create an OSSClient instance by using a custom domain name

The following sample code provides an example on how to create an OSSClient instance by using a custom domain name. For more information, see Map a custom domain name to the default domain name of a bucket.

Important

If you use a custom domain name, the ossClient.listBuckets method is unavailable.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

// Call handleError to handle unrecoverable errors and terminate the program after recording the error messages.
func handleError(err error) {
	log.Fatalf("Error: %v", err)
}

// Use setupClient to create and configure an OSSClient instance and use CNAME as an endpoint.
// Parameters:
//
//	endpoint: the custom domain name that you want to map to the bucket.
//
// Return the created OSSClient 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 use CNAME as an endpoint.
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	clientOptions = append(clientOptions, oss.UseCname(true))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New(endpoint, "", "", clientOptions...)
	if err != nil {
		return nil, err
	}

	return client, nil
}

func main() {
	// Specify the endpoint of the region in which the bucket is located.
	// Example: custom-domain-for-your-bucket.com.
	endpoint := "yourEndpoint"

	// Check whether the environment variables are configured.
	if endpoint == "" {
		log.Fatal("Please set yourEndpoint.")
	}

	// Create and configure an OSSClient instance and use CNAME as an endpoint.
	client, err := setupClient(endpoint)
	if err != nil {
		handleError(err)
	}

	// Display the client information.
	log.Printf("Client: %#v\n", client)
}

Configure an OSSClient instance

You can use an OSSClient instance to configure parameters, such as the proxy server, connection timeout period, and the maximum number of connections. The following table describes the parameters.

Parameter

Description

Method

MaxIdleConns

The maximum number of idle connections. Default value: 100.

oss.MaxConns

MaxIdleConnsPerHost

The maximum number of idle connections of a server. Default value: 100.

oss.MaxConns

MaxConnsPerHost

The maximum number of connections of a server. By default, this parameter is left empty.

oss.MaxConns

ConnectTimeout

The timeout period of an HTTP connection. Unit: seconds. Default value: 10. The value 0 indicates that the HTTP connection does not time out.

oss.Timeout

ReadWriteTimeout

The read or write timeout period of an HTTP connection. Unit: seconds. Default value: 20. The value 0 indicates that the HTTP connection does not time out.

oss.Timeout

IsCname

Specifies whether a custom domain name can be used as an endpoint. By default, a custom domain name cannot be used as an endpoint.

oss.UseCname

UserAgent

The User-Agent header. Default value: aliyun-sdk-go.

oss.UserAgent

ProxyHost

Specifies whether to enable the IP address and the port of the proxy server. Valid values:

  • true

  • false (default)

oss.AuthProxy

ProxyUser

The username that is used to log on to the proxy server.

oss.AuthProxy

ProxyPassword

The password that is used to log on to the proxy server.

oss.AuthProxy

RedirectEnabled

Specifies whether to enable HTTP redirection. Valid values:

  • true (default)

  • false

oss.RedirectEnabled

InsecureSkipVerify

Specifies whether to enable SSL-based authentication. Valid values:

  • true (default)

  • false

oss.InsecureSkipVerify

IsEnableCRC

Specifies whether to enable CRC-64. Valid values:

  • true (default)

  • false

    Important

    We recommend that you do not disable CRC-64. If you disable CRC-64, data integrity may be affected during object uploads and downloads.

oss.EnableCRC

LogLevel

The log mode. Valid values:

  • oss.LogOff

  • oss.Debug

  • oss.Error

  • oss.Warn

  • oss.Info

oss.SetLogLevel

Example:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

// Call handleError to handle unrecoverable errors and terminate the program after recording the error messages.
func handleError(err error) {
	log.Fatalf("Error: %v", err)
}

// Use setupClient to create and configure an OSSClient instance.
// Parameters:
//
//	endpoint: endpoint of the region in which the bucket is located.
//
// Return the created OSSClient 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 number of connections to 10, the maximum number of idle connections of a server to 20, and the maximum number of connections of a server to 20.
	conn := oss.MaxConns(10, 20, 20)

	// Set the timeout period of an HTTP connection to 20 and the read or write timeout period of an HTTP connection to 60. Unit: seconds.
	time := oss.Timeout(20, 60)

	// Specify whether a custom domain name can be used as an endpoint. By default, a custom domain name cannot be used as an endpoint.
	cname := oss.UseCname(true)

	// Specify the User-Agent header. Default value: aliyun-sdk-go.
	userAgent := oss.UserAgent("aliyun-sdk-go")

	// Specify whether to enable HTTP redirection. Default value: true.
	redirect := oss.RedirectEnabled(true)

	// Specify whether to enable SSL-based authentication. Default value: false.
	verifySsl := oss.InsecureSkipVerify(false)

	// Specify whether to enable the IP address and port of the proxy server.
	// proxy := oss.Proxy("yourProxyHost")

	// Specify the IP address and the port of the proxy server, and the username and the password that are used to log on to the proxy server.
	authProxy := oss.AuthProxy("yourProxyHost", "yourProxyUserName", "yourProxyPassword")

	// Enable CRC-64.
	crc := oss.EnableCRC(true)

	// Specify the log mode.
	logLevel := oss.SetLogLevel(oss.LogOff)

	// Create an OSSClient instance. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify 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() {
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	endpoint := "yourEndpoint"

	// Check whether the environment variables are configured.
	if endpoint == "" {
		log.Fatal("Please set yourEndpoint.")
	}

	// Create and configure an OSSClient instance.
	client, err := setupClient(endpoint)
	if err != nil {
		handleError(err)
	}

	// Display the client information.
	log.Printf("Client: %#v\n", client)
}

Specify the request context

You can use the request context to manage the lifecycle of a request and pass context information related to the request.

The following sample code provides an example on how to specify the request context. You can specify the request context by using OSS SDK for Go 2.2.9 and later.

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

// Call handleError to handle unrecoverable errors and terminate the program after recording the error messages.
func handleError(err error) {
	log.Fatalf("Error: %v", err)
}

// Call uploadFile to upload a local file to an OSS bucket.
// Parameters:
//
//	bucketName: name of the bucket.
//	objectName: the full path of the object. Do not include the bucket name in the full path.
//	localFileName: the full path of the local file.
//	endpoint: endpoint of the region in which the bucket is located.
//
// If the local file is uploaded, a log is generated. Otherwise, an error message 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. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
	client, err := oss.New(endpoint, "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		return err
	}

	// Create a bucket.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return err
	}

	// Specify the request context.
	ctx := context.Background()

	// Specify the expiration time of 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 local file is uploaded, a log is generated.
	log.Printf("File uploaded successfully: %s/%s", bucketName, objectName)
	return nil
}

func main() {
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	endpoint := "yourEndpoint"

	// Specify the name of the bucket. Example: examplebucket.
	bucketName := "examplebucket"

	// Specify the full path of the object. Do not include the bucket name in the full path.
	objectName := "yourObjectName"

	// Specify the full path of the local file.
	localFileName := "yourLocalFile"

	// Check whether the environment variables are configured.
	if endpoint == "" || bucketName == "" || objectName == "" || localFileName == "" {
		log.Fatal("Please set yourEndpoint, bucketName, objectName, and localFileName.")
	}

	// Upload the local file. If the local file fails to be uploaded, an error is reported. Resolve the error.
	if err := uploadFile(bucketName, objectName, localFileName, endpoint); err != nil {
		handleError(err)
	}

	// A message indicating that the object is uploaded is returned.
	log.Println("Upload Success!")
}

What to do next

After you initialize OSS SDK for Go, you can use the OSSClient instance to initiate a request. For more information, see Get started with OSS SDK for Go.