All Products
Search
Document Center

Object Storage Service:OSS Go SDK V1

Last Updated:Jun 17, 2026

We recommend the newer OSS Go SDK V2 (alibabacloud-oss-go-sdk-v2), which offers major architectural improvements over V1 (aliyun-oss-go-sdk). V2 simplifies identity verification, request retries, and error handling, and adds advanced interfaces such as paginators, transfer managers, and file-like interfaces. To upgrade, see Go SDK V1 to V2 Migration Guide.

Quick integration

Complete the following steps to integrate OSS Go SDK V1.

image

Prepare the environment

Download and install the Go build and runtime environment. For more information, see Install Go. Use Go 1.13 or later.

  • Go 1.13 and later enable module mode by default to manage package dependencies. You do not need to manually set GOPATH.

  • For Go 1.12 and earlier, you must set the GOPATH system environment variable and point it to your code directory.

You can run the go version command to view the Go version.

Install the SDK

Select an installation method based on your development environment. We recommend using the latest SDK version.

go mod (Recommended)

Add the following dependency to the go.mod file. This example uses version 3.0.2. Replace it with the version you need.

require (
    github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible
)

From source code

Run the following command to install the SDK:

go get github.com/aliyun/aliyun-oss-go-sdk/oss

The installation process does not display any prompts. If the installation times out, run the command again.

Configure access credentials

Configure access credentials with a RAM user's AccessKey pair.

  1. In the RAM console, create a RAM user with a Permanent AccessKey Pair. Save the AccessKey pair and grant the AliyunOSSFullAccess permission to the user.

  2. Use the AccessKey pair of the RAM user to configure environment variables.

    Linux

    1. Run the following commands in the command-line interface to append the environment variable settings to the ~/.bashrc file.

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
    2. Run the following command to apply the changes.

      source ~/.bashrc
    3. Run the following commands to verify that the environment variables are configured.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Run the following command in the terminal to view the default shell type.

      echo $SHELL
    2. Perform the following operations based on the default shell type.

      Zsh
      1. Run the following commands to append the environment variable settings to the ~/.zshrc file.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
      2. Run the following command to apply the changes.

        source ~/.zshrc
      3. Run the following commands to verify that the environment variables are configured.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET
      Bash
      1. Run the following commands to append the environment variable settings to the ~/.bash_profile file.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
      2. Run the following command to apply the changes.

        source ~/.bash_profile
      3. Run the following commands to verify that the environment variables are configured.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD
    1. Run the following commands in CMD.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. Run the following commands to verify that the environment variables are configured.

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%
    PowerShell
    1. Run the following commands in PowerShell.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
    2. Run the following commands to verify that the environment variables are configured.

      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Initialize the client

The following sample code initializes a client using the public endpoint of the China (Hangzhou) region and lists the buckets under the current account. For a complete list of regions and endpoints, see Regions and endpoints.

package main

// Sample code for initializing a client in OSS Go SDK V1

import (
	"fmt"

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

func main() {

	// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, _ := oss.NewEnvironmentVariableCredentialsProvider()

	// Create an OSS client instance.
	client, _ := oss.New(
		"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
		"",
		"",
		oss.SetCredentialsProvider(&provider),
		oss.AuthVersion(oss.AuthV4),
		oss.Region("cn-hangzhou"),
	)

	// List all buckets.
	buckets, err := client.ListBuckets()
	if err != nil {
		fmt.Printf("Failed to list buckets: %v\n", err)
		return
	}

	// Print the bucket list.
	fmt.Printf("Found %d buckets:\n", len(buckets.Buckets))

	for _, bucket := range buckets.Buckets {
		fmt.Printf("%s\n", bucket.Name)
	}
}

Client configuration

When you initialize a client, you can customize parameters such as the endpoint type, timeout period, and connection pool size to suit your network and performance requirements.

Click to view configurable client parameters

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. Default value: empty.

oss.MaxConns

ConnectTimeout

The HTTP connection timeout period in seconds. Default value: 10. A value of 0 means no timeout.

oss.Timeout

ReadWriteTimeout

The HTTP read or write timeout period in seconds. Default value: 20. A value of 0 means no timeout.

oss.Timeout

IsCname

Specifies whether to use a custom domain name as the endpoint. The default value is false.

oss.UseCname

UserAgent

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:

  • true: enables the proxy server host address and port.

  • false (default): disables the proxy server host address and port.

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:

  • true (default): enables HTTP redirection.

  • false: disables HTTP redirection.

oss.RedirectEnabled

InsecureSkipVerify

Specifies whether to enable SSL certificate verification. Valid values:

  • true (default): ignores SSL certificate verification.

  • false: enables SSL certificate verification.

oss.InsecureSkipVerify

IsEnableCRC

Specifies whether to enable CRC data validation. Valid values:

  • true (default): enables CRC data validation.

  • false: disables CRC data validation.

oss.EnableCRC

LogLevel

The log level. Valid values:

  • oss.LogOff

  • oss.Debug

  • oss.Error

  • oss.Warn

  • oss.Info

oss.SetLogLevel

Use an internal endpoint

To access OSS over an internal network, specify an internal endpoint when you initialize the OSS client.

// Create an OSS client instance.
client, _ := oss.New(
	"oss-cn-hangzhou-internal.aliyuncs.com", // The internal endpoint of China (Hangzhou) is used as an example.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
)

Use a custom domain name

To access OSS using a custom domain name, specify it as the endpoint and enable the CNAME option with oss.UseCname(true) during client initialization.

Before you use a custom domain name, make sure that you have mapped the custom domain name to a bucket. For more information, see Access OSS through a custom domain name.
// Specify whether to use a custom domain name as the endpoint. The default value is false.
cname := oss.UseCname(true)

// Create an OSS client instance.
client, _ := oss.New(
	"http://kitkat-cloud.cn", // A custom domain name.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
	cname,
)

Timeout control

Use the oss.Timeout parameter to set the HTTP connection timeout period and read/write timeout period in seconds.

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

// Create an OSS client instance.
client, _ := oss.New(
	"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
	time,
)

Set the connection pool size

Use the oss.MaxConns parameter to adjust the connection pool size.

// Set the maximum number of idle connections (MaxIdleConns) to 10. The default value is 100.
// Set the maximum number of idle connections per host (MaxIdleConnsPerHost) to 20. The default value is 100.
// Set the maximum number of connections per host (MaxConnsPerHost) to 50. The default value is empty.
conn := oss.MaxConns(10, 20, 50)

// Create an OSS client instance.
client, _ := oss.New(
	"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
	conn,
)

Disable CRC data validation

Set oss.EnableCRC(false) to disable CRC data validation.

Important

We strongly recommend that you keep CRC data validation enabled. If you disable this feature, OSS cannot guarantee the integrity of data during uploads and downloads.

// Disable CRC data validation.
crc := oss.EnableCRC(false)

// Create an OSS client instance.
client, _ := oss.New(
	"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
	crc,
)

Signature version

Important

Alibaba Cloud Object Storage Service V1 signatures will be deprecated on the following schedule. Upgrade to V4 signatures as soon as possible to ensure your services are not affected.

  • Starting from March 1, 2025, new users cannot use V1 signatures.

  • Starting from September 1, 2025, maintenance and updates for V1 signatures will be gradually discontinued, and newly created buckets cannot use V1 signatures.

The following sample code initializes a client with a V1 signature. For V4 signature initialization, see Initialize the client.

package main

// Sample code for initializing a client with a V1 signature in OSS Go SDK V1

import (
	"fmt"

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

func main() {

	// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, _ := oss.NewEnvironmentVariableCredentialsProvider()

	// Create an OSS client instance.
	client, _ := oss.New(
		"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
		"",
		"",
		oss.SetCredentialsProvider(&provider),
	)

	// List all buckets.
	buckets, err := client.ListBuckets()
	if err != nil {
		fmt.Printf("Failed to list buckets: %v\n", err)
		return
	}

	// Print the bucket list.
	fmt.Printf("Found %d buckets:\n", len(buckets.Buckets))

	for _, bucket := range buckets.Buckets {
		fmt.Printf("%s\n", bucket.Name)
	}
}

Set the request context

Use the request context to control the lifecycle of requests.

Only OSS Go SDK 2.2.9 and later support setting the request context.
package main

// Sample code for setting the request context in OSS Go SDK V1

import (
	"context"
	"fmt"
	"time"

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

func main() {

	// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, _ := oss.NewEnvironmentVariableCredentialsProvider()

	// Create an OSS client instance.
	client, _ := oss.New(
		"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
		"",
		"",
		oss.SetCredentialsProvider(&provider),
		oss.AuthVersion(oss.AuthV4),
		oss.Region("cn-hangzhou"),
	)

	// Get the bucket object.
	bucket, _ := client.Bucket("example-bucket-hz")

	// Configure object information.
	key := "oss-browser2-mac-arm64-2.1.0.dmg"       // The path of the object in OSS.
	file_path := "oss-browser2-mac-arm64-2.1.0.dmg" // The local path to save the object.

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

	// Specify that the request context expires in 5 seconds.
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	// Download the object from OSS to the specified local path and set the request context.
	err := bucket.GetObjectToFile(key, file_path, oss.WithContext(ctx))
	if err != nil {
		select {
		case <-ctx.Done():
			fmt.Printf("Request canceled or timed out: %v\n", err)
		default:
			fmt.Printf("Download failed: %v\n", err)
		}
		return
	}

	fmt.Printf("Object downloaded: %s -> %s\n", key, file_path)
}

Error handling

When an error occurs during OSS access, the SDK returns details including the HTTP status code, error message, request ID, and EC error code. The EC error code identifies the specific cause and helps you quickly troubleshoot the issue. For example, if you try to download an object that does not exist, the following error message is returned:

oss: service returned error: StatusCode=404, ErrorCode=NoSuchKey, ErrorMessage="The specified key does not exist.", RequestId=69030EDB2E5F223030953167, Ec=0026-00000001

In the error message, 'EC': '0026-00000001' is the EC error code. You can use this error code to find the cause of the issue and the solution.

Sample code

OSS Go SDK V1 provides sample code covering core features such as bucket management, object operations, access control, and encrypted transfer. The following table lists available samples:

GitHub sample code

Official documentation sample code

new_bucket.go

Initialize a client

create_bucket.go

Create a bucket (Go SDK V1)

bucket_acl.go

Manage bucket ACLs (Go SDK V1)

bucket_policy.go

Authorization policy

bucket_referer.go

Hotlink protection (Go SDK V1)

bucket_lifecycle.go

Lifecycle

bucket_logging.go

Access log

bucket_cors.go

Cross-origin access

bucket_website.go

Static website hosting (mirroring-based back-to-origin) (Go SDK V1)

bucket_encryption.go

Server-side encryption (Go SDK V1)

bucket_requestpayment.go

Pay-by-requester (Go SDK V1)

bucket_inventory.go

Bucket inventory (Go SDK V1)

bucket_accessmonitor.go

Access tracking (Go SDK V1)

bucket_metaquery.go

Data indexing (Go SDK V1)

list_buckets.go

List buckets (Go SDK V1)

bucket_stat.go

Obtain the storage capacity of a bucket (Go SDK V1)

bucket_tagging.go

Bucket tagging (Go SDK V1)

put_object.go

Upload objects, including simple upload (Go SDK V1) and resumable upload (Go SDK V1)

append_object.go

Append upload

get_object.go

Download objects, including streaming download (Go SDK V1) and conditional download (Go SDK V1)

delete_object.go

Delete objects (Go SDK V1)

copy_object.go

Copy objects (Go SDK V1)

list_objects.go

List objects (Go SDK V1)

archive.go

Restore objects (Go SDK V1)

object_acl.go

Manage object ACLs

sign_url.go

Upload objects using signed URLs (Go SDK V1)

object_tagging.go

Object tagging

select_object.go

Query objects (Go SDK V1)

object_meta.go

Manage object metadata (Go SDK V1)

livechannel.go

LiveChannel management (Go SDK V1)

Query endpoint information

OSS Go SDK V1 lets you query endpoint information for all or specified regions, including public endpoints (IPv4), internal endpoints (classic network or VPC), and acceleration endpoints.

Note

Go SDK 2.2.8 and later support querying endpoint information.

package main

// Sample code for querying endpoint information in OSS Go SDK V1

import (
	"fmt"

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

func main() {

	fmt.Println("=== Query endpoint information for all supported regions ===\n")

	// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, _ := oss.NewEnvironmentVariableCredentialsProvider()

	// Create an OSS client instance.
	client, err := oss.New(
		"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
		"",
		"",
		oss.SetCredentialsProvider(&provider),
		oss.AuthVersion(oss.AuthV4),
		oss.Region("cn-hangzhou"),
	)
	if err != nil {
		fmt.Printf("Failed to create client: %v\n", err)
		return
	}

	// Query endpoint information for all supported regions.
	result, err := client.DescribeRegions()
	if err != nil {
		fmt.Printf("Failed to query endpoint information: %v\n", err)
		return
	}

	// Traverse all region information.
	for _, region := range result.Regions {
		fmt.Printf("Region: %s\n", region.Region)
		fmt.Printf("  Public endpoint (IPv4): %s\n", region.InternetEndpoint)
		fmt.Printf("  Internal endpoint (classic network or VPC): %s\n", region.InternalEndpoint)
		fmt.Printf("  Acceleration endpoint (global upload and download acceleration): %s\n", region.AccelerateEndpoint)
		fmt.Println("--------------------------------------------------------------------------------")
	}

	// Print statistics.
	fmt.Printf("\nFound endpoint information for %d regions\n", len(result.Regions))
}

To query endpoint information for a specific region, specify the OSS-specific region ID in the DescribeRegions method.

result, err := client.DescribeRegions(oss.AddParam("regions", "oss-cn-hangzhou"))

Access credential configuration

OSS supports multiple credential initialization methods. Select a method based on your authentication and authorization requirements.

Click to view how to select access credentials

Credential provider initialization method

Scenarios

Requires pre-configured AccessKey pair or STS token

Underlying credential

Credential validity

Credential rotation or refresh method

Use the AccessKey pair of a RAM user

Applications that are deployed in a secure and stable environment that is not susceptible to external attacks and require long-term access to Alibaba Cloud services without frequent credential rotation.

Yes

AccessKey pair

Long-term

Manual rotation

Use STS temporary access credentials

Applications that are deployed in an untrusted environment and require control over the validity period and permissions of access.

Yes

Security Token Service token

Temporary

Manual refresh

Use a RAM role ARN

Applications that require authorized access to Alibaba Cloud services, such as cross-account access.

Yes

Security Token Service token

Temporary

Auto-refresh

Use an ECS instance RAM role

Applications that are deployed on Alibaba Cloud ECS instances, ECI instances, or worker nodes of Container Service for Kubernetes.

No

Security Token Service token

Temporary

Auto-refresh

Use an OIDC role ARN

Untrusted applications that are deployed on worker nodes of Alibaba Cloud Container Service for Kubernetes.

No

Security Token Service token

Temporary

Auto-refresh

Use credentials from the Function Compute context

Functions of applications that are deployed in Alibaba Cloud Function Compute.

No

Security Token Service token

Temporary

No refresh required

Use a CredentialsURI

Applications that need to obtain access credentials from an external system.

No

Security Token Service token

Temporary

Auto-refresh

Use an auto-rotating AccessKey pair

Applications that are deployed in an environment with a risk of AccessKey pair leakage and require frequent credential rotation for long-term access to Alibaba Cloud services.

No

AccessKey pair

Long-term

Auto-rotation

Use custom access credentials

If none of the preceding credential configuration methods meet your requirements, you can customize the way you obtain credentials.

Custom

Custom

Custom

Custom

Use the AccessKey pair of a RAM user

Suitable for applications deployed in a secure environment that require long-term OSS access without frequent credential rotation. You initialize the credential provider with the AccessKey pair (AccessKey ID and AccessKey secret) of an Alibaba Cloud account or a RAM user. This method requires manual AccessKey pair maintenance, which may introduce security risks.

Important
  • An Alibaba Cloud account has full permissions on resources. If the AccessKey pair is leaked, it poses a significant risk to your system. We do not recommend using the AccessKey pair of an Alibaba Cloud account. Use the AccessKey pair of a RAM user with the minimum required permissions.

  • To create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret of a RAM user are displayed only when the AccessKey pair is created. If you forget them, create a new AccessKey pair to replace the old one.

Environment variables

  1. Configure environment variables using the AccessKey pair of a RAM user.

    Linux

    1. Run the following commands in the command-line interface to append the environment variable settings to the ~/.bashrc file.

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
    2. Run the following command to apply the changes.

      source ~/.bashrc
    3. Run the following commands to verify that the environment variables are configured.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Run the following command in the terminal to view the default shell type.

      echo $SHELL
    2. Perform the following operations based on the default shell type.

      Zsh

      1. Run the following commands to append the environment variable settings to the ~/.zshrc file.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
      2. Run the following command to apply the changes.

        source ~/.zshrc
      3. Run the following commands to verify that the environment variables are configured.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Run the following commands to append the environment variable settings to the ~/.bash_profile file.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
      2. Run the following command to apply the changes.

        source ~/.bash_profile
      3. Run the following commands to verify that the environment variables are configured.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Run the following commands in CMD.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. Run the following commands to verify that the environment variables are configured.

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Run the following commands in PowerShell.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
    2. Run the following commands to verify that the environment variables are configured.

      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. After modifying the system environment variables, restart or refresh the build and runtime environment. This includes IDEs, command-line interfaces, other desktop applications, and backend services to ensure that the latest system environment variables are loaded.

  3. Use environment variables to pass credential information.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    func main() {
    	// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Create an OSSClient instance.
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	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("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Static credentials

To avoid hard-coding credentials in source code, reference them through variables that read from environment variables, configuration files, or other external sources at runtime. The following example uses a configuration file:

  1. You can install the go-ini library.

    go get -u github.com/go-ini/ini
  2. You can create a configuration file named config.ini.

    [credentials]
    alibaba_cloud_access_key_id = <ALIBABA_CLOUD_ACCESS_KEY_ID>
    alibaba_cloud_access_key_secret = <ALIBABA_CLOUD_ACCESS_KEY_SECRET>
  3. You can write code to read credential information from the configuration file and initialize the OSS client.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"gopkg.in/ini.v1"
    )
    
    type defaultCredentials struct {
    	config *oss.Config
    }
    
    func (defCre *defaultCredentials) GetAccessKeyID() string {
    	return defCre.config.AccessKeyID
    }
    
    func (defCre *defaultCredentials) GetAccessKeySecret() string {
    	return defCre.config.AccessKeySecret
    }
    
    func (defCre *defaultCredentials) GetSecurityToken() string {
    	return defCre.config.SecurityToken
    }
    
    type defaultCredentialsProvider struct {
    	config *oss.Config
    }
    
    func (defBuild *defaultCredentialsProvider) GetCredentials() oss.Credentials {
    	return &defaultCredentials{config: defBuild.config}
    }
    func NewDefaultCredentialsProvider(accessID, accessKey, token string) (defaultCredentialsProvider, error) {
    	var provider defaultCredentialsProvider
    	if accessID == "" {
    		return provider, fmt.Errorf("access key id is empty!")
    	}
    	if accessKey == "" {
    		return provider, fmt.Errorf("access key secret is empty!")
    	}
    	config := &oss.Config{
    		AccessKeyID:     accessID,
    		AccessKeySecret: accessKey,
    		SecurityToken:   token,
    	}
    	return defaultCredentialsProvider{
    		config,
    	}, nil
    }
    
    func main() {
    	cfg, err := ini.Load("config.ini")
    	if err != nil {
    		fmt.Println("Error loading config file:", err)
    		return
    	}
    	accessKeyID := cfg.Section("credentials").Key("alibaba_cloud_access_key_id").String()
    	accessKeySecret := cfg.Section("credentials").Key("alibaba_cloud_access_key_secret").String()
    	provider, err := NewDefaultCredentialsProvider(accessKeyID, accessKeySecret, "")
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	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("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Use STS temporary access credentials

Suitable for applications that need temporary OSS access. You initialize the credential provider with temporary credentials (AccessKey ID, AccessKey secret, and Security Token) obtained from STS. This method requires manual STS token maintenance. To access OSS multiple times, you must manually refresh the token before it expires.

Important
  1. Set environment variables using the temporary identity credentials.

    Mac OS/Linux/Unix

    Important
    • Use the temporary identity credentials (AccessKey ID, AccessKey secret, and Security Token) obtained from STS, not the AccessKey pair (AccessKey ID and AccessKey secret) of a RAM user.

    • The AccessKey ID obtained from STS starts with "STS.", for example, "STS.****************".

    export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>

    Windows

    Important
    • Use the temporary identity credentials (AccessKey ID, AccessKey secret, and Security Token) obtained from STS, not the AccessKey pair (AccessKey ID and AccessKey secret) of a RAM user.

    • The AccessKey ID obtained from STS starts with "STS.", for example, "STS.****************".

    set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
  2. Pass the credential information through environment variables.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    func main() {
    	// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are set.
    	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Create an OSSClient instance.
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	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("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Use a RAM role ARN

Suitable for applications that require authorized access to OSS, such as cross-account access. You initialize the credential provider by specifying the ARN of a RAM role. The Credentials tool automatically obtains STS tokens and refreshes them before expiration by calling the AssumeRole operation. You can also assign a policy to restrict the role to a smaller set of permissions.

Important
  • An Alibaba Cloud account has full permissions on resources. If the AccessKey pair is leaked, it poses a significant risk to your system. We do not recommend using the AccessKey pair of an Alibaba Cloud account. Use the AccessKey pair of a RAM user with the minimum required permissions.

  • To create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret of a RAM user are displayed only when the AccessKey pair is created. Save them promptly. If you forget them, create a new AccessKey pair to replace the old one.

  • To obtain a RAM role ARN, see Create a RAM role.

  1. You can add the credentials dependency.

    go get github.com/aliyun/credentials-go/credentials
  2. Configure the AccessKey pair and RAM role ARN as access credentials.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    type Credentials struct {
    	AccessKeyId     string
    	AccessKeySecret string
    	SecurityToken   string
    }
    
    type defaultCredentialsProvider struct {
    	cred credentials.Credential
    }
    
    func (credentials *Credentials) GetAccessKeyID() string {
    	return credentials.AccessKeyId
    }
    
    func (credentials *Credentials) GetAccessKeySecret() string {
    	return credentials.AccessKeySecret
    }
    
    func (credentials *Credentials) GetSecurityToken() string {
    	return credentials.SecurityToken
    }
    
    func (defBuild *defaultCredentialsProvider) GetCredentials() oss.Credentials {
    	cred, _ := defBuild.cred.GetCredential()
    	return &Credentials{
    		AccessKeyId:     *cred.AccessKeyId,
    		AccessKeySecret: *cred.AccessKeySecret,
    		SecurityToken:   *cred.SecurityToken,
    	}
    }
    
    func NewRamRoleArnCredentialsProvider(credential credentials.Credential) defaultCredentialsProvider {
    	return defaultCredentialsProvider{
    		cred: credential,
    	}
    }
    
    func main() {
    	config := new(credentials.Config).
    		// The credential type. Set the value to ram_role_arn.
    		SetType("ram_role_arn").
    		// The AccessKey ID and AccessKey secret of the RAM user. The values are obtained from environment variables.
    		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
    		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
    		// The following operations directly use parameter values. You can also add environment variables and use os.Getenv("<variable_name>") to set the corresponding parameters.
    		// The ARN of the RAM role to assume. The value is obtained from an environment variable. Format: acs:ram::$accountID:role/$roleName.
    		SetRoleArn("ALIBABA_CLOUD_ROLE_ARN"). // The standard environment variable name for RoleArn is ALIBABA_CLOUD_ROLE_ARN.
    		// A custom name for the role session to distinguish different tokens.
    		SetRoleSessionName("ALIBABA_CLOUD_ROLE_SESSION_NAME"). // The standard environment variable name for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME.
    		// (Optional) Restrict the permissions of the STS token.
    		SetPolicy("").
    		// (Optional) Limit the validity period of the STS token.
    		SetRoleSessionExpiration(3600)
    
    	arnCredential, err := credentials.NewCredential(config)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    
    	provider := NewRamRoleArnCredentialsProvider(arnCredential)
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	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("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    
    	fmt.Printf("client:%#v\n", client)
    }

Use an ECS instance RAM role

Recommended for applications running on ECS instances, ECI instances, or Container Service for Kubernetes worker nodes. An ECS instance RAM role associates a role with the instance, enabling automatic STS token refresh without providing an AccessKey pair or STS token. For information about how to obtain an ECS instance RAM role, see Create a RAM role. For information about how to associate a role with an ECS instance, see Instance RAM roles.

  1. You can add the credentials dependency.

    go get github.com/aliyun/credentials-go/credentials
  2. Configure the ECS instance RAM role as the access credential.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    type Credentials struct {
    	AccessKeyId     string
    	AccessKeySecret string
    	SecurityToken   string
    }
    
    type CredentialsProvider struct {
    	cred credentials.Credential
    }
    
    func (credentials *Credentials) GetAccessKeyID() string {
    	return credentials.AccessKeyId
    }
    
    func (credentials *Credentials) GetAccessKeySecret() string {
    	return credentials.AccessKeySecret
    }
    
    func (credentials *Credentials) GetSecurityToken() string {
    	return credentials.SecurityToken
    }
    
    func (defBuild CredentialsProvider) GetCredentials() oss.Credentials {
    	cred, _ := defBuild.cred.GetCredential()
    	return &Credentials{
    		AccessKeyId:     *cred.AccessKeyId,
    		AccessKeySecret: *cred.AccessKeySecret,
    		SecurityToken:   *cred.SecurityToken,
    	}
    }
    
    func NewEcsCredentialsProvider(credential credentials.Credential) CredentialsProvider {
    	return CredentialsProvider{
    		cred: credential,
    	}
    }
    
    func main() {
    	config := new(credentials.Config).
    		// The credential type. Set the value to ecs_ram_role.
    		SetType("ecs_ram_role").
    		// (Optional) The role name. If you do not specify this parameter, OSS automatically obtains the role. We recommend that you specify the role name to reduce the number of requests.
    		SetRoleName("RoleName")
    
    	ecsCredential, err := credentials.NewCredential(config)
    	if err != nil {
    		return
    	}
    	provider := NewEcsCredentialsProvider(ecsCredential)
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	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("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    
    }

Use an OIDC role ARN

For untrusted applications deployed on Container Service for Kubernetes worker nodes, the RAM Roles for Service Accounts (RRSA) feature provides pod-level credential isolation. Instead of sharing the worker node's instance RAM role via the global meta service, RRSA mounts a service account OIDC token file into each pod and injects the configuration into environment variables. The Credentials tool then calls the AssumeRoleWithOIDC operation to exchange the OIDC token for an STS token. No AccessKey pair or STS token is required. For more information, see Configure RAM permissions for a ServiceAccount using RRSA to achieve pod-level permission isolation.

  1. You can add the credentials dependency.

    go get github.com/aliyun/credentials-go/credentials
  2. Configure the OIDC RAM role as the access credential.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    type Credentials struct {
    	AccessKeyId     string
    	AccessKeySecret string
    	SecurityToken   string
    }
    
    type CredentialsProvider struct {
    	cred credentials.Credential
    }
    
    func (credentials *Credentials) GetAccessKeyID() string {
    	return credentials.AccessKeyId
    }
    
    func (credentials *Credentials) GetAccessKeySecret() string {
    	return credentials.AccessKeySecret
    }
    
    func (credentials *Credentials) GetSecurityToken() string {
    	return credentials.SecurityToken
    }
    
    func (defBuild CredentialsProvider) GetCredentials() oss.Credentials {
    	cred, _ := defBuild.cred.GetCredential()
    	return &Credentials{
    		AccessKeyId:     *cred.AccessKeyId,
    		AccessKeySecret: *cred.AccessKeySecret,
    		SecurityToken:   *cred.SecurityToken,
    	}
    }
    
    func NewOIDCRoleARNCredentialsProvider(credential credentials.Credential) CredentialsProvider {
    	return CredentialsProvider{
    		cred: credential,
    	}
    }
    
    func main() {
    	config := new(credentials.Config).
    		// The file path of the OIDC token.
    		SetOIDCTokenFilePath(os.Getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE")).
    		// The following operations directly use parameter values. You can also add environment variables and use os.Getenv("<variable_name>") to set the corresponding parameters.
    		// The credential type. Set the value to oidc_role_arn.
    		SetType("oidc_role_arn").
    		// The ARN of the OIDC provider. Format: acs:ram::account-id:oidc-provider/provider-name.
    		SetOIDCProviderArn("acs:ram::113511544585****:oidc-provider/TestOidcProvider"). // The standard environment variable name for OIDCProviderArn is ALIBABA_CLOUD_OIDC_PROVIDER_ARN.
    		// A custom name for the role session to distinguish different tokens.
    		SetRoleSessionName("role_session_name"). // The standard environment variable name for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME.
    		// The ARN of the role to assume. Format: acs:ram::113511544585****:oidc-provider/TestOidcProvider
    		SetRoleArn("acs:ram::113511544585****:role/testoidc"). // The standard environment variable name for RoleArn is ALIBABA_CLOUD_ROLE_ARN.
    		// (Optional) The policy to use when assuming the role.
    		SetPolicy("").
    		SetSessionExpiration(3600)
    	oidcCredential, err := credentials.NewCredential(config)
    	if err != nil {
    		return
    	}
    	provider := NewOIDCRoleARNCredentialsProvider(oidcCredential)
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	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("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Use credentials from the Function Compute context

Suitable for application functions deployed in Function Compute. Function Compute obtains an STS token by assuming the service role configured for the function and passes it through the Credentials parameter in the context. This STS token is valid for 36 hours and does not expire during function execution (maximum 24 hours), so no refresh is needed. No AccessKey pair or STS token is required. For information about granting Function Compute permissions to access OSS, see Use a function role to grant Function Compute permissions to access other Alibaba Cloud services.

  1. You can add the Function Compute context dependencies.

    go get github.com/aliyun/fc-runtime-go-sdk/fc
    go get github.com/aliyun/fc-runtime-go-sdk/fccontext
  2. You can initialize the credential provider using credentials from the Function Compute context.

    package main
    
    import (
    	"context"
    	"fmt"
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/fc-runtime-go-sdk/fc"
    	"github.com/aliyun/fc-runtime-go-sdk/fccontext"
    )
    
    type GetObjectContext struct {
    	OutputRoute string `json:"outputRoute"`
    	OutputToken string `json:"outputToken"`
    	InputOssUrl string `json:"inputOssUrl"`
    }
    
    type StructEvent struct {
    	GetObjectContext GetObjectContext `json:"getObjectContext"`
    }
    
    func HandleRequest(ctx context.Context, event StructEvent) error {
    	endpoint := event.GetObjectContext.OutputRoute
    	fctx, _ := fccontext.FromContext(ctx)
    	client, err := oss.New(endpoint, fctx.Credentials.AccessKeyId, fctx.Credentials.AccessKeySecret, oss.SecurityToken(fctx.Credentials.SecurityToken))
    	if err != nil {
    		return fmt.Errorf("client new error: %v", err)
    	}
    	fmt.Printf("client:%#v\n", client)
    	return nil
    }
    
    func main() {
    	fc.Start(HandleRequest)
    }

Use a CredentialsURI

Suitable for applications that obtain credentials from an external system. The Credentials tool retrieves STS tokens from the specified URI and automatically refreshes them. No AccessKey pair or STS token is required.

Important
  • The CredentialsURI is the server address from which the STS token is obtained.

  • The backend service that provides the CredentialsURI response must implement the logic for automatic STS token refresh to ensure that the application can always obtain valid credentials.

  1. For the Credentials tool to correctly parse and use the STS token, the URI must adhere to the following response protocol:

    • Response status code: 200

    • Response body structure:

      {
          "Code": "Success",
          "AccessKeySecret": "AccessKeySecret",
          "AccessKeyId": "AccessKeyId",
          "Expiration": "2021-09-26T03:46:38Z",
          "SecurityToken": "SecurityToken"
      }
  2. You can add the credentials dependency.

    go get github.com/aliyun/credentials-go/credentials
  3. Configure the CredentialsURI as the access credential.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    type Credentials struct {
    	AccessKeyId     string
    	AccessKeySecret string
    	SecurityToken   string
    }
    
    type CredentialsProvider struct {
    	cred credentials.Credential
    }
    
    func (credentials *Credentials) GetAccessKeyID() string {
    	return credentials.AccessKeyId
    }
    
    func (credentials *Credentials) GetAccessKeySecret() string {
    	return credentials.AccessKeySecret
    }
    
    func (credentials *Credentials) GetSecurityToken() string {
    	return credentials.SecurityToken
    }
    
    func (defBuild CredentialsProvider) GetCredentials() oss.Credentials {
    	cred, _ := defBuild.cred.GetCredential()
    	return &Credentials{
    		AccessKeyId:     *cred.AccessKeyId,
    		AccessKeySecret: *cred.AccessKeySecret,
    		SecurityToken:   *cred.SecurityToken,
    	}
    }
    
    func NewCredentialsUriCredentialsProvider(credential credentials.Credential) CredentialsProvider {
    	return CredentialsProvider{
    		cred: credential,
    	}
    }
    
    func main() {
    	config := new(credentials.Config).
    		// The credential type. Set the value to credentials_uri.
    		SetType("credentials_uri").
    		// Specify the URL address. You can also set an environment variable and use os.Getenv("<variable_name>") to pass the parameter.
    		// The standard environment variable name for URLCredential is ALIBABA_CLOUD_CREDENTIALS_URI.
    		SetURLCredential("http://127.0.0.1")
    	uriCredential, err := credentials.NewCredential(config)
    	if err != nil {
    		return
    	}
    	provider := NewCredentialsUriCredentialsProvider(uriCredential)
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	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("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Use an auto-rotating AccessKey pair

Suitable for applications that require long-term OSS access but are deployed in environments where AccessKey pair leakage is a risk. You initialize the credential provider with a ClientKey. Key Management Service (KMS) automatically rotates the managed RAM user's AccessKey pair on a periodic schedule, turning a static credential into a dynamic one. KMS also supports immediate rotation for quick replacement if a leak occurs. For information about how to obtain a ClientKey, see Create an application access point.

  1. You can add the credential client dependency.

    go get -u github.com/aliyun/aliyun-secretsmanager-client-go
  2. You can create a configuration file named secretsmanager.properties.

    # Access credential type
    credentials_type=client_key
    
    # The password used to decrypt the client key. The password can be read from an environment variable or a file.
    client_key_password_from_env_variable=#your client key private key password environment variable name#
    client_key_password_from_file_path=#your client key private key password file path#
    
    # The path of the client key's private key file.
    client_key_private_key_path=#your client key private key file path#
    
    # The region of the associated KMS service.
    cache_client_region_id=[{"regionId":"#regionId#"}]
  3. You can use the configuration file to pass credential information.

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/aliyun-secretsmanager-client-go/sdk"
    )
    
    type defaultCredentials struct {
    	config *oss.Config
    }
    
    func (defCre *defaultCredentials) GetAccessKeyID() string {
    	return defCre.config.AccessKeyID
    }
    
    func (defCre *defaultCredentials) GetAccessKeySecret() string {
    	return defCre.config.AccessKeySecret
    }
    
    func (defCre *defaultCredentials) GetSecurityToken() string {
    	return defCre.config.SecurityToken
    }
    
    type defaultCredentialsProvider struct {
    	config *oss.Config
    }
    
    func (defBuild *defaultCredentialsProvider) GetCredentials() oss.Credentials {
    	return &defaultCredentials{config: defBuild.config}
    }
    func NewDefaultCredentialsProvider(accessID, accessKey, token string) (defaultCredentialsProvider, error) {
    	var provider defaultCredentialsProvider
    	if accessID == "" {
    		return provider, fmt.Errorf("access key id is empty!")
    	}
    	if accessKey == "" {
    		return provider, fmt.Errorf("access key secret is empty!")
    	}
    	config := &oss.Config{
    		AccessKeyID:     accessID,
    		AccessKeySecret: accessKey,
    		SecurityToken:   token,
    	}
    	return defaultCredentialsProvider{
    		config,
    	}, nil
    }
    
    func main() {
    	client, err := sdk.NewClient()
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	secretInfo, err := client.GetSecretInfo("#secretName#")
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("SecretValue:%s\n", secretInfo.SecretValue)
    	var m map[string]string
    	err = json.Unmarshal([]byte(secretInfo.SecretValue), &m)
    	if err != nil {
    		fmt.Println("Error decoding JSON:", err)
    		os.Exit(-1)
    	}
    	accessKeyId := m["AccessKeyId"]
    	accessKeySecret := m["AccessKeySecret"]
    	provider, err := NewDefaultCredentialsProvider(accessKeyId, accessKeySecret, "")
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	ossClient, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", ossClient)
    }

Use custom access credentials

If none of the preceding methods meet your requirements, you can implement a custom credential provider using the Credential Providers interface. If the underlying credentials are STS-based, you must handle token refresh.

package main

import (
	"fmt"
	"os"

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

type CustomerCredentialsProvider struct {
	config *oss.Config
}

func NewCustomerCredentialsProvider() CustomerCredentialsProvider {
	return CustomerCredentialsProvider{}
}

func (s CustomerCredentialsProvider) GetCredentials() oss.Credentials {
	// Return long-term credentials.
	config := &oss.Config{
		AccessKeyID:     "id",
		AccessKeySecret: "secret",
	}
	return &CustomerCredentialsProvider{
		config,
	}
	// Return temporary credentials.
	//config := &oss.Config{
	//    AccessKeyID:     "id",
	//    AccessKeySecret: "secret",
	//    SecurityToken:   "token",
	//}
	//return &CustomerCredentialsProvider{
	//    config,
	//}
}

func (s *CustomerCredentialsProvider) GetAccessKeyID() string {
	return s.config.AccessKeyID
}

func (s *CustomerCredentialsProvider) GetAccessKeySecret() string {
	return s.config.AccessKeySecret
}

func (s *CustomerCredentialsProvider) GetSecurityToken() string {
	return s.config.SecurityToken
}

func main() {
	provider := NewCustomerCredentialsProvider()
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	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("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.Printf("client:%#v\n", client)
}

FAQ

How do I troubleshoot the AccessDenied error when I use the SDK?

The AccessDenied error typically indicates insufficient permissions. Follow these steps to troubleshoot:

  1. Confirm the AccessKey ID and AccessKey secret: Make sure you are using the correct AccessKey ID and AccessKey secret.

  2. Check RAM user permissions: Confirm whether the RAM user has the necessary permissions for bucket or object operations.

  3. Check the bucket policy: If the error message mentions "Access denied by bucket policy," it means the access was denied by a bucket policy.

  4. For more information about how to query other error types and troubleshoot common access control errors, see Error handling.

References