All Products
Search
Document Center

Object Storage Service:Get started with OSS SDK for Go

Last Updated:Nov 04, 2024

This topic describes how to use Object Storage Service (OSS) SDK for Go 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.

Install the Go compilation and runtime environment

Download and install the Go compilation and runtime environment by referring to Installing Go from source. Run the following command to check whether Go is installed:

go version

Install OSS SDK for Go

Run the following command to obtain the code package:

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

Configure access credentials

Before you use OSS SDK for Go, you need to configure access credentials. In this example, the AccessKey pair of a RAM user is used. For more information about how to configure access credentials, see Configure access credentials. For more information about how to obtain the AccessKey pair of a RAM user, see CreateAccessKey.

Run the following command to configure access credentials by using the AccessKey pair of the RAM user:

Mac OS X/Linux/Unix

export OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID>
export OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>

Windows

set OSS_ACCESS_KEY_ID <ALIBABA_CLOUD_ACCESS_KEY_ID>
set OSS_ACCESS_KEY_SECRET <ALIBABA_CLOUD_ACCESS_KEY_SECRET>

Demo projects

The following demo shows how to create an OSSClient instance, create a bucket, and upload, download, list, and delete objects.

  1. Create the main.go file in the directory of your demo project.

    package main
    
    import (
    	"log"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    var client *oss. Client // Specify the global variable used to store the OSSClient instance.
    
    func main() {
    	// Specify the name of the bucket. 
    	bucketName := "yourBucketName"
    	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    	endpoint := "yourEndpoint"
    
    	// Check whether the environment variables are configured. 
    	if endpoint == "" || bucketName == "" {
    		log.Fatal("Please set yourEndpoint and bucketName.")
    	}
    
    	// Obtain access credentials from environment variables. 
    	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    	if err != nil {
    		handleError(err)
    	}
    
    	// Create an OSSClient instance. 
    	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Specify the version of the signature algorithm.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New(endpoint, "", "", clientOptions...)
    	if err != nil {
    		handleError(err)
    	}
    
    	// Display the client information. 
    	log.Printf("Client: %#v\n", client)
    
    	// Sample operation: create a bucket. 
    	if err := createBucket(bucketName); err != nil {
    		handleError(err)
    	}
    
    	// Sample operation: upload an object. 
    	objectName := "file.txt"
    	localFileName := "/path/to/local/file.txt"
    	if err := uploadFile(bucketName, objectName, localFileName); err != nil {
    		handleError(err)
    	}
    
    	// Sample operation: download an object. 
    	downloadedFileName := "/path/to/downloaded/file.txt"
    	if err := downloadFile(bucketName, objectName, downloadedFileName); err != nil {
    		handleError(err)
    	}
    
    	// Sample operation: list an object. 
    	if err := listObjects(bucketName); err != nil {
    		handleError(err)
    	}
    
    	// Sample operation: delete an object. 
    	if err := deleteObject(bucketName, objectName); err != nil {
    		handleError(err)
    	}
    }
    
    // Call handleError to handle unrecoverable errors and terminate the program after recording the error messages. 
    func handleError(err error) {
    	log.Fatalf("Error: %v", err)
    }
    
    // Call CreateBucket to create an OSS bucket. 
    // Specify the following parameters:
    //
    // bucketName: the name of the bucket. 
    // endpoint: the endpoint of the region in which the bucket is located. 
    //
    // If the bucket is created, a log is generated. Otherwise, an error message is returned. 
    func createBucket(bucketName string) error {
    	// Create the bucket. 
    	err := client.CreateBucket(bucketName)
    	if err != nil {
    		return err
    	}
    
    	// After the bucket is created, a log is generated. 
    	log.Printf("Bucket created successfully: %s", bucketName)
    	return nil
    }
    
    // Call uploadFile to upload a local file to an OSS bucket. 
    // Specify the following parameters:
    //
    // bucketName: the name of the bucket. 
    // objectName: the full path of the object. Do not include the bucket name in the full path. 
    // localFileName: the full path of the local file. 
    // endpoint: the endpoint of the region in which the bucket is located. 
    //
    // If the local file is uploaded, a log is generated. Otherwise, an error message is returned. 
    func uploadFile(bucketName, objectName, localFileName string) error {
    	// Obtain the bucket information. 
    	bucket, err := client.Bucket(bucketName)
    	if err != nil {
    		return err
    	}
    
    	// Upload the local file. 
    	err = bucket.PutObjectFromFile(objectName, localFileName)
    	if err != nil {
    		return err
    	}
    
    	// After the local file is uploaded, a log is generated. 
    	log.Printf("File uploaded successfully to %s/%s", bucketName, objectName)
    	return nil
    }
    
    // Call downloadFile to download an object from an OSS bucket to a local path. 
    // Specify the following parameters:
    //
    // bucketName: the name of the bucket. 
    // objectName: the full path of the object. Do not include the bucket name in the full path. 
    // downloadedFileName: the full path of the local file that you want to store the downloaded object. 
    // endpoint: the endpoint of the region in which the bucket is located. 
    //
    // If the object is downloaded, a log is generated. Otherwise, an error message is returned. 
    func downloadFile(bucketName, objectName, downloadedFileName string) error {
    	// Obtain the bucket information. 
    	bucket, err := client.Bucket(bucketName)
    	if err != nil {
    		return err
    	}
    
    	// Download the object. 
    	err = bucket.GetObjectToFile(objectName, downloadedFileName)
    	if err != nil {
    		return err
    	}
    
    	// After the object is downloaded, a log is generated. 
    	log.Printf("File downloaded successfully to %s", downloadedFileName)
    	return nil
    }
    
    // Call listObjects to list all objects in an OSS bucket. 
    // Specify the following parameters:
    //
    // bucketName: the name of the bucket. 
    // endpoint: the endpoint of the region in which the bucket is located. 
    //
    // If the objects are listed, all objects are displayed. Otherwise, an error message is returned. 
    func listObjects(bucketName string) error {
    	// Obtain the bucket information. 
    	bucket, err := client.Bucket(bucketName)
    	if err != nil {
    		return err
    	}
    
    	// List objects. 
    	marker := ""
    	for {
    		lsRes, err := bucket.ListObjects(oss.Marker(marker))
    		if err != nil {
    			return err
    		}
    
    		// Display the listed objects. By default, 100 objects are returned at a time. 
    		for _, object := range lsRes.Objects {
    			log.Printf("Object: %s", object.Key)
    		}
    
    		if !lsRes.IsTruncated {
    			break
    		}
    		marker = lsRes.NextMarker
    	}
    
    	return nil
    }
    
    // Call deleteObject to delete an object from an OSS bucket. 
    // Specify the following parameters:
    //
    // bucketName: the name of the bucket. 
    // objectName: the name of the object that you want to delete. 
    // endpoint: the endpoint of the region in which the bucket is located. 
    //
    // If the object is deleted, a log is generated. Otherwise, an error message is returned. 
    func deleteObject(bucketName, objectName string) error {
    	// Obtain the bucket information. 
    	bucket, err := client.Bucket(bucketName)
    	if err != nil {
    		return err
    	}
    
    	// Delete the object. 
    	err = bucket.DeleteObject(objectName)
    	if err != nil {
    		return err
    	}
    
    	// After the object is deleted, a log is generated. 
    	log.Printf("Object deleted successfully: %s/%s", bucketName, objectName)
    	return nil
    }
  2. Replace bucketName, endpoint, objectName, localFileName, and downloadedFileName in the main.go file with the actual values based on your business requirements.

  3. Run the following command:

    go run main.go

References