Tencent Cloud SDK for Go

repository·master·Indexed 20 days ago

https://github.com/tencentcloud/tencentcloud-sdk-go

A development toolkit for interacting with the Tencent Cloud API 3.0 platform. It provides structured Request/Response models and client implementations for all Tencent Cloud products. The SDK supports Go 1.9+ and includes features such as automatic region failover, multiple credential providers (Env, Config File, STS, Instance Role, TKE OIDC), automatic retries for network errors and rate limiting via ClientToken idempotency, and customizable client profiles for HTTP proxy and timeout configurations.

Tokens
109.3K
Snippets
553
Records
635
Agent score
73%

What's inside tencentcloud-sdk-go

  1. How to set Request parameters using pointers

    master

    The SDK uses a pointer-based style for assigning request parameters. Even for basic types (like int64 or string), you must pass a pointer. The SDK provides helper functions to wrap these values easily:

    • common.Int64Ptr(val): For int64 types.
    • common.StringPtr(val): For string types.
    • common.StringPtrs([]string{...}): For slices of strings.

    Example for complex objects: When setting a field that is a slice of complex structs (like Filters), you must pass a slice of pointers to those structs.

    // Basic type using pointer helper
    request.Limit = common.Int64Ptr(1)
    
    // Complex object (slice of pointers to structs)
    request.Filters = []*cvm.Filter{
        &cvm.Filter{
            Name:   common.StringPtr("zone"),
            Values: common.StringPtrs([]string{"ap-guangzhou-1"}),
        },
    }
  2. Handling empty arrays and omitempty serialization

    master

    The SDK's behavior regarding empty arrays has evolved across versions:

    • v1.0.738 and earlier: Uses omitempty tags. Both nil arrays and zero-length empty arrays are not serialized. To send an empty array, you previously had to use CommonClient.
    • >= v1.0.739: Uses omitnil tags. nil arrays are ignored, but empty arrays (length 0) are correctly serialized and sent.
    • >= v1.0.885: A switch was added. If you want to revert to the old behavior (where empty arrays are not sent), you can set json.OmitBehaviour = json.OmitEmpty.
  3. How ClientToken works for idempotency

    master

    When network error retries or rate limit retries are enabled, the SDK automatically injects a ClientToken parameter into the request if the request contains a ClientToken field and it is currently empty.

    If you manually specify a ClientToken, the SDK will skip the automatic injection process. The injected ClientToken provides global uniqueness for concurrency levels below 100000/s.

  4. Manage Credentials using various Providers

    master

    The SDK supports multiple ways to manage credentials (since v1.0.217):

    1. Environment Variables: Uses TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY. Use common.DefaultEnvProvider().
    2. Configuration Files: Reads from TENCENTCLOUD_CREDENTIALS_FILE or default paths (~/.tencentcloud/credentials on Linux/macOS, c:\Users\NAME\.tencentcloud\credentials on Windows). Use common.DefaultProfileProvider().
    3. Role Assumption (STS): Uses a pre-created CAM role. Use common.DefaultRoleArnProvider(secretId, secretKey, roleArn).
    4. Instance Role: Accesses temporary credentials via instance metadata. Use common.DefaultCvmRoleProvider().
    5. TKE OIDC Credentials: For TKE Pod identity. Use common.DefaultTkeOIDCRoleArnProvider().
    6. Provider Chain: Attempts providers in a specific order. Use common.DefaultProviderChain() for the default order (Env -> Config File -> Instance Role) or common.NewProviderChain([]common.Provider{...}) for a custom order.
    // Example: Using a custom provider chain
    provider1 := common.DefaultCvmRoleProvider()
    provider2 := common.DefaultEnvProvider()
    customProviderChain := []common.Provider{provider1, provider2}
    provider := common.NewProviderChain(customProviderChain)
    credential, err := provider.GetCredential()
  5. Configure Region Disaster Recovery

    master

    Since v1.0.227, the SDK supports automatic region failover. If a request meets the failure threshold (failures >= 5 AND failure rate >= 75%), the SDK automatically switches to a backup region.

    To enable this, set DisableRegionBreaker to false and provide a BackupEndpoint. The BackupEndpoint should be the domain (e.g., ap-guangzhou.tencentcloudapi.com), and the SDK will automatically prepend the service name (e.g., cvm.ap-guangzhou.tencentcloudapi.com). Note that this feature only supports synchronous requests for a single client.

        // Enable failover
        cpf.DisableRegionBreaker = false
        // Set backup endpoint (do not include service name)
        cpf.BackupEndpoint = "ap-guangzhou.tencentcloudapi.com"
  6. Disable Keep-alive (Short Connections)

    master

    By default, every SDK client uses keep-alive mode (the Connection header is set to keep-alive). To use short connections (setting the Connection header to close), configure a custom http.Transport with DisableKeepAlives: true and apply it to the client using WithHttpTransport.

        client, _ := cvm.NewClient(credential, regions.Guangzhou, cpf)
        tp := &http.Transport{
            DisableKeepAlives: true,
        }
        client.WithHttpTransport(tp)
  7. Quick Start: Query CVM Instances

    master

    The SDK follows a pattern where every API has a corresponding Request and Response structure. This example demonstrates how to initialize credentials, create a client for the Cloud Virtual Machine (CVM) service, and call the DescribeInstances method.

    Note: For security, avoid hardcoding credentials. Use environment variables like TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY.

    package main
    
    import (
    	"fmt"
    	"os"
    	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
    	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
    	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
    	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
    	cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312"
    )
    
    func main() {
    	credential := common.NewCredential(
    		os.Getenv("TENCENTCLOUD_SECRET_ID"),
    		os.Getenv("TENCENTCLOUD_SECRET_KEY"),
    	)
    
    	client, _ := cvm.NewClient(credential, regions.Guangzhou, profile.NewClientProfile())
    
    	request := cvm.NewDescribeInstancesRequest()
    	response, err := client.DescribeInstances(request)
    
    	if _, ok := err.(*errors.TencentCloudSDKError); ok {
    		fmt.Printf("An API error has returned: %s", err)
    		return
    	}
    	if err != nil {
    		panic(err)
    	}
    	fmt.Printf("%s\n", response.ToJsonString())
    }
  8. Configure automatic retries for network errors

    master

    The SDK can be configured to automatically retry requests when temporary network errors or timeouts occur. This feature is disabled by default.

    Important: Idempotency Requirement To prevent inconsistent results from multiple re-plays, the SDK only performs automatic retries for idempotent requests. It checks the Request struct for a ClientToken field via reflection. If the field exists, the request is considered idempotent and eligible for retry. If the field is missing, the SDK will throw an exception instead of retrying.

    Configure retries using the ClientProfile object by setting NetworkFailureMaxRetries and NetworkFailureRetryDuration.

    package main
    
    import (
    	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
    	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
    	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
    	cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312"
    )
    
    func main() {
    	credential := common.NewCredential("secretId", "secretKey")
    	prof := profile.NewClientProfile()
    	prof.NetworkFailureMaxRetries = 3                               // Define max retries
    	prof.NetworkFailureRetryDuration = profile.ExponentialBackoff   // Define retry interval
    	client, _ := cvm.NewClient(credential, regions.Guangzhou, prof)
    
    	// ...
    }
  9. Ignore Server Certificate Validation

    master

    For testing or extreme edge cases, you can bypass server certificate verification by providing a custom http.Transport with InsecureSkipVerify: true.

    Warning: Do not use this in production as it exposes you to man-in-the-middle attacks.

    import "crypto/tls"
    ...
        client, _ := cvm.NewClient(credential, regions.Guangzhou, cpf)
        tr := &http.Transport{
            TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
        }
        client.WithHttpTransport(tr)
  10. Install the Tencent Cloud SDK for Go

    master

    You can install the SDK using go get or by downloading the source code.

    Prerequisites

    • Go 1.9 or higher (Go 1.14+ required if using go mod).
    • Access to Tencent Cloud Console to enable products and obtain SecretID and SecretKey.

    To speed up downloads, use the Tencent Cloud mirror:

    Linux or MacOS:

    export GOPROXY=https://mirrors.tencent.com/go/

    Windows:

    set GOPROXY=https://mirrors.tencent.com/go/

    This method requires GO111MODULE=auto or on and an initialized module (go mod init). To minimize build size, install only the common base package and the specific product package you need (e.g., cvm).

    Note: Ensure the common package and all product packages are kept at the same version.

    1. Install the common base package:
    go get -v -u github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common
    1. Install a specific product package (e.g., cvm):
    go get -v -u github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm

    Install via Source

    Download the code from CNB, GitHub, or Gitee and install it to $GOPATH/src/github.com/tencentcloud.

    go get -v -u github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common
    go get -v -u github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm
  11. Configure HTTP Proxy

    master

    In environments requiring a proxy, you can either set the system environment variable https_proxy or configure the proxy directly in the client's HttpProfile.

        // With authentication
        clientProfile.HttpProfile.Proxy = "http://username:password@127.0.0.1:1080"
        // Without authentication
        clientProfile.HttpProfile.Proxy = "http://127.0.0.1:1080"