Relevant Resources
The source code download address for XML Go SDK for COS: XML Go SDK.
Download address for the Example Demo: COS XML Go SDK sample.
For more information, see the COS Go SDK API documentation.
For all sample code in the SDK documentation, see SDK Code Samples.
For the change log of the SDK, see ChangeLog.
For SDK FAQ, see: Go SDK FAQ.
Note:
If you encounter errors such as missing functions or methods when using the SDK, please upgrade to the latest version and try again.
Environment Configuration and Preparation
Golang: used to download and install the Go compilation and run environment. Go to the Golang official website to download it.
The minimum supported Go version is 1.16, and it is recommended to use the latest stable version 1.24.10.
You need to obtain a Tencent Cloud API key. This key is a prerequisite for your use of the various features of the COS SDK.
Installing the SDK
Run the following command to install the Go SDK for COS.
go get -u github.com/tencentyun/cos-go-sdk-v5
Initialize COS Service
The following describes how to use the COS Go SDK to perform basic operations, such as initializing a client, creating a bucket, querying the bucket list, uploading an object, querying the object list, downloading an object, and deleting an object.
Initialize COS
Use the COS domain name to create a Client structure for COS Go.
Method Prototype
func NewClient(uri *BaseURL, httpClient *http.Client) *Client
Parameter Description
// BaseURL The base URL required to access each APItype BaseURL struct {// Base URL for accessing APIs related to bucket and object (excluding the path part): https://examplebucket-1250000000.cos.<Region>.myqcloud.comBucketURL *url.URL// Base URL for accessing service APIs (excluding the path part): https://cos.<Region>.myqcloud.comServiceURL *url.URL// Base URL for accessing Batch APIs (excluding the path part): https://<UIN>.cos-control.<Region>.myqcloud.comBatchURL *url.URL// Base URL for accessing CI (excluding the path part): https://examplebucket-1250000000.ci.<Region>.myqcloud.com.CIURL *url.URL}
Parameter Name | Parameter Description | Type | Required |
BucketURL | Base URL for accessing APIs related to bucket and object (excluding the path part) | string | Yes |
ServiceURL | Base URL for accessing service APIs (excluding the path part) | string | No |
BatchURL | Base URL for accessing Batch APIs (excluding the path part). | string | No |
CIURL | Base URL for accessing CI (excluding the path part). | string | No |
Configure Access Key for API
Access Keys are a prerequisite for COS SDK to access all services. The keys are divided into: temporary keys and permanent keys.
Note:
It is recommended that users use sub-account keys + environment variables to call the SDK to enhance the security of SDK usage. When authorizing sub-accounts, follow the least privilege principle to prevent the leakage of resources other than the target bucket or objects.
If you must use permanent secret keys, it is recommended that you follow the Principle of Least Privilege to restrict the scope of permissions for these keys.
Temporary secret key generation and usage can be found in Temporary Secret Key Generation and Usage Guidelines.
// Replace examplebucket-1250000000 and COS_REGION with your actual information.// Bucket name, composed of bucketname-appid. The appid must be included. You can view the bucket name in the COS console. https://console.cloud.tencent.com/cos5/bucket// COS_REGION can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket. For details about regions, see https://cloud.tencent.com/document/product/436/6224u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")b := &cos.BaseURL{BucketURL: u}// 2. Temporary Secret Keysclient := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// If you are using temporary secret keys, you need to enter them. For guidelines on generating and using temporary secret keys, see https://cloud.tencent.com/document/product/436/14048SecretID: "SECRETID",SecretKey: "SECRETKEY",SessionToken: "SECRETTOKEN",},})if client != nil {// Call COS requests.}
// Replace examplebucket-1250000000 and COS_REGION with your actual information.// Bucket name, composed of bucketname-appid. The appid must be included. You can view the bucket name in the COS console. https://console.cloud.tencent.com/cos5/bucket// COS_REGION can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket. For details about regions, see https://cloud.tencent.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")// Used for Get Service queries, defaults to all regions: service.cos.myqcloud.com.su, _ := url.Parse("https://cos.COS_REGION.myqcloud.com")b := &cos.BaseURL{BucketURL: u, ServiceURL: su}// 1. Permanent Secret Keysclient := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{SecretID: os.Getenv("SECRETID"), // User's SecretId. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140SecretKey: os.Getenv("SECRETKEY"), // User's SecretKey. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140},})
Configure Domain Name
By modifying the BaseURL, you can directly use a custom domain name or global acceleration domain name to access COS.
// Use a domain name for global acceleration to access COS.u, _ := url.Parse("http://<BucketName-APPID>.cos.accelerate.myqcloud.com")b := &cos.BaseURL{BucketURL: u}// 2. Temporary Secret Keysclient := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// If you are using temporary secret keys, you need to enter them. For guidelines on generating and using temporary secret keys, see https://cloud.tencent.com/document/product/436/14048.SecretID: "SECRETID",SecretKey: "SECRETKEY",SessionToken: "SECRETTOKEN",},})
CRC64 Check (Optional)
COS Go SDK has CRC64 verification for file uploads enabled by default.
Note:
COS Go SDK requires version v0.7.23 or above.
It is strongly recommended that users do not disable CRC64 verification.
// Replace examplebucket-1250000000 and COS_REGION with your actual information.// Bucket name, composed of bucketname-appid. The appid must be included. You can view the bucket name in the COS console. https://console.cloud.tencent.com/cos5/bucket// COS_REGION can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket. For details about regions, see https://cloud.tencent.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")b := &cos.BaseURL{BucketURL: u}// 2. Temporary Secret Keysclient := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// If you are using temporary secret keys, you need to enter them. For guidelines on generating and using temporary secret keys, see https://cloud.tencent.com/document/product/436/14048.SecretID: "SECRETID",SecretKey: "SECRETKEY",SessionToken: "SECRETTOKEN",},})// Disable CRC64 verification.client.Conf.EnableCRC = false
Access the COS Service
package mainimport ("context""net/http""net/url""os""github.com/tencentyun/cos-go-sdk-v5")func main() {// Replace examplebucket-1250000000 and COS_REGION with your actual information.// Bucket name, composed of bucketname-appid. The appid must be included. You can view the bucket name in the COS console. https://console.cloud.tencent.com/cos5/bucket// COS_REGION can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket. For details about regions, see https://cloud.tencent.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")b := &cos.BaseURL{BucketURL: u}c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{SecretID: os.Getenv("SECRETID"), // User's SecretId. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140SecretKey: os.Getenv("SECRETKEY"), // User's SecretKey. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140},})_, err := c.Bucket.Put(context.Background(), nil)if err != nil {panic(err)}}
package mainimport ("context""fmt""net/http""os""github.com/tencentyun/cos-go-sdk-v5")func main() {c := cos.NewClient(nil, &http.Client{Transport: &cos.AuthorizationTransport{SecretID: os.Getenv("SECRETID"), // User's SecretId. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140SecretKey: os.Getenv("SECRETKEY"), // User's SecretKey. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140},})s, _, err := c.Service.Get(context.Background())if err != nil {panic(err)}for _, b := range s.Buckets {fmt.Printf("%#v\n", b)}}
package mainimport ("context""net/http""net/url""os""strings""github.com/tencentyun/cos-go-sdk-v5")func main() {// Replace examplebucket-1250000000 and COS_REGION with your actual information.// Bucket name, composed of bucketname-appid. The appid must be included. You can view the bucket name in the COS console. https://console.cloud.tencent.com/cos5/bucket// COS_REGION can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket. For details about regions, see https://cloud.tencent.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")b := &cos.BaseURL{BucketURL: u}c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{SecretID: os.Getenv("SECRETID"), // User's SecretId. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140SecretKey: os.Getenv("SECRETKEY"), // User's SecretKey. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140},})// The object key is the unique identifier of the object in the bucket.// For example, in the object's domain name `examplebucket-1250000000.cos.COS_REGION.myqcloud.com/test/objectPut.go`, the object key is test/objectPut.go.name := "test/objectPut.go"// 1. Upload an object via a string.f := strings.NewReader("test")_, err := c.Object.Put(context.Background(), name, f, nil)if err != nil {panic(err)}// 2. Upload an object via a local file._, err = c.Object.PutFromFile(context.Background(), name, "../test", nil)if err != nil {panic(err)}// 3. Upload an object via a file stream.fd, err := os.Open("./test")if err != nil {panic(err)}defer fd.Close()_, err = c.Object.Put(context.Background(), name, fd, nil)if err != nil {panic(err)}}
package mainimport ("context""fmt""net/http""net/url""os""github.com/tencentyun/cos-go-sdk-v5")func main() {// Replace examplebucket-1250000000 and COS_REGION with your actual information.// Bucket name, composed of bucketname-appid. The appid must be included. You can view the bucket name in the COS console. https://console.cloud.tencent.com/cos5/bucket// COS_REGION can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket. For details about regions, see https://cloud.tencent.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")b := &cos.BaseURL{BucketURL: u}c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{SecretID: os.Getenv("SECRETID"), // User's SecretId. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140.SecretKey: os.Getenv("SECRETKEY"), // User's SecretKey. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140.},})opt := &cos.BucketGetOptions{Prefix: "test",MaxKeys: 3,}v, _, err := c.Bucket.Get(context.Background(), opt)if err != nil {panic(err)}for _, c := range v.Contents {fmt.Printf("%s, %d\n", c.Key, c.Size)}}
package mainimport ("context""fmt""io""net/http""net/url""os""github.com/tencentyun/cos-go-sdk-v5")func main() {// Replace examplebucket-1250000000 and COS_REGION with your actual information.// Bucket name, composed of bucketname-appid. The appid must be included. You can view the bucket name in the COS console. https://console.cloud.tencent.com/cos5/bucket// COS_REGION can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket. For details about regions, see https://cloud.tencent.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")b := &cos.BaseURL{BucketURL: u}c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{SecretID: os.Getenv("SECRETID"), // User's SecretId. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140.SecretKey: os.Getenv("SECRETKEY"), // User's SecretKey. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140.},})// 1. Obtain the object via the response body.name := "test/objectPut.go"resp, err := c.Object.Get(context.Background(), name, nil)if err != nil {panic(err)}bs, _ := io.ReadAll(resp.Body)resp.Body.Close()fmt.Printf("%s\n", string(bs))// 2. Obtain the object to a local file._, err = c.Object.GetToFile(context.Background(), name, "exampleobject", nil)if err != nil {panic(err)}}
Note:
Once an object is deleted, its corresponding data will no longer be accessible.
package mainimport ("context""net/http""net/url""os""github.com/tencentyun/cos-go-sdk-v5")func main() {// Replace examplebucket-1250000000 and COS_REGION with your actual information.// Bucket name, composed of bucketname-appid. The appid must be included. You can view the bucket name in the COS console. https://console.cloud.tencent.com/cos5/bucket// COS_REGION can be viewed in the console at https://console.cloud.tencent.com/cos5/bucket. For details about regions, see https://cloud.tencent.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.COS_REGION.myqcloud.com")b := &cos.BaseURL{BucketURL: u}c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{SecretID: os.Getenv("SECRETID"), // User's SecretId. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140.SecretKey: os.Getenv("SECRETKEY"), // User's SecretKey. It is recommended to use sub-account keys, with authorization following the principle of least privilege to mitigate usage risks. For how to obtain sub-account keys, refer to https://cloud.tencent.com/document/product/598/37140.},})name := "test/objectPut.go"_, err := c.Object.Delete(context.Background(), name)if err != nil {panic(err)}}