### Download Object Example Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/object.md Basic example of downloading an object and reading its content. Ensure to close the response body. ```go resp, err := client.Object.Get(context.Background(), "myfile.txt", nil) if err != nil { panic(err) } deferr resp.Body.Close() // Read response body data, err := ioutil.ReadAll(resp.Body) fmt.Println(string(data)) ``` -------------------------------- ### Complete COS Go SDK v5 Configuration Example Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/configuration.md This example demonstrates a full configuration of the COS Go SDK, including setting the base URL, customizing the HTTP client with authorization transport, and configuring SDK options like retry mechanisms and CRC checks. ```go package main import ( "context" "net/http" "net/url" "os" "time" "github.com/tencentyun/cos-go-sdk-v5" ) func main() { // 1. Configure base URL u, _ := url.Parse("https://mybucket.cos.ap-beijing.myqcloud.com") baseURL := &cos.BaseURL{BucketURL: u} // 2. Configure HTTP client httpClient := &http.Client{ Timeout: 100 * time.Second, Transport: &cos.AuthorizationTransport{ SecretID: os.Getenv("COS_SECRETID"), SecretKey: os.Getenv("COS_SECRETKEY"), Expire: time.Hour, }, } // 3. Create client client := cos.NewClient(baseURL, httpClient) // 4. Configure SDK options client.Conf = &cos.Config{ EnableCRC: true, RequestBodyClose: false, RetryOpt: cos.RetryOptions{ Count: 3, Interval: 100 * time.Millisecond, AutoSwitchHost: false, }, ObjectKeySimplifyCheck: true, } // 5. Use client resp, err := client.Object.Get(context.Background(), "myfile.txt", nil) if err != nil { panic(err) } defer resp.Body.Close() } ``` -------------------------------- ### Test Suite Setup Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/vendor/github.com/stretchr/testify/README.md Defines a test suite struct, including setup methods and test methods. The suite is run using `suite.Run`. ```go // Basic imports import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // Define the suite, and absorb the built-in basic suite // functionality from testify - including a T() method which // returns the current testing context type ExampleTestSuite struct { suite.Suite VariableThatShouldStartAtFive int } // Make sure that VariableThatShouldStartAtFive is set to five // before each test func (suite *ExampleTestSuite) SetupTest() { suite.VariableThatShouldStartAtFive = 5 } // All methods that begin with "Test" are run as tests within a // suite. func (suite *ExampleTestSuite) TestExample() { assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) } // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run func TestExampleTestSuite(t *testing.T) { suite.Run(t, new(ExampleTestSuite)) } ``` -------------------------------- ### Install COS Go SDK Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/index.md Installs the Tencent COS Go SDK v5 using the go get command. ```bash go get -u github.com/tencentyun/cos-go-sdk-v5 ``` -------------------------------- ### Describe Job Example Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/batch.md Example of how to retrieve and display details of a specific batch job using its jobID. It prints the job's ID, status, priority, and progress summary. ```go result, _, err := client.Batch.DescribeJob(context.Background(), jobID) if err != nil { panic(err) } job := result.Job fmt.Printf("Job ID: %s\n", job.JobID) fmt.Printf("Status: %s\n", job.JobStatus) fmt.Printf("Priority: %d\n", job.Priority) fmt.Printf("Progress: %d/%d succeeded, %d failed\n", job.ProgressSummary.NumberOfTasksSucceeded, job.ProgressSummary.TotalNumberOfTasks, job.ProgressSummary.NumberOfTasksFailed) ``` -------------------------------- ### Minimal COS Client Setup Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Initialize a COS client with the minimal required configuration, including parsing the bucket URL. ```go // Minimal setup u, _ := url.Parse("https://bucket.cos.region.myqcloud.com") c := cos.NewClient(&cos.BaseURL{BucketURL: u}, nil) ``` -------------------------------- ### Download Object with Progress Tracking Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/object.md Example of downloading an object while tracking download progress using a listener. ```go opt := &cos.ObjectGetOptions{ Listener: &cos.ProgressListener{ ProgressChangedCallback: func(event *cos.ProgressEvent) { fmt.Printf("Downloaded: %d/%d bytes\n", event.ConsumedBytes, event.TotalBytes) }, }, } resp, err := client.Object.Get(context.Background(), "myfile.txt", opt) ``` -------------------------------- ### Setup COS Client Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Demonstrates how to create a COS client instance. Ensure you have the necessary imports and provide your bucket URL and authentication credentials. ```go import ( "context" "net/http" "net/url" "os" "time" "github.com/tencentyun/cos-go-sdk-v5" ) // Create client u, _ := url.Parse("https://bucket-123456789.cos.ap-beijing.myqcloud.com") client := cos.NewClient(&cos.BaseURL{BucketURL: u}, &http.Client{ Timeout: 100 * time.Second, Transport: &cos.AuthorizationTransport{ SecretID: os.Getenv("COS_SECRETID"), SecretKey: os.Getenv("COS_SECRETKEY"), }, }) ``` -------------------------------- ### Example: Initiate Multipart Upload Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/object-multipart.md Demonstrates how to initiate a multipart upload for a large file and retrieve the UploadID. Ensure you handle potential errors. ```go result, _, err := client.Object.InitiateMultipartUpload(context.Background(), "largefile.bin", nil) if err != nil { panic(err) } uploadID := result.UploadID fmt.Printf("Initiated multipart upload. UploadID: %s\n", uploadID) ``` -------------------------------- ### Image Processing Example Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/ci.md Demonstrates how to initialize the CI client, define image processing rules, and execute the processing pipeline. ```APIDOC ## ImageProcess ### Description Processes an image using a defined set of rules. This can include resizing, format conversion, and adding watermarks. ### Method `client.CI.ImageProcess(context.Context, string, *cos.ImageProcessOptions) (*cos.ImageProcessResult, *Response, error)` ### Parameters #### Path Parameters - **objectKey** (string) - Required - The key of the object in the bucket to process. #### Request Body - **opt** (*cos.ImageProcessOptions) - Optional - Options for image processing, including `IsPicInfo` and `Rules`. - **IsPicInfo** (int) - Optional - Set to 1 to return image information. - **Rules** ([]cos.PicOperationsRules) - Optional - A list of processing rules to apply. - **FileId** (string) - Required - The ID of the output file. - **Rule** (string) - Required - The image processing rule string. ### Request Example ```go opt := &cos.ImageProcessOptions{ IsPicInfo: 1, Rules: []cos.PicOperationsRules{ { FileId: "thumbnail.jpg", Rule: "imageMogr2/thumbnail/!100x100r/gravity/center/crop/100x100", }, { FileId: "converted.png", Rule: "imageMogr2/format/png", }, }, } result, _, err := client.CI.ImageProcess(context.Background(), "original.jpg", opt) ``` ### Response #### Success Response (200) - **OriginalInfo** (*PicOriginalInfo) - Original image metadata. - **ProcessResults** ([]PicProcessObject) - Processed images. - **ImgTargetRecResult** (*ImgTargetRecResult) - Target recognition results (optional). #### Response Example ```json { "OriginalInfo": { "ImageInfo": { "Width": 1920, "Height": 1080, "Format": "jpg", "Quality": 90, "Size": 102400, "ColorModel": "RGB" } }, "ProcessResults": [ { "Location": "thumbnail.jpg", "Width": 100, "Height": 100, "Format": "jpg", "Size": 5120 }, { "Location": "converted.png", "Width": 1920, "Height": 1080, "Format": "png", "Size": 204800 } ] } ``` ``` -------------------------------- ### Basic Assertion Example Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/vendor/github.com/stretchr/testify/README.md Shows how to import and use the `assert` package for basic boolean assertions in a test function. ```go package yours import ( "testing" "github.com/stretchr/testify/assert" ) func TestSomething(t *testing.T) { assert.True(t, true, "True is true!") } ``` -------------------------------- ### Mock Object Example Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/vendor/github.com/stretchr/testify/README.md Demonstrates how to use a mock object to set expectations on a method call and assert that those expectations were met. ```go func TestSomething(t *testing.T) { // create an instance of our test object testObj := new(MyMockedObject) // setup expectations testObj.On("DoSomething", 123).Return(true, nil) // call the code we are testing targetFuncThatDoesSomethingWithObj(testObj) // assert that the expectations were met testObj.AssertExpectations(t) } ``` ```go func TestSomethingElse(t *testing.T) { // create an instance of our test object testObj := new(MyMockedObject) // setup expectations with a placeholder in the argument list testObj.On("DoSomething", mock.Anything).Return(true, nil) // call the code we are testing targetFuncThatDoesSomethingWithObj(testObj) // assert that the expectations were met testObj.AssertExpectations(t) } ``` -------------------------------- ### Example of Encoding Picture Operations Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/ci.md Demonstrates how to use the EncodePicOperations function with a sample PicOperations struct. ```go pic := &cos.PicOperations{ IsPicInfo: 1, Rules: []cos.PicOperationsRules{ { FileId: "thumb.jpg", Rule: "imageMogr2/thumbnail/!50x50r/gravity/center/crop/50x50", }, }, } encoded := cos.EncodePicOperations(pic) fmt.Println(encoded) ``` -------------------------------- ### COS Client Setup with All Options Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Initialize a COS client with all available configuration options, including multiple URLs, custom HTTP client with timeout and session token, and SDK configurations like CRC and retry options. ```go baseURL := &cos.BaseURL{ BucketURL: bucketURL, ServiceURL: serviceURL, BatchURL: batchURL, CIURL: ciURL, } httpClient := &http.Client{ Timeout: 100 * time.Second, Transport: &cos.AuthorizationTransport{ SecretID: "xxx", SecretKey: "xxx", SessionToken: "xxx", Expire: time.Hour, }, } c := cos.NewClient(baseURL, httpClient) c.Conf.EnableCRC = true c.Conf.RetryOpt.Count = 3 ``` -------------------------------- ### Download Object with Range Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/object.md Example of downloading a specific byte range of an object. Useful for large files. ```go opt := &cos.ObjectGetOptions{ Range: "bytes=0-99", // First 100 bytes } resp, err := client.Object.Get(context.Background(), "largefile.bin", opt) ``` -------------------------------- ### Access Service APIs - Get Buckets Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/client.md Demonstrates how to access the Service API to retrieve a list of buckets associated with the account. ```go // Access service APIs buckets, _, err := client.Service.Get(ctx) ``` -------------------------------- ### Initialize COS Client and Get Object Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/README.md Demonstrates how to initialize the COS client with your bucket, region, and credentials, and then retrieve an object from COS. Ensure your bucket name follows the format {name}-{appid} and set your SecretID and SecretKey, preferably via environment variables. ```go package main import ( "context" "fmt" "io/ioutil" "net/http" "net/url" "os" "time" "github.com/tencentyun/cos-go-sdk-v5" ) func main() { //将修改为真实的信息 //bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式 u, _ := url.Parse("https://.cos..myqcloud.com") b := &cos.BaseURL{BucketURL: u} c := cos.NewClient(b, &http.Client{ //设置超时时间 Timeout: 100 * time.Second, Transport: &cos.AuthorizationTransport{ //如实填写账号和密钥,也可以设置为环境变量 SecretID: os.Getenv("COS_SECRETID"), SecretKey: os.Getenv("COS_SECRETKEY"), }, }) name := "test/hello.txt" resp, err := c.Object.Get(context.Background(), name, nil) if err != nil { panic(err) } bs, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() fmt.Printf("%s\n", string(bs)) } ``` -------------------------------- ### Complete Batch Job Workflow Example Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/batch.md Demonstrates the full lifecycle of a batch job: creation, setting status to Ready, and monitoring progress. Ensure you have initialized the COS client and provided necessary parameters like bucket names and target resources. ```go package main import ( "context" "fmt" "time" "github.com/tencentyun/cos-go-sdk-v5" ) func main() { // Assume baseURL and httpClient are initialized // baseURL := &cos.BaseURL{BucketURL: "https://my-bucket-1250000000.cos.ap-guangzhou.myqcloud.com"} // httpClient := &http.Client{} client := cos.NewClient(baseURL, httpClient) // Step 1: Create job createOpt := &cos.CreateJobOptions{ Report: &cos.BatchJobReport{ Bucket: "report-bucket", Enabled: "true", Format: "Report_CSV_20180820", Prefix: "batch-reports/", }, Operation: &cos.BatchJobOperation{ PutObjectCopy: &cos.BatchJobOperationCopy{ TargetResource: "cos://target-bucket", TargetKeyPrefix: "archived/", }, }, Priority: 10, } result, _, err := client.Batch.CreateJob(context.Background(), createOpt) if err != nil { panic(err) } jobID := result.JobID fmt.Printf("Created job: %s\n", jobID) // Step 2: Update job status to Ready statusOpt := &cos.UpdateJobStatusOptions{ RequestedJobStatus: "Ready", } _, err = client.Batch.UpdateJobStatus(context.Background(), jobID, statusOpt) if err != nil { panic(err) } fmt.Println("Job ready to run") // Step 3: Monitor job progress for i := 0; i < 10; i++ { describeResult, _, err := client.Batch.DescribeJob(context.Background(), jobID) if err != nil { panic(err) } job := describeResult.Job fmt.Printf("Status: %s\n", job.JobStatus) fmt.Printf("Progress: %d/%d tasks completed\n", job.ProgressSummary.NumberOfTasksSucceeded + job.ProgressSummary.NumberOfTasksFailed, job.ProgressSummary.TotalNumberOfTasks) if job.JobStatus == "Complete" || job.JobStatus == "Failed" { fmt.Printf("Job finished with status: %s\n", job.JobStatus) break } time.Sleep(5 * time.Second) } } ``` -------------------------------- ### Example: Uploading a Part File Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/object-multipart.md Demonstrates how to open a file, upload it as a part of a multipart upload, and retrieve the ETag from the response. Ensure ContentLength is specified for readers other than standard types. ```go partFile, err := os.Open("part1.bin") if err != nil { panic(err) } defer partFile.Close() resp, err := client.Object.UploadPart( context.Background(), "largefile.bin", uploadID, 1, // Part number partFile, nil, ) if err != nil { panic(err) } etag := resp.Header.Get("ETag") fmt.Printf("Part 1 uploaded. ETag: %s\n", etag) ``` -------------------------------- ### Get Bucket Versioning Configuration Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Retrieves the versioning configuration for a bucket. ```go // Get result, _, _ := client.Bucket.GetVersioning(context.Background()) ``` -------------------------------- ### Service Access Example Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/client.md Demonstrates how to access and utilize different service APIs provided by the client, such as listing buckets, managing objects, and initiating multipart uploads. ```APIDOC ## Service Access Example ### Description This example shows how to interact with various service APIs available through the client, including operations on services, buckets, and objects. ### Example Usage ```go // Access service APIs to list buckets buckets, _, err := client.Service.Get(ctx) // List objects in a bucket with specific options listResp, _, err := client.Bucket.Get(ctx, &cos.BucketGetOptions{MaxKeys: 100}) // Download an object from the bucket resp, err := client.Object.Get(ctx, "myfile.txt", nil) // Initiate a multipart upload for a large file uploadID, _, err := client.Object.InitiateMultipartUpload(ctx, "largefile.bin", nil) ``` ``` -------------------------------- ### Get Bucket Website Configuration Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/bucket.md Retrieves the website configuration for a bucket. Use this to check current website settings. ```go func (s *BucketService) GetWebsite(ctx context.Context, opt ...*BucketGetWebsiteOptions) (*BucketGetWebsiteResult, *Response, error) ``` -------------------------------- ### Image Processing Example Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/ci.md Demonstrates how to process an image using ImageProcessOptions, specifying resizing rules and output file name. It prints the location of the processed image. ```go opt := &cos.ImageProcessOptions{ IsPicInfo: 1, Rules: []cos.PicOperationsRules{ { FileId: "resized.jpg", Rule: "imageMogr2/format/jpeg/w/200/h/200", }, }, } result, _, err := client.CI.ImageProcess(context.Background(), "photo.jpg", opt) if err != nil { panic(err) } fmt.Printf("Output: %s\n", result.ProcessResults[0].Location) ``` -------------------------------- ### Set Bucket Tagging Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Sets or replaces the tagging information for a bucket. This example adds a 'Type: Data' tag. ```go // Set client.Bucket.PutTagging(context.Background(), &cos.BucketPutTaggingOptions{ TagSet: []cos.BucketTagSet{ {Key: "Type", Value: "Data"}, }, }) ``` -------------------------------- ### List all objects with pagination Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/bucket.md This example demonstrates how to list all objects within a bucket, handling pagination to retrieve all items even if they exceed the initial response limit. ```APIDOC ## Get Bucket Objects ### Description Lists objects in a bucket with pagination support. ### Method GET ### Endpoint /bucket ### Parameters #### Query Parameters - **MaxKeys** (int) - Optional - The maximum number of keys to return. - **Marker** (string) - Optional - Specifies the object key to start listing from. Used for pagination. ### Request Example ```go marker := "" for { resp, _, err := client.Bucket.Get(context.Background(), &cos.BucketGetOptions{ MaxKeys: 1000, Marker: marker, }) if err != nil { panic(err) } for _, obj := range resp.Contents { fmt.Println(obj.Key) } if !resp.IsTruncated { break } marker = resp.NextMarker } ``` ### Response #### Success Response (200) - **Contents** ([]Object) - A list of objects in the bucket. - **IsTruncated** (bool) - Indicates if the listing is truncated and more objects are available. - **NextMarker** (string) - The marker to use for the next listing request if `IsTruncated` is true. ``` -------------------------------- ### Create and Use COS Client Example Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/client.md Demonstrates how to create a COS client with a custom HTTP client and authorization, then use it to retrieve an object. Ensure environment variables COS_SECRETID and COS_SECRETKEY are set. ```go package main import ( "context" "net/http" "net/url" "os" "time" "github.com/tencentyun/cos-go-sdk-v5" ) func main() { // Create bucket URL u, _ := url.Parse("https://mybucket.cos.ap-beijing.myqcloud.com") baseURL := &cos.BaseURL{BucketURL: u} // Create HTTP client with authorization httpClient := &http.Client{ Timeout: 100 * time.Second, Transport: &cos.AuthorizationTransport{ SecretID: os.Getenv("COS_SECRETID"), SecretKey: os.Getenv("COS_SECRETKEY"), }, } // Create COS client client := cos.NewClient(baseURL, httpClient) // Use the client resp, err := client.Object.Get(context.Background(), "myfile.txt", nil) if err != nil { panic(err) } defer resp.Body.Close() } ``` -------------------------------- ### Get Bucket Lifecycle Configuration Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Retrieves the lifecycle configuration for a bucket. ```go // Get result, _, _ := client.Bucket.GetLifecycle(context.Background()) ``` -------------------------------- ### Example Authorization Header Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/authentication.md Illustrates the structure of the Authorization header automatically added by the SDK, including signing algorithm, access key, timestamps, and signature. ```text Authorization: q-sign-algorithm=sha1&q-ak=AKIDz8krbsJ5GPXXXXXXXX&q-sign-time=1234567890;1234571490&q-key-time=1234567890;1234571490&q-header-list=host;x-cos-storage-class&q-url-param-list=prefix&q-signature=0123456789abcdef0123456789abcdef01234567 ``` -------------------------------- ### Customize Client Configuration Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/client.md Example of how to customize the SDK client's configuration, including disabling CRC verification, adjusting retry attempts and intervals, and modifying object key validation. ```go client := cos.NewClient(baseURL, httpClient) // Customize configuration client.Conf.EnableCRC = false // Disable CRC verification client.Conf.RetryOpt.Count = 5 // Increase retry attempts client.Conf.RetryOpt.Interval = 100 * time.Millisecond client.Conf.ObjectKeySimplifyCheck = false // Disable key validation ``` -------------------------------- ### List All Buckets Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/service.md Retrieves a list of all buckets associated with your account. This is the most basic usage of the Service Get API. ```go resp, _, err := client.Service.Get(context.Background()) if err != nil { panic(err) } for _, bucket := range resp.Buckets { fmt.Printf("Bucket: %s (Region: %s, Created: %s)\n", bucket.Name, bucket.Location, bucket.CreationDate) } ``` -------------------------------- ### Configure COS Client Access Settings Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/configuration.md Example of initializing a COS client and modifying its configuration for CRC verification and retry attempts. ```go client := cos.NewClient(baseURL, httpClient) client.Conf.EnableCRC = false // Disable CRC verification client.Conf.RetryOpt.Count = 5 // Set retry attempts ``` -------------------------------- ### Mock Object Setup in Go with Testify Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/vendor/github.com/stretchr/testify/README.md The mock package facilitates creating mock objects for dependency injection in tests. Define mock types and their methods to simulate behavior and record calls. ```go package yours import ( "testing" "github.com/stretchr/testify/mock" ) /* Test objects */ // MyMockedObject is a mocked object that implements an interface // that describes an object that the code I am testing relies on. type MyMockedObject struct{ mock.Mock } // DoSomething is a method on MyMockedObject that implements some interface // and just records the activity, and returns what the Mock object tells it to. // // In the real object, this method would do something useful, but since this // is a mocked object - we're just going to stub it out. // // NOTE: This method is not being tested here, code that uses this object is. func (m *MyMockedObject) DoSomething(number int) (bool, error) { args := m.Called(number) return args.Bool(0), args.Error(1) } ``` -------------------------------- ### Set bucket lifecycle policy Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/bucket.md This example shows how to set a lifecycle policy for a bucket, defining rules for object expiration based on prefixes and days. ```APIDOC ## Put Bucket Lifecycle ### Description Sets the lifecycle configuration for a bucket. ### Method PUT ### Endpoint /bucket?lifecycle ### Parameters #### Request Body - **Rules** ([]BucketLifecycleRule) - Required - A list of lifecycle rules. - **ID** (string) - Required - The unique identifier for the rule. - **Filter** (BucketLifecycleFilter) - Optional - Specifies the objects to which the rule applies. - **Prefix** (string) - Optional - Filters objects with the specified prefix. - **Expiration** (BucketLifecycleExpiration) - Optional - Defines the expiration action. - **Days** (int) - Optional - The number of days after creation when objects expire. ``` -------------------------------- ### Set Bucket Lifecycle Configuration Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Sets the lifecycle configuration for a bucket. This example configures objects with the prefix 'logs/' to expire after 30 days. ```go // Set (expire objects after 30 days) client.Bucket.PutLifecycle(context.Background(), &cos.BucketPutLifecycleOptions{ Rules: []cos.BucketLifecycleRule{ { ID: "rule1", Filter: &cos.BucketLifecycleFilter{ Prefix: "logs/", }, Expiration: &cos.BucketLifecycleExpiration{ Days: 30, }, }, }, }) ``` -------------------------------- ### Common COS Operations Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/START_HERE.md Provides examples for common COS tasks including uploading, downloading to a file, listing objects, deleting objects, and generating presigned URLs. These snippets assume the client has already been initialized. ```go // Upload client.Object.Put(ctx, "key", file, nil) ``` ```go // Download client.Object.GetToFile(ctx, "key", "/tmp/file", nil) ``` ```go // List objects client.Bucket.Get(ctx, &cos.BucketGetOptions{MaxKeys: 100}) ``` ```go // Delete client.Object.Delete(ctx, "key") ``` ```go // Presigned URL url, _ := client.Object.GetPresignedURL(ctx, "GET", "key", ak, sk, time.Hour, nil) ``` -------------------------------- ### Get (Download Object) Function Signature Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/object.md Signature for downloading an object from a bucket. Supports context, object name, options, and version ID. ```go func (s *ObjectService) Get(ctx context.Context, name string, opt *ObjectGetOptions, id ...string) (*Response, error) ``` -------------------------------- ### Setting Environment Variables for COS Credentials Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/configuration.md This example shows how to set environment variables for COS credentials and region. These variables are commonly used to configure the SDK. ```bash export COS_SECRETID=your_access_key_id export COS_SECRETKEY=your_secret_access_key export COS_REGION=ap-beijing export COS_BUCKET=mybucket ``` -------------------------------- ### COS Client Setup with Custom Timeout Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Configure a COS client with a custom HTTP client, including a specific timeout and an authorization transport. ```go // With custom timeout c := cos.NewClient(baseURL, &http.Client{ Timeout: 30 * time.Second, Transport: &cos.AuthorizationTransport{ SecretID: "xxx", SecretKey: "xxx", }, }) ``` -------------------------------- ### Update Job Status Example Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/batch.md Example of how to update the status of a batch job using the UpdateJobStatusOptions. Ensure you have a valid jobID. ```go opt := &cos.UpdateJobStatusOptions{ RequestedJobStatus: "Ready", StatusUpdateReason: "Starting bulk copy operation", } resp, err := client.Batch.UpdateJobStatus(context.Background(), jobID, opt) if err != nil { panic(err) } fmt.Println("Job status updated") ``` -------------------------------- ### Buckets: Tagging Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Get or set tags for a bucket. ```APIDOC ## Buckets: Tagging ### Description Manages tags associated with a bucket, which can be used for organizing, managing costs, and controlling access. ### Methods - GetTagging - PutTagging ### Usage Example ```go // Get result, _, _ := client.Bucket.GetTagging(context.Background()) // Set client.Bucket.PutTagging(context.Background(), &cos.BucketPutTaggingOptions{ TagSet: []cos.BucketTagSet{ {Key: "Type", Value: "Data"}, }, }) ``` ``` -------------------------------- ### Set Bucket Lifecycle Policy - Go Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/bucket.md Configure a lifecycle rule for a bucket, such as expiring objects after a specified number of days. This example sets a rule to expire objects in the 'logs/' prefix after 90 days. ```go lifecycle := &cos.BucketLifecycleRule{ ID: "rule1", Filter: &cos.BucketLifecycleFilter{ Prefix: "logs/", }, Expiration: &cos.BucketLifecycleExpiration{ Days: 90, }, } opt := &cos.BucketPutLifecycleOptions{ Rules: []cos.BucketLifecycleRule{*lifecycle}, } _, err := client.Bucket.PutLifecycle(context.Background(), opt) ``` -------------------------------- ### Initialize COS Client and Download Object Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/START_HERE.md Demonstrates how to initialize the COS client with your bucket URL and credentials, and then download an object. Ensure your COS_SECRETID and COS_SECRETKEY environment variables are set. ```go package main import ( "context" "fmt" "net/http" "net/url" "os" "time" "github.com/tencentyun/cos-go-sdk-v5" ) func main() { // Initialize u, _ := url.Parse("https://bucket-123456789.cos.ap-beijing.myqcloud.com") client := cos.NewClient(&cos.BaseURL{BucketURL: u}, &http.Client{ Timeout: 100 * time.Second, Transport: &cos.AuthorizationTransport{ SecretID: os.Getenv("COS_SECRETID"), SecretKey: os.Getenv("COS_SECRETKEY"), }, }) // Download resp, err := client.Object.Get(context.Background(), "file.txt", nil) if err != nil { panic(err) } defer resp.Body.Close() // Use response body... } ``` -------------------------------- ### Buckets: Versioning Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Get or enable/disable versioning for a bucket. ```APIDOC ## Buckets: Versioning ### Description Manages the versioning state of a bucket, allowing you to keep multiple versions of an object to protect against accidental overwrites or deletions. ### Methods - GetVersioning - PutVersioning ### Usage Example ```go // Get result, _, _ := client.Bucket.GetVersioning(context.Background()) // Enable client.Bucket.PutVersioning(context.Background(), &cos.BucketPutVersioningOptions{ Status: "Enabled", }) ``` ``` -------------------------------- ### Buckets: Lifecycle Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Get or set the lifecycle configuration for a bucket. ```APIDOC ## Buckets: Lifecycle ### Description Manages the lifecycle of objects within a bucket, defining rules for expiration or transition based on age or other criteria. ### Methods - GetLifecycle - PutLifecycle ### Usage Example ```go // Get result, _, _ := client.Bucket.GetLifecycle(context.Background()) // Set (expire objects after 30 days) client.Bucket.PutLifecycle(context.Background(), &cos.BucketPutLifecycleOptions{ Rules: []cos.BucketLifecycleRule{ { ID: "rule1", Filter: &cos.BucketLifecycleFilter{ Prefix: "logs/", }, Expiration: &cos.BucketLifecycleExpiration{ Days: 30, }, }, }, }) ``` ``` -------------------------------- ### Get Bucket Tagging Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Retrieves the tagging information for a bucket. ```go // Get result, _, _ := client.Bucket.GetTagging(context.Background()) ``` -------------------------------- ### List Buckets with Pagination Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/service.md Demonstrates how to list buckets with pagination using `MaxKeys` and `Marker`. If `resp.IsTruncated` is true, you can use `resp.NextMarker` to fetch the subsequent page. ```go opt := &cos.ServiceGetOptions{ MaxKeys: 100, } resp, _, err := client.Service.Get(context.Background(), opt) if err != nil { panic(err) } for _, bucket := range resp.Buckets { fmt.Println(bucket.Name) } // Get next page if resp.IsTruncated { opt.Marker = resp.NextMarker nextResp, _, _ := client.Service.Get(context.Background(), opt) // Process nextResp.Buckets } ``` -------------------------------- ### Buckets: ACL Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Get or set the Access Control List (ACL) for a bucket. ```APIDOC ## Buckets: ACL ### Description Manages the Access Control List (ACL) for a bucket, allowing you to define permissions for different users or groups. ### Methods - GetACL - PutACL ### Usage Example ```go // Get result, _, _ := client.Bucket.GetACL(context.Background()) // Set client.Bucket.PutACL(context.Background(), &cos.BucketPutACLOptions{ Header: &cos.ACLHeaderOptions{ XCosACL: "private", }, }) ``` ``` -------------------------------- ### Get Bucket ACL Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Retrieves the Access Control List (ACL) for a bucket. ```go // Get result, _, _ := client.Bucket.GetACL(context.Background()) ``` -------------------------------- ### Buckets: CORS Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Get or set the Cross-Origin Resource Sharing (CORS) configuration for a bucket. ```APIDOC ## Buckets: CORS ### Description Configures Cross-Origin Resource Sharing (CORS) for a bucket, enabling web applications from different domains to access resources in the bucket. ### Methods - GetCORS - PutCORS ### Usage Example ```go // Get result, _, _ := client.Bucket.GetCORS(context.Background()) // Set client.Bucket.PutCORS(context.Background(), &cos.BucketPutCORSOptions{ Rules: []cos.BucketCORSRule{ { AllowedOrigins: []string{"https://example.com"}, AllowedMethods: []string{"GET", "PUT"}, MaxAgeSeconds: 3600, }, }, }) ``` ``` -------------------------------- ### Create, Update, and Describe Batch Jobs Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Shows how to create a batch job with a PutObjectCopy operation, update its status to 'Ready', and describe its progress. ```go // Create job result, _, _ := client.Batch.CreateJob(context.Background(), &cos.CreateJobOptions{ Operation: &cos.BatchJobOperation{ PutObjectCopy: &cos.BatchJobOperationCopy{ TargetResource: "cos://target-bucket", }, }) // Update status client.Batch.UpdateJobStatus(context.Background(), result.JobID, &cos.UpdateJobStatusOptions{ RequestedJobStatus: "Ready", }) // Check progress job, _, _ := client.Batch.DescribeJob(context.Background(), result.JobID) fmt.Printf("Progress: %d/%d\n", job.ProgressSummary.NumberOfTasksSucceeded, job.ProgressSummary.TotalNumberOfTasks) ``` -------------------------------- ### Get Bucket CORS Configuration Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Retrieves the Cross-Origin Resource Sharing (CORS) configuration for a bucket. ```go // Get result, _, _ := client.Bucket.GetCORS(context.Background()) ``` -------------------------------- ### Get Service Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/README.md Retrieves the service information for the COS account. This operation lists all buckets associated with the account. ```APIDOC ## Get Service ### Description Retrieves the service information for the COS account. This operation lists all buckets associated with the account. ### Method GET ### Endpoint / ### Parameters None ### Request Example None ### Response #### Success Response (200) - **Buckets** (Array of Bucket) - A list of buckets owned by the requester. #### Response Example ```json { "Buckets": [ { "Name": "examplebucket-1250000000", "CreationDate": "2023-01-01T12:00:00.000Z" } ] } ``` ``` -------------------------------- ### Set Bucket ACL Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Sets the Access Control List (ACL) for a bucket. Example sets the bucket to private. ```go // Set client.Bucket.PutACL(context.Background(), &cos.BucketPutACLOptions{ Header: &cos.ACLHeaderOptions{ XCosACL: "private", }, }) ``` -------------------------------- ### Filter Buckets by Tag Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/service.md Filters buckets based on specified tag key-value pairs, for example, 'Environment: Production'. ```go opt := &cos.ServiceGetOptions{ TagKey: "Environment", TagValue: "Production", } resp, _, err := client.Service.Get(context.Background(), opt) if err != nil { panic(err) } ``` -------------------------------- ### Get Bucket Encryption Configuration Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/bucket.md Retrieves the encryption configuration for a bucket. This is useful for verifying current encryption settings. ```go func (s *BucketService) GetEncryption(ctx context.Context, opt ...*BucketGetEncryptionOptions) (*BucketGetEncryptionResult, *Response, error) ``` -------------------------------- ### Access Object API - Download Object Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/client.md Illustrates how to use the Object API to download a file from a bucket. ```go // Download object resp, err := client.Object.Get(ctx, "myfile.txt", nil) ``` -------------------------------- ### Initialize COS Client Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/index.md Initializes the COS client with bucket URL and credentials. Ensure your COS_SECRETID and COS_SECRETKEY environment variables are set. ```go package main import ( "context" "net/http" "net/url" "os" "time" "github.com/tencentyun/cos-go-sdk-v5" ) func main() { // Initialize client with bucket URL and credentials u, _ := url.Parse("https://bucket-name.cos.region.myqcloud.com") b := &cos.BaseURL{BucketURL: u} c := cos.NewClient(b, &http.Client{ Timeout: 100 * time.Second, Transport: &cos.AuthorizationTransport{ SecretID: os.Getenv("COS_SECRETID"), SecretKey: os.Getenv("COS_SECRETKEY"), }, }) // Use the client to perform operations resp, err := c.Object.Get(context.Background(), "test/hello.txt", nil) if err != nil { panic(err) } defer resp.Body.Close() } ``` -------------------------------- ### Configure SDK Features and Retries Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Demonstrates how to enable/disable features like CRC verification and connection reuse, and configure retry options including count, interval, and auto-switch host. ```go // Enable/disable features client.Conf.EnableCRC = true // Verify downloads client.Conf.RequestBodyClose = false // Reuse connections client.Conf.ObjectKeySimplifyCheck = true // Validate keys // Configure retries client.Conf.RetryOpt.Count = 3 client.Conf.RetryOpt.Interval = 100 * time.Millisecond client.Conf.RetryOpt.AutoSwitchHost = true ``` -------------------------------- ### Get (List Objects) Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/api-reference/bucket.md Lists objects within a specified bucket. This operation allows for filtering and pagination of the object list. ```APIDOC ## Get (List Objects) ### Description Lists objects in a bucket. This operation supports filtering by prefix, delimiter, and marker, as well as controlling the number of returned items. ### Method GET ### Endpoint `/{bucketName}` ### Parameters #### Query Parameters - **prefix** (string) - Optional - Filters the objects to be returned, returning only those whose keys begin with the specified prefix. - **delimiter** (string) - Optional - A delimiter is a character you can use to group objects by name. It acts like a folder separator. - **encoding-type** (string) - Optional - Specifies the encoding method for the object keys. - **marker** (string) - Optional - Specifies the object key to start the listing from. Objects with keys alphabetically preceding the marker will not be included. - **max-keys** (int) - Optional - Sets the maximum number of objects to be returned in the response. ### Request Example ```go opt := &cos.BucketGetOptions{ MaxKeys: 100, Prefix: "logs/", } resp, _, err := client.Bucket.Get(context.Background(), opt) if err != nil { panic(err) } for _, obj := range resp.Contents { fmt.Printf("Key: %s, Size: %d bytes\n", obj.Key, obj.Size) } ``` ### Response #### Success Response (200) - **Name** (string) - The name of the bucket. - **Prefix** (string) - The prefix used for the listing. - **Marker** (string) - The marker used for the listing. - **NextMarker** (string) - The marker to be used for the next listing request if the results are truncated. - **Delimiter** (string) - The delimiter used for the listing. - **MaxKeys** (int) - The maximum number of keys returned in the response. - **IsTruncated** (bool) - Indicates whether the list of objects is truncated. - **Contents** ([]Object) - A list of objects in the bucket. - **CommonPrefixes** ([]string) - A list of common prefixes, used when a delimiter is specified. - **EncodingType** (string) - The encoding type used for the object keys. #### Response Example { "Name": "my-bucket", "Prefix": "logs/", "Marker": "", "NextMarker": "log_2023-01-01.txt", "Delimiter": "/", "MaxKeys": 100, "IsTruncated": true, "Contents": [ { "Key": "logs/access.log", "LastModified": "2023-10-26T10:00:00Z", "ETag": "\"abcdef1234567890\"", "Size": 1024, "Owner": { "ID": "1234567890" }, "StorageClass": "STANDARD" } ], "CommonPrefixes": [ "logs/archive/" ], "EncodingType": "url" } ``` -------------------------------- ### Configuration Options Source: https://github.com/tencentyun/cos-go-sdk-v5/blob/master/_autodocs/QUICK_REFERENCE.md Shows how to configure various aspects of the SDK client, including feature flags, connection reuse, key validation, and retry mechanisms. ```APIDOC ## Configuration This section covers various client configuration options. ### Feature Flags - `client.Conf.EnableCRC` (bool): Enable/disable CRC checksum verification for downloads. Defaults to `false`. - `client.Conf.RequestBodyClose` (bool): Controls whether to reuse connections after the request body is sent. Defaults to `true`. - `client.Conf.ObjectKeySimplifyCheck` (bool): Enable/disable validation of object keys. Defaults to `false`. ### Retry Options - `client.Conf.RetryOpt.Count` (int): The number of retry attempts. Defaults to `0`. - `client.Conf.RetryOpt.Interval` (time.Duration): The interval between retry attempts. Defaults to `0`. - `client.Conf.RetryOpt.AutoSwitchHost` (bool): Whether to automatically switch hosts on retry. Defaults to `false`. ### Credentials Update To update credentials, access the underlying transport and use `SetCredential`. #### Method Signature ```go transport := client.client.Transport.(*cos.AuthorizationTransport) transport.SetCredential(accessKey, secretKey, sessionToken) ``` ### Example Configuration ```go // Enable/disable features client.Conf.EnableCRC = true // Verify downloads client.Conf.RequestBodyClose = false // Reuse connections client.Conf.ObjectKeySimplifyCheck = true // Validate keys // Configure retries client.Conf.RetryOpt.Count = 3 client.Conf.RetryOpt.Interval = 100 * time.Millisecond client.Conf.RetryOpt.AutoSwitchHost = true // Update credentials transport := client.client.Transport.(*cos.AuthorizationTransport) transport.SetCredential("new_ak", "new_sk", "") ``` ```