go mod is used). Plus, the necessary environment variables such as GOPATH should be set properly.SecretId and SecretKey. SecretId is used to identify the API requester, while SecretKey is a key used for signature string encryption and authentication by the server. You can get them on the API Key Management page as shown below:

*.tencentcloudapi.com and varies by product. For example, the endpoint of CVM is cvm.tencentcloudapi.com. For specific endpoints, please see the API documentation of the corresponding product.OS | Command |
Linux/macOS | 1 goexport GOPROXY=https://mirrors.tencent.com/go/ |
Windows | 1 goset GOPROXY=https://mirrors.tencent.com/go/ |
GO111MODULE should be auto or on, and go mod init xxx should be executed in your project . If you use GOPATH, please see the full installation method.GOPATH and Go Modules.Installation Method | Description | Command |
On-Demand installation (recommended) | Install the common basic package | 1 bashgo get -v -u github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common |
| Install the corresponding product package (such as CVM) | 1 bashgo get -v -u github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm |
Full installation | Download the packages of all Tencent Cloud products at once | 1 bashgo get -v -u github.com/tencentcloud/tencentcloud-sdk-go |
go mod, the SDK version number has been reduced from v3.x to v1.x, and all tags of v3.0.* and 3.0.* were removed on May 10, 2021. If you need to backtrack previous tags, please refer to the commit2tag file in the root directory of the project.$GOPATH/src/github.com/tencentcloud directory.DescribeInstances API for querying the CVM instance list has a request structure DescribeInstancesRequest and a response structure DescribeInstancesResponse.package mainimport ("fmt""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("secretId", "secretKey")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())}
package mainimport ("fmt""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() {// Essential steps:// Instantiate an authentication object. The Tencent Cloud account key pair `secretId` and `secretKey` need to be passed in as the input parameters.// You can also write the key pair directly into the code, but be careful not to copy, upload, or share the code to others;// otherwise, the key pair may be leaked, causing damage to your properties.credential := common.NewCredential("secretId", "secretKey")// Nonessential steps// Instantiate a client configuration object. You can specify the timeout period and other configuration itemscpf := profile.NewClientProfile()// The SDK uses the POST method by default.// If you have to use the GET method, you can set it here, but the GET method cannot handle some large requests.// Do not modify the default settings unless absolutely necessary.cpf.HttpProfile.ReqMethod = "POST"// The SDK has a default timeout period. Do not adjust it unless absolutely necessary.// If needed, check in the code to get the latest default value.cpf.HttpProfile.ReqTimeout = 30// The SDK automatically specifies the domain name. Generally, you don't need to specify a domain name, but if you are accessing a service in a finance availability zone,// you have to manually specify the domain name, such as cvm.ap-shanghai-fsi.tencentcloudapi.com for the Shanghai Finance availability zonecpf.HttpProfile.Endpoint = "cvm.tencentcloudapi.com"// The SDK uses `TC3-HMAC-SHA256` for signing by default, which is more secure but slightly reduces the performance.// Do not modify the default settings unless absolutely necessary.cpf.SignMethod = "TC3-HMAC-SHA256"// The SDK uses `zh-CN` calls to return Chinese content by default. You can also set it to `en-US` to return English content.// However, most products or APIs do not fully support returns in English.// Do not modify the default settings unless absolutely necessary.cpf.Language = "en-US"// Print logs. The default value is `false`// cpf.Debug = true// Instantiate the client object of the requested product (with CVM as an example)// The second parameter is the region information. You can directly enter the string `ap-guangzhou` or import the preset constantclient, _ := cvm.NewClient(credential, regions.Guangzhou, cpf)// Instantiate a request object. You can further set the request parameters according to the API called and actual conditions// You can directly check the SDK source code to determine which attributes of `DescribeInstancesRequest` can be set.// An attribute may be of a basic type or import another data structure.// You are recommended to use the IDE for development where you can easily redirect to and view the documentation of each API and data structure.request := cvm.NewDescribeInstancesRequest()// Settings of a basic parameter.// This API allows setting the number of instances returned, which is specified as only one here.// The SDK uses the pointer style to specify parameters, so even for basic parameters, you need to use pointers to assign values to them.// The SDK provides encapsulation functions for importing the pointers of basic parametersrequest.Limit = common.Int64Ptr(1)// Settings of an array.// This API allows filtering by specified instance ID; however, as it conflicts with the `Filter` parameter to be demonstrated next, it is commented out here.// request.InstanceIds = common.StringPtrs([]string{"ins-r8hr2upy"})// Settings of a complex object.// In this API, `Filters` is an array whose elements are complex objects `Filter`, and the member `Values` of `Filter` are string arrays.request.Filters = []*cvm.Filter{&cvm.Filter{Name: common.StringPtr("zone"),Values: common.StringPtrs([]string{"ap-guangzhou-1"}),},}// Call the API you want to access through the client object. You need to pass in the request objectresponse, err := client.DescribeInstances(request)// Handle the exceptionif _, ok := err.(*errors.TencentCloudSDKError); ok {fmt.Printf("An API error has returned: %s", err)return}// This is a direct failure instead of SDK exception. You can add other troubleshooting measures in the real code.if err != nil {panic(err)}// Print the returned JSON stringfmt.Printf("%s\\n", response.ToJsonString())}
profile.ClientProfile.// Nonessential steps// Instantiate a client configuration object. You can specify the timeout period and other configuration itemscpf := profile.NewClientProfile()
cpf.HttpProfile.ReqMethod = "POST"
cpf.HttpProfile.ReqTimeout = 30
cvm.ap-shanghai-fsi.tencentcloudapi.com.cpf.HttpProfile.Endpoint = "cvm.tencentcloudapi.com"
TC3-HMAC-SHA256 for signing by default, which is more secure but slightly reduces the performance.cpf.SignMethod = "HmacSHA1"
false.cpf.Debug = true
https_proxy; otherwise, it may not be called normally, and a connection timeout exception will be thrown.GODEBUG=netdns=cgo or specify the -tags 'netcgo' parameter when compiling go build so as to get the nscd cache.import "crypto/tls"...client, _ := cvm.NewClient(credential, regions.Guangzhou, cpf)tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true},}client.WithHttpTransport(tr)...
v1.0.181, Tencent Cloud SDK for Go defines the error codes returned by each product as constants. You can directly call them for handling without manual definition required. If you use an IDE (such as GoLand) for development, you can use their code hint features to choose directly; for example,...//Your other go code// Handling errorsresponse, err := client.DescribeInstances(request)if terr, ok := err.(*errors.TencentCloudSDKError); ok {code :=terr.GetCode()if code == cvm.FAILEDOPERATION_ILLEGALTAGKEY{fmt.Printf("Handling error: FailedOperation.IllegalTagKey,%s", err)}else if code == cvm.UNAUTHORIZEDOPERATION{fmt.Printf("Handling error: UnauthorizedOperation,%s", err)}else{fmt.Printf("An API error has returned: %s", err)}return}...
// DescribeInstances// This API is used to query the details of one or multiple instances.//////// * You can query the details of an instance according to its `ID`, name, billing mode, or other information. For more information on how to filter information, please see `Filter`.//// * If no parameter is defined, the status of a certain number of instances under the current account will be returned. The number is specified by `Limit` and is 20 by default.//// * The latest operation (LatestOperation) and the latest operation status (LatestOperationState) of the instance can be queried.//// Possible error codes:// FAILEDOPERATION_ILLEGALTAGKEY = "FailedOperation.IllegalTagKey"// FAILEDOPERATION_ILLEGALTAGVALUE = "FailedOperation.IllegalTagValue"// FAILEDOPERATION_TAGKEYRESERVED = "FailedOperation.TagKeyReserved"// INTERNALSERVERERROR = "InternalServerError"// INVALIDFILTER = "InvalidFilter"// INVALIDFILTERVALUE_LIMITEXCEEDED = "InvalidFilterValue.LimitExceeded"// INVALIDHOSTID_MALFORMED = "InvalidHostId.Malformed"// INVALIDINSTANCEID_MALFORMED = "InvalidInstanceId.Malformed"// INVALIDPARAMETER = "InvalidParameter"// INVALIDPARAMETERVALUE = "InvalidParameterValue"// INVALIDPARAMETERVALUE_IPADDRESSMALFORMED = "InvalidParameterValue.IPAddressMalformed"// INVALIDPARAMETERVALUE_INVALIDIPFORMAT = "InvalidParameterValue.InvalidIpFormat"// INVALIDPARAMETERVALUE_INVALIDVAGUENAME = "InvalidParameterValue.InvalidVagueName"// INVALIDPARAMETERVALUE_LIMITEXCEEDED = "InvalidParameterValue.LimitExceeded"// INVALIDPARAMETERVALUE_SUBNETIDMALFORMED = "InvalidParameterValue.SubnetIdMalformed"// INVALIDPARAMETERVALUE_TAGKEYNOTFOUND = "InvalidParameterValue.TagKeyNotFound"// INVALIDPARAMETERVALUE_VPCIDMALFORMED = "InvalidParameterValue.VpcIdMalformed"// INVALIDSECURITYGROUPID_NOTFOUND = "InvalidSecurityGroupId.NotFound"// INVALIDSGID_MALFORMED = "InvalidSgId.Malformed"// INVALIDZONE_MISMATCHREGION = "InvalidZone.MismatchRegion"// RESOURCENOTFOUND_HPCCLUSTER = "ResourceNotFound.HpcCluster"// UNAUTHORIZEDOPERATION_INVALIDTOKEN = "UnauthorizedOperation.InvalidToken"func (c *Client) DescribeInstances(request *DescribeInstancesRequest) (response *DescribeInstancesResponse, err error){...}
v1.0.189, Tencent Cloud SDK for Go supports the use of Common Request mode for requests. You only need to install the common package to initiate calls to any Tencent Cloud product.ClientProfile.Request structure is checked for whether it has the ClientToken field, and if so, it will be considered an idempotent request. Only idempotent requests will be retried automatically in case of network errors, while exceptions will be thrown for non-idempotent requests to prevent inconsistent results caused by multiple replays of the requests.package mainimport ("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 the maximum number of retry attemptsprof.NetworkFailureRetryDuration = profile.ExponentialBackoff // Define the retry interval timeclient, _ := cvm.NewClient(credential, regions.Guangzhou, prof)// ...}
ClientProfile.package mainimport ("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.RateLimitExceededMaxRetries = 3 // Define the maximum number of retry attemptsprof.RateLimitExceededRetryDuration = profile.ExponentialBackoff // Define the retry interval timeclient, _ := cvm.NewClient(credential, regions.Guangzhou, prof)// ...}
ClientToken parameter will be automatically injected into the request (if the request has an empty ClientToken field). If you manually specify ClientToken, the injection process will be skipped.ClientToken provides global uniqueness below a 100000/s concurrency.imported and not used: "os" is reported, it means that the package os is not used in the code. Therefore, simply remove it.Feedback