All Products
Search
Document Center

Object Storage Service:Get started with OSS SDK for Go

Last Updated:Jun 19, 2025

This topic describes how to use Object Storage Service (OSS) SDK for Go V2 to perform common operations. You can learn how to install OSS SDK for Go, configure access credentials, and perform basic operations, such as creating buckets and uploading, downloading, listing, and deleting objects.

Notes

  • For more information about the regions and endpoints supported by OSS, see Regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials using OSS SDK for Go Version 2.0, see Configure access credentials.

  • Before you use OSS SDK for Go Version 2.0 to initiate a request to OSS, you must initialize and configure an OSSClient instance. In this example, an OSSClient instance is created by loading the default configurations. For more information about how to configure an OSS client using OSS SDK for Go Version 2.0, see Configure client.

Prerequisites

Configure environment variables

  1. Create an AccessKey pair for a Resource Access Management (RAM) user that has full OSS access permissions.

    Create an AccessKey pair by using ROS

    You can quickly create an AccessKey pair for a RAM user that has full OSS access permissions by using a Resource Orchestration Service (ROS) script. To do so, go to the wizard for template-based stack creation, select I confirm that Alibaba Cloud ROS may create RAM resources in the Security Confirmation section, and click Create.

    1.png

    After the AccessKey pair is created, copy the AccessKey pair on the Outputs tab.

    image

  2. Configure environment variables for the AccessKey pair.

    Linux

    1. Run the following commands on the CLI to add the configurations of the environment variables 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
      1. Run the following command to apply the changes:

        source ~/.bashrc
      2. Run the following commands to check whether the environment variables have taken effect:

        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. Configure environment variables based on the default shell type.

      Zsh

      1. Run the following commands to add the configurations of the environment variables 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 check whether the environment variables take effect:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Run the following commands to add the configurations of the environment variables 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 check whether the environment variables take effect:

        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 check whether the environment variables take effect:

      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 check whether the environment variable takes effect:

      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  3. After configuring the environment variables as described above, please restart or refresh your compilation and runtime environment, namely IDEs, command-line interfaces, other desktop applications, and background services, to ensure that the latest system environment variables are successfully loaded. 

Install OSS SDK for GO

  • Download and install a compilation and runtime environment of Go 1.18 or later. Run the following command to check whether Go is installed:

    go version

    If the existing compilation and runtime environment does not meet the requirements, go to Installing Go from source to download and install the environment.

  • Create a project directory and initialize a Go module.

    mkdir oss-go-example && cd oss-go-example && go mod init oss-go-example
  • Run the following command to obtain the OSS SDK for Go package:

    go get github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss
  • Run the following code to import the OSS SDK for Go package:

    import "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"

Demo projects

The following demo describes how to create a bucket and upload, download, list, and delete objects.

Create a bucket

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	request := &oss.PutBucketRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
	}

	// Execute a request to create a bucket.
	result, err := client.PutBucket(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket %v", err)
	}

	// Display the result of the bucket creation.
	log.Printf("put bucket result:%#v\n", result)
}

Upload an object

package main

import (
	"context"
	"flag"
	"log"
	"strings"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "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 whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Specify the content that you want to upload.
	content := "hi oss"

	// Load the default configurations and specify 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 upload an object.
	request := &oss.PutObjectRequest{
		Bucket: oss.Ptr(bucketName),        // The name of the bucket.
		Key: oss.Ptr(objectName),        // The name of the object.
		Body:   strings.NewReader(content), // The content that you want to upload.
	}

	// Execute the request to upload an object.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Display the result of the object upload.
	log.Printf("put object result:%#v\n", result)
}

Download an object

package main

import (
	"context"
	"flag"
	"io"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "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 whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify 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 query the object.
	request := &oss.GetObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
	}

	// Query the object and process the results.
	result, err := client.GetObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get object %v", err)
	}
	defer result.Body.Close() // Make sure that the response body is closed when the function is complete.

	log.Printf("get object result:%#v\n", result)

	// Read the content of the object.
	data, _ := io.ReadAll(result.Body)
	log.Printf("body:%s\n", data)
}

List objects

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify 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 list objects.
	request := &oss.ListObjectsV2Request{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
	}

	// Create a paginator.
	p := client.NewListObjectsV2Paginator(request)

	// Initialize the page number counter.
	var i int
	log.Println("Objects:")

	// Traverse each page in the paginator.
	for p.HasNext() {
		i++

		// Obtain the data of the next page.
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("failed to get page %v, %v", i, err)
		}

		// Display information about each object in the page.
		for _, obj := range page.Contents {
			log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
		}
	}
}

Delete an object

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "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 whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify 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 delete an object.
	request := &oss.DeleteObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
	}

	// Delete the object and process the results.
	result, err := client.DeleteObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete object %v", err)
	}

	// Display the result of the object deletion.
	log.Printf("delete object result:%#v\n", result)
}

Example

  1. Create the main.go file in the directory of your demo project. Copy the preceding sample code to the main.go file based on your business requirements.

  2. Replace "your region", "your bucket name", and "your object name" in the following command with the actual values. Replace "your region" with the region in which your bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. For details, see Regions and endpoints.

    go run main.go --region "your region" --bucket "your bucket name" --object "your object name"

FAQ

What do I do if the AccessDenied error is reported when using OSS SDKs?

The AccessDenied error typically occurs due to insufficient access permissions. Below are steps to resolve this issue:

  1. Verify AccessKey ID and AccessKey Secret: Please make sure that the AccessKey ID and AccessKey Secret you use are correct. For more information, see Create an AccessKey pair.

  2. Check the permissions granted to RAM users: Please make sure that the RAM user has permissions required to perform operations on the bucket or the object. For more information, see Grant permissions to a RAM user.

  3. Check bucket policies: If the error message contains 'Access denied by bucket policy,' it indicates that the error occured due to restrictions specified in the bucket policies. For more information, see Bucket policies.

  4. For information about other types of errors, see Error codes. For example, you can refer to the 03-ACCESS_CONTROL section for common errors related to access control.

References

  • For more information about the sample code, visit GitHub.