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.
Before you use OSS SDK for Go 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, see Configure an OSSClient instance.
Prerequisites
Configure environment variables
Configure environment variables for the AccessKey pair.
Linux
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
Run the following command to apply the changes:
source ~/.bashrc
Run the following commands to check whether the environment variables take 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
~/.zshrc
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
Run the following command to apply the changes:
source ~/.zshrc
Run the following commands to check whether the environment variables take 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_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
Run the following command to apply the changes:
source ~/.bash_profile
Run the following commands to check whether the environment variables take 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"
Run the following commands to 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)
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)
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(®ion, "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(®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 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(®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 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(®ion, "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(®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 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
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.
Replace "yourRegion", "yourBucketName", and "yourObjectName" in the following command with your actual configurations. Replace "yourRegion" with the region of the bucket. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
go run main.go --region "yourRegion" --bucket "yourBucketName" --object "yourObjectName"
References
For more information about OSS SDK for Go V2, visit Alibaba Cloud OSS SDK for Go v2.
For more information about the sample code, visit GitHub.