GitHub | OSS Go SDK V2 developer guide | OSS SDK for Go API
Quickstart
Environment preparation
Requires Go 1.18 or later.
Check your Go version with go -version. If Go is not installed or is older than 1.18, install Go.
Install the SDK
-
Create a project directory and initialize the Go module.
mkdir oss-go-example && cd oss-go-example && go mod init oss-go-example -
Install the SDK package (latest version recommended).
go get github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss -
Import the SDK package.
import "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
Configure access credentials
Use a RAM user's AccessKey to configure access credentials.
-
In the RAM console, create a RAM user with Access By Using Permanent AccessKey, save the AccessKey pair, and grant the
AliyunOSSFullAccesspermission. -
Use the RAM user's AccessKey to configure environment variables.
Linux
-
Append the environment variables to
~/.bashrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Apply the changes.
source ~/.bashrc -
Verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Check your default shell.
echo $SHELL-
Configure environment variables based on your shell.
Zsh
-
Append the environment variables to
~/.zshrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Apply the changes.
source ~/.zshrc -
Verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Append the environment variables to
~/.bash_profile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Apply the changes.
source ~/.bash_profile -
Verify that the environment variables are set.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Run the following commands in CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Verify that the environment variables are set.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
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)-
Verify that the environment variables are set.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
Initialize the client
Due to a policy change to improve compliance and security, starting March 20, 2025, new OSS users must use a custom domain name (CNAME) to perform data API operations on OSS buckets located in Chinese mainland regions. Default public endpoints are restricted for these operations. Refer to the official announcement for a complete list of the affected operations. If you access your data via HTTPS, you must bind a valid SSL Certificate to your custom domain. This is mandatory for OSS Console access, as the console enforces HTTPS.
Before you run the sample code, replace placeholders such as<region-id>with your actual regions and endpoints, for example,ap-southeast-1.
package main
import (
"context"
"log"
"strings"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
/*
Go SDK V2 client initialization configuration:
1. Signature version: Go SDK V2 uses v4 signatures by default to provide enhanced security.
2. Region configuration: You must specify an Alibaba Cloud region ID to identify the request region.
3. Endpoint configuration:
- You can use the endpoint parameter to specify a custom domain name for service requests.
- If this parameter is not specified, the SDK automatically constructs a public endpoint based on the region information.
4. Protocol configuration:
- The SDK uses the HTTPS protocol by default to construct endpoints.
- To use HTTP, you must specify an endpoint that starts with http://.
*/
func main() {
// Method 1: Specify only the region (recommended).
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>") // Specify the region where the bucket is located.
// Method 2: Specify both the region and the endpoint.
// cfg := oss.LoadDefaultConfig().
// WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
// WithRegion("<region-id>"). // Specify the region where the bucket is located.
// WithEndpoint("<endpoint>") // Specify the public endpoint of the region where the bucket is located.
// Create an OSS client.
client := oss.NewClient(cfg)
// Create the upload body.
body := strings.NewReader("hi oss")
// Create a request to upload the object.
request := &oss.PutObjectRequest{
Bucket: oss.Ptr("Your Bucket Name"), // The name of the bucket.
Key: oss.Ptr("Your Object Key"), // The name of the object.
Body: body, // The string content to upload.
}
// Send the request to upload the object.
result, err := client.PutObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put object %v", err)
}
// Print the result of the upload operation.
log.Printf("Status: %#v\n", result.Status)
log.Printf("RequestId: %#v\n", result.ResultCommon.Headers.Get("X-Oss-Request-Id"))
log.Printf("ETag: %#v\n", *result.ETag)
}
Successful output:
Status: "200 OK"
RequestId: "68746C5FE001B434303B90B6"
ETag: "B22E0DC370A7F7067FACF5F75D7FA385"
Client configuration
Custom domain names
Bind a custom domain name to enable browser-based file preview and CDN acceleration.
Before you run the sample code, replace the<region-id>placeholder with your region and endpoint, such as orap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Specify the region where the bucket is located.
// Specify your custom domain name, for example, https://www.example-***.com
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>").
WithEndpoint("https://www.example-***.com").
WithUseCName(true) // Set this parameter to true to use a custom domain name via CNAME.
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client to perform subsequent operations...
}
Timeout control
Before running the sample code, replace the<region-id>placeholder with your region and endpoint, such as orap-southeast-1.
package main
import (
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>"). // The region where your bucket is located.
WithConnectTimeout(10 * time.Second). // Connection timeout. Defaults to 5s.
WithReadWriteTimeout(30 * time.Second) // Read/write timeout. Defaults to 10s.
// Create the OSS client.
client := oss.NewClient(cfg)
// Use the client to perform further operations...
}
Maximum retry attempts
The OSSClient retries failed requests 3 times by default.
Use WithRetryMaxAttempts to increase retries for high-concurrency or unstable-network scenarios.
Before you run the sample code, replace the<region-id>placeholder with the region and endpoint, such as orap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>"). // Specifies the bucket's region.
WithRetryMaxAttempts(5) // Sets the maximum number of retry attempts. The default is 3.
// Create an OSSClient instance.
client := oss.NewClient(cfg)
// Use the client for subsequent operations...
}
HTTP/HTTPS protocol
Use WithDisableSSL(true) to switch from HTTPS to HTTP.
Before running the sample code, replace the<region-id>placeholder with the actual region and endpoint, such as orap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>"). // Specify the region where the bucket is located.
WithDisableSSL(true) // Disable the HTTPS protocol, which is enabled by default.
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client for subsequent operations...
}
Proxy server
Use WithProxyHost to route requests through a proxy server.
Before you run the sample code, replace the<region-id>placeholder with the region and endpoint, such asap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>"). // Specify the region where the bucket is located.
WithUserAgent("aliyun-sdk-go"). // Set the user agent for the HTTP User-Agent header.
WithProxyHost("http://user:passswd@proxy.example-***.com") // Set the proxy server, e.g., "http://user:passswd@proxy.example-***.com".
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client to perform subsequent operations...
}
Internal endpoint
Use an internal endpoint when your application runs on an ECS instance in the same region as the bucket to reduce costs and latency.
Before you run the sample code, replace placeholders such as<region-id>with your Region and Endpoint, such as orap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main()
// Method 1: Specify the region and set WithUseInternalEndpoint to true.
// Specify the region where the bucket is located.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>").
WithUseInternalEndpoint(true)
// Method 2: Directly specify the region and endpoint.
// Specify the internal endpoint corresponding to the bucket's region.
// cfg := oss.LoadDefaultConfig().
// WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
// WithRegion("<region-id>").
// WithEndpoint("<endpoint>")
// Create an OSS client.
client := oss.NewClient(cfg)
// Use this client for further operations.
}
Accelerated endpoint
Before running the sample code, replace the<region-id>placeholder with the ID for your region and endpoint, such asap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Method 1: Specify the region and set WithUseAccelerateEndpoint to true.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>").
WithUseAccelerateEndpoint(true)
// Method 2: Directly specify the region and endpoint.
// cfg := oss.LoadDefaultConfig().
// WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
// WithRegion("<region-id>").
// WithEndpoint("https://oss-accelerate.aliyuncs.com").
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client to perform operations...
}
Private domain
Before running the sample code, replace the<region-id>placeholder with the correct ID based on your region and endpoint, such asap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Specify the region that contains the bucket.
// Specify your private domain. Example: https://service.corp.example.com
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>").
WithEndpoint("https://service.corp.example.com")
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client to perform subsequent operations...
}
Government cloud endpoints
The following example shows how to configure the OSS client to use government cloud endpoints.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Specify the region where the bucket is located and its corresponding internal endpoint.
// For example, for the China North 2 Ali Gov 1 region, set Region to "cn-north-2-gov-1" and Endpoint to "https://oss-cn-north-2-gov-1-internal.aliyuncs.com".
// To use the HTTP protocol, use the HTTP endpoint: "http://oss-cn-north-2-gov-1-internal.aliyuncs.com".
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("cn-north-2-gov-1").
WithEndpoint("https://oss-cn-north-2-gov-1-internal.aliyuncs.com")
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client to perform further operations...
}
Access CloudBox buckets
Before you run the sample code, replace the<region-id>placeholder with the actual region and endpoint, such asap-southeast-1.
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Method 1: Automatically detect the CloudBox ID.
// Specify the region where the bucket is located.
// Set the endpoint to the data domain name of the CloudBox bucket. Example: http://cb-xxxxxx.<region-id>.oss-cloudbox.aliyuncs.com
// Set WithEnableAutoDetectCloudBoxId to true to automatically detect the CloudBox ID.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithEndpoint("http://cb-xxxxxx.<region-id>.oss-cloudbox.aliyuncs.com").
WithEnableAutoDetectCloudBoxId(true)
// Method 2: Manually set the CloudBox ID.
// Specify the region where the bucket is located.
// Set the endpoint to the data domain name of the CloudBox bucket. Example: http://cb-xxxxxx.<region-id>.oss-cloudbox.aliyuncs.com
// Specify the CloudBox ID manually. Example: cb-xxxxxx
// cfg := oss.LoadDefaultConfig().
// WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
// WithEndpoint("http://cb-xxxxxx.<region-id>.oss-cloudbox.aliyuncs.com").
// WithCloudBoxId("cb-xxxxxx")
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client for OSS operations...
}
Customize the HTTP client
Use WithHTTPClient to replace the default HTTP client when the standard parameters are insufficient.
Before running the sample code, replace the<region-id>placeholder with your actual region and endpoint, such as orap-southeast-1.
package main
import (
"crypto/tls"
"net/http"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/transport"
)
func main() {
// Common timeout or other settings.
transConfig := transport.Config{
// The connection timeout. Default: 5 seconds.
ConnectTimeout: oss.Ptr(10 * time.Second),
// The timeout for reading data from and writing data to a connection. Default: 10 seconds.
ReadWriteTimeout: oss.Ptr(20 * time.Second),
// The idle connection timeout. Default: 50 seconds.
IdleConnectionTimeout: oss.Ptr(40 * time.Second),
// The keep-alive timeout for a network connection. Default: 30 seconds.
KeepAliveTimeout: oss.Ptr(40 * time.Second),
// Enables HTTP redirection. Disabled by default.
EnabledRedirect: oss.Ptr(true),
}
// http.Transport settings.
var transports []func(*http.Transport)
// The maximum number of connections. Default: 100.
transports = append(transports, transport.MaxConnections(200))
// The maximum time to wait for a server's first response header after the request headers are written if the request has an 'Expect: 100-Continue' header. Default: 1 second.
transports = append(transports, transport.ExpectContinueTimeout(2*time.Second))
// The minimum TLS version. Default: TLS 1.2.
transports = append(transports, transport.TLSMinVersion(tls.VersionTLS13))
// Skips certificate verification. The default is false (certificates are verified).
transports = append(transports, transport.InsecureSkipVerify(true))
// For more transport parameters, see https://pkg.go.dev/net/http#Transport.
// Create a custom HTTP client.
customClient := transport.NewHttpClient(&transConfig, transports...)
cfg := oss.LoadDefaultConfig().
WithHttpClient(customClient).
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("<region-id>")
// Create an OSS client.
client := oss.NewClient(cfg)
// Use the client to perform subsequent operations...
}
Access credential configuration
Choose a credential method that fits your authentication needs.
Use a RAM user's AK
For long-term access in secure environments, initialize a credential provider with a RAM user's AccessKey pair (AccessKey ID and AccessKey secret). Manual key management increases security risks.
-
An Alibaba Cloud account has full permissions. A leaked AccessKey pair is a major security risk. Use a RAM user's AccessKey pair with minimum required permissions.
-
Create an AccessKey for the RAM user. The AccessKey ID and secret are shown only at creation. Save them immediately — if lost, create a new pair.
Environment variables
-
Set environment variables using the AccessKey pair of a RAM user.
Linux
-
Run the following commands on the CLI to add the configurations of the environment variables to the
~/.bashrcfile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Apply the changes.
source ~/.bashrc -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Run the following command in the terminal to view the default shell type:
echo $SHELL-
Configure environment variables based on the default shell type.
Zsh
-
Run the following commands to add the configurations of the environment variables to the
~/.zshrcfile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Apply the changes.
source ~/.zshrc -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Run the following commands to add the configurations of the environment variables to the
~/.bash_profilefile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Apply the changes.
source ~/.bash_profile -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Run the following commands in CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Check whether the environment variables take effect:
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
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)-
Check whether the environment variable takes effect:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
-
After setting environment variables, restart your IDE, terminal, and any running applications to load them.
-
Load credentials from environment variables.
Before you run this sample code, replace the
<region-id>placeholder with your actual region and endpoint, such as orap-southeast-1.package main import ( "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) func main() { // Set the region based on your requirements. region := "<region-id>" // Load access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. provider := credentials.NewEnvironmentVariableCredentialsProvider() // Load the default configuration, and then set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Static credentials
Hard-code static credentials directly in your application.
Do not embed access credentials in application code for production environments. This method is for testing purposes only.
Before you run this sample code, replace the<region-id>placeholder with your actual region and endpoint, such as orap-southeast-1.
package main
import (
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Set the region based on your requirements.
region := "<region-id>"
// Specify the AccessKey ID and AccessKey secret of the RAM user.
accessKeyID := "yourAccessKeyID"
accessKeySecret := "yourAccessKeySecret"
// Use the NewStaticCredentialsProvider method to directly set the AccessKey ID and AccessKey secret.
provider := credentials.NewStaticCredentialsProvider(accessKeyID, accessKeySecret)
// Load the default configuration, and then set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(provider).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
log.Printf("ossclient: %v", client)
}
STS temporary access credentials
For temporary OSS access, initialize a credential provider with STS credentials (AccessKey ID, AccessKey secret, and security token). You must manage token refresh manually.
-
Obtain temporary access credentials by calling AssumeRole - Obtain temporary access credentials for a role.
-
Obtain temporary access credentials with an SDK: Use STS temporary access credentials to access OSS.
-
STS tokens expire after the duration you specify. Expired tokens cannot be used.
-
For a list of STS service endpoints, see Service Endpoints.
Environment variables
-
Set environment variables with your temporary access credentials.
Mac OS X/Linux/Unix
Warning-
These credentials are the STS temporary access credentials (AccessKey ID, AccessKey secret, and security token), not a RAM user's AccessKey pair.
-
An AccessKey ID 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
Warning-
These credentials are the STS temporary access credentials (AccessKey ID, AccessKey secret, and security token), not a RAM user's AccessKey pair.
-
An AccessKey ID 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> -
-
Load credentials from environment variables.
Before you run the sample code, replace the
<region-id>placeholder with an actual region and endpoint, such as orap-southeast-1.package main import ( "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) func main() { // Set the region based on your requirements. region := "<region-id>" // Load access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are set. provider := credentials.NewEnvironmentVariableCredentialsProvider() // Load the default configuration, and then set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Static credentials
You can hard-code temporary access credentials in your application.
Do not embed access credentials in production code. This method is for testing only.
Before you run the sample code, replace the<region-id>placeholder with an actual region and endpoint, such as orap-southeast-1.
package main
import (
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// Set the region based on your requirements.
region := "<region-id>"
// Use the temporary access credentials (AccessKey ID, AccessKey secret, and security token) from STS.
// Do not use the credentials of a RAM user.
// Note that an AccessKey ID from STS starts with `STS.`.
accessKeyID := "STS.****************"
accessKeySecret := "yourAccessKeySecret"
// Specify the STS security token.
stsToken := "yourSecurityToken"
// Use the NewStaticCredentialsProvider method to directly set the AccessKey ID, AccessKey secret, and STS token.
provider := credentials.NewStaticCredentialsProvider(accessKeyID, accessKeySecret, stsToken)
// Load the default configuration, and then set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(provider).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
log.Printf("ossclient: %v", client)
}
Use RAMRoleARN
For cross-account or delegated OSS access, use RAMRoleARN. The Credentials tool automatically obtains and refreshes STS tokens via AssumeRole. Use the policy parameter to restrict permissions.
-
An Alibaba Cloud account has full permissions. A leaked access key is a major security risk. Use a RAM user's access key with minimum required permissions.
-
Create an access key for the RAM user. The access key ID and secret are shown only at creation. Save them immediately — if lost, create a new pair.
-
Create a role to obtain a RAMRoleARN.
-
Add the credentials dependency.
go get github.com/aliyun/credentials-go/credentials -
Configure access credentials.
Before you run the sample code, replace the
<region-id>placeholder with an actual region, such as orap-southeast-1.package main import ( "context" "log" "os" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" openapicred "github.com/aliyun/credentials-go/credentials" ) func main() { // Set the region based on your requirements. region := "<region-id>" config := new(openapicred.Config). // Specify the credential type. This value must be ram_role_arn. SetType("ram_role_arn"). // Obtain the access key ID and access key secret for the RAM user from environment variables. SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")). SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")). // The following parameters are set with placeholder strings. In a production environment, you should load these values from a secure source, such as environment variables. // Specify the ARN of the RAM role to assume. The format is acs:ram::$accountID:role/$roleName. SetRoleArn("ALIBABA_CLOUD_ROLE_ARN"). // The conventional environment variable for RoleArn is ALIBABA_CLOUD_ROLE_ARN. // Specify a custom role session name to distinguish between different tokens. SetRoleSessionName("ALIBABA_CLOUD_ROLE_SESSION_NAME"). // The conventional environment variable for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME. // (Optional) Restrict the permissions of the STS token. SetPolicy("Policy"). // (Optional) Specify the validity period of the STS token. SetRoleSessionExpiration(3600) arnCredential, gerr := openapicred.NewCredential(config) provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) { if gerr != nil { return credentials.Credentials{}, gerr } cred, err := arnCredential.GetCredential() if err != nil { return credentials.Credentials{}, err } return credentials.Credentials{ AccessKeyID: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, }, nil }) // Load the default configuration, and set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Use an ECSRAMRole
For applications on ECS, ECI, or Container Service for Kubernetes worker nodes, use ECSRAMRole. It automatically refreshes STS tokens for ECS, ECI, or Container Service for Kubernetes worker nodes, eliminating manual credential management. Create a role before proceeding.
-
Add the credentials dependency.
go get github.com/aliyun/credentials-go/credentials -
Configure access credentials.
Before you run the sample code, replace the
<region-id>placeholder with your region and endpoint, such as orap-southeast-1.package main import ( "context" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" openapicred "github.com/aliyun/credentials-go/credentials" ) func main() { // Set the region. region := "<region-id>" config := new(openapicred.Config). // Specify the credential type. Set the value to ecs_ram_role. SetType("ecs_ram_role"). // (Optional) Specify the role name. If omitted, the OSS client automatically discovers one. Specifying the role name is recommended to reduce requests. SetRoleName("RoleName") arnCredential, gerr := openapicred.NewCredential(config) provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) { if gerr != nil { return credentials.Credentials{}, gerr } cred, err := arnCredential.GetCredential() if err != nil { return credentials.Credentials{}, err } return credentials.Credentials{ AccessKeyID: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, }, nil }) // Load the default configuration and set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Use OIDCRoleARN
For untrusted applications on Container Service for Kubernetes (ACK) worker nodes, use OIDC-based RRSA to enforce pod-level least privilege. ACK mounts an OIDC token file per pod, and the Credentials tool calls AssumeRoleWithOIDC to obtain STS tokens automatically. Use RRSA to configure RAM permissions for a service account to isolate pod permissions.
-
Add the credentials dependency.
go get github.com/aliyun/credentials-go/credentials -
Configure access credentials.
Before you run the sample code, replace the
<region-id>placeholder with your region and endpoint, such as orap-southeast-1.package main import ( "context" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" openapicred "github.com/aliyun/credentials-go/credentials" ) func main() { // Specify the region. region := "<region-id>" config := new(openapicred.Config). // The credential type. Must be "oidc_role_arn". SetType("oidc_role_arn"). // Specify the ARN of the OIDC provider. The format is acs:ram::account-id:oidc-provider/provider-name. SetOIDCProviderArn("OIDCProviderArn"). // Specify the path to the OIDC token file. SetOIDCTokenFilePath("OIDCTokenFilePath"). // Specify a custom role session name to distinguish between tokens. SetRoleSessionName("RoleSessionName"). // The default environment variable for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME. // (Optional) Specify the policy to use when assuming the role. SetPolicy("Policy"). // The ARN of the ram role to assume, in the format acs:ram::account-id:role/role-name. SetRoleArn("RoleArn"). // The session duration in seconds. SetSessionExpiration(3600) arnCredential, gerr := openapicred.NewCredential(config) provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) { if gerr != nil { return credentials.Credentials{}, gerr } cred, err := arnCredential.GetCredential() if err != nil { return credentials.Credentials{}, err } return credentials.Credentials{ AccessKeyID: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, }, nil }) // Load the default configuration and set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Custom credential provider
Implement a custom provider if the standard methods do not meet your requirements.
-
Use the credentials.CredentialsProviderFunc interface
Before you run the sample code, replace the
<region-id>placeholder with a valid region and endpoint, such asap-southeast-1.package main import ( "context" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) func main() { // Set the region based on your requirements. region := "<region-id>" // Create a custom credential provider. provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) { // Return long-term credentials. return credentials.Credentials{AccessKeyID: "id", AccessKeySecret: "secret"}, nil // Return temporary credentials. //return credentials.Credentials{AccessKeyID: "id", AccessKeySecret: "secret", SecurityToken: "token"}, nil }) // Load the default configuration and set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) } -
Implement the credentials.CredentialsProvider interface
Before you run the sample code, replace the
<region-id>placeholder with a valid region and endpoint, such asap-southeast-1.package main import ( "context" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) type CustomerCredentialsProvider struct { // TODO } func NewCustomerCredentialsProvider() CustomerCredentialsProvider { return CustomerCredentialsProvider{} } func (s CustomerCredentialsProvider) GetCredentials(_ context.Context) (credentials.Credentials, error) { // Return long-term credentials. return credentials.Credentials{AccessKeyID: "id", AccessKeySecret: "secret"}, nil // Return temporary credentials. //return credentials.Credentials{AccessKeyID: "id", AccessKeySecret: "secret", SecurityToken: "token"}, nil } func main() { // Set the region based on your requirements. region := "<region-id>" // Create a custom credential provider. provider := NewCustomerCredentialsProvider() // Load the default configuration and set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Use the default credential provider chain
If no parameters are provided, the SDK uses the default credential provider chain to find credentials automatically.
Before you run the sample code, replace the<region-id>placeholder with your region and endpoint, such as orap-southeast-1.
package main
import (
"context"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
osscred "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
"github.com/aliyun/credentials-go/credentials"
)
func main() {
// Set the region based on your requirements.
region := "<region-id>"
// Passing nil uses the default credential provider chain to find credentials.
arnCredential, gerr := credentials.NewCredential(nil)
provider := osscred.CredentialsProviderFunc(func(ctx context.Context) (osscred.Credentials, error) {
if gerr != nil {
return osscred.Credentials{}, gerr
}
cred, err := arnCredential.GetCredential()
if err != nil {
return osscred.Credentials{}, err
}
return osscred.Credentials{
AccessKeyID: *cred.AccessKeyId,
AccessKeySecret: *cred.AccessKeySecret,
SecurityToken: *cred.SecurityToken,
}, nil
})
// Load the default configuration and set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(provider).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
log.Printf("ossclient: %v", client)
}
Troubleshooting
OSS errors include an HTTP status code, message, request ID, and EC error code. Use the EC code to identify the root cause.
-
For example, when you use the following code to download an object that does not exist:
package main import ( "context" "flag" "io" "log" "os" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) // Define global variables. var ( region string // The region where the bucket is located. bucketName string // The name of the bucket. objectName string // The name of the object. ) // The init function initializes command-line parameters. func init() { flag.StringVar(®ion, "region", "", "The region in which the bucket is located.") flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.") flag.StringVar(&objectName, "object", "", "The name of the object.") } func main() { // Parse command-line parameters. flag.Parse() // Check if the bucket name is empty. if len(bucketName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, bucket name required") } // Check if the region is empty. if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region required") } // Check if the object name is empty. if len(objectName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, object name required") } // Define the output file path. outputFile := "downloaded.txt" // Replace this with the desired file path. // Load the default configuration and set the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) // Create a request to get the object. request := &oss.GetObjectRequest{ Bucket: oss.Ptr(bucketName), // The name of the bucket. Key: oss.Ptr(objectName), // The name of the object. } // Get the object and process the result. result, err := client.GetObject(context.TODO(), request) if err != nil { log.Fatalf("failed to get object %v", err) } defer result.Body.Close() // Ensure the response body is closed when the function finishes. // Read the entire object content at once. data, err := io.ReadAll(result.Body) if err != nil { log.Fatalf("failed to read object %v", err) } // Write the content to the file. err = os.WriteFile(outputFile, data, 0644) if err != nil { log.Fatalf("failed to write to output file %v", err) } log.Printf("file downloaded successfully to %s", outputFile) } -
The following is an example of a returned error message. It includes the EC error code 'EC': '0026-00000001', which uniquely identifies the cause of the error.
2025/03/07 15:13:46 failed to get object operation error GetObject: Error returned by Service. Http Status Code: 404. Error Code: NoSuchKey. Request Id: 67CA9CAADC44E03938AD91F0. Message: The specified key does not exist.. EC: 0026-00000001. Timestamp: 2025-03-07 07:13:46 +0000 UTC. Request Endpoint: GET https://xxx.oss-cn-hangzhou.aliyuncs.com/asdgkhfk. -
To troubleshoot the error using the EC error code from the example, follow these steps:
-
Open the OpenAPI Self-diagnosis Platform.
-
In the search box, enter the EC error code, such as 0026-00000001. Then, paste the error message that contains the request ID into the text box and click Diagnose.
-
The diagnosis shows the error cause and solution. For EC error code
0026-00000001: the target object does not exist. Possible causes include a failed upload, lifecycle rule deletion, deletion by another user, or cross-region replication sync. Verify the object with HeadObject, check versions with ListObjectVersions, and review naming conventions, lifecycle rules, permissions, and replication rules. Related errors: NoSuchKey and NoSuchVersion.
-
Sample code
Available sample code and source files:
|
Description |
Sample file |
|
- |
|
|
- |
|
|
- |
|
|
- |