English | ็ฎไฝไธญๆ
Huawei Cloud Go Software Development Kit (Go SDK)
The Huawei Cloud Go SDK allows you to easily work with Huawei Cloud services such as Elastic Compute Service (ECS) and
Virtual Private Cloud (VPC) without the need to handle API related tasks.
This document introduces how to obtain and use Huawei Cloud Go SDK.
Requirements
-
To use Huawei Cloud Go SDK, you must have Huawei Cloud account as well as the Access Key and Secret key of the Huawei
Cloud account. You can create an AccessKey in the Huawei Cloud console. For more information,
see My Credentials.
-
To use Huawei Cloud Go SDK to access the APIs of specific service, please make sure you do have activated the service
in Huawei Cloud console if needed.
-
Huawei Cloud Go SDK requires go 1.14 or later, run command go version
to check the version of Go.
Install Go SDK
Run the following command to install Huawei Cloud Go SDK:
# Install the library of Huawei Cloud Go SDK
go get github.com/huaweicloud/huaweicloud-sdk-go-v3
Code Example
- The following example shows how to query a list of VPCs in a specific region, you need to substitute your
real
{service} "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/{service}/{version}"
for vpc "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2"
in actual use, and initialize the client
as {service}.New{Service}Client
.
- Substitute the values for
{your ak string}
, {your sk string}
, {your endpoint string}
and {your project id}
.
package main
import (
"fmt"
"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/config"
"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/httphandler"
vpc "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2"
"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/vpc/v2/model"
"net/http"
)
func RequestHandler(request http.Request) {
fmt.Println(request)
}
func ResponseHandler(response http.Response) {
fmt.Println(response)
}
func main() {
client := vpc.NewVpcClient(
vpc.VpcClientBuilder().
WithEndpoint("{your endpoint}").
WithCredential(
basic.NewCredentialsBuilder().
WithAk("{your ak string}").
WithSk("{your sk string}").
WithProjectId("{your project id}").
Build()).
WithHttpConfig(config.DefaultHttpConfig().
WithIgnoreSSLVerification(true).
WithHttpHandler(httphandler.
NewHttpHandler().
AddRequestHandler(RequestHandler).
AddResponseHandler(ResponseHandler))).
Build())
limit := int32(1)
request := &model.ListVpcsRequest{
Limit: &limit,
}
response, err := client.ListVpcs(request)
if err == nil {
fmt.Printf("%+v\n\n", response.Vpcs)
} else {
fmt.Println(err)
}
}
Changelog
Detailed changes for each released version are documented in
the CHANGELOG.md.
User Manual ๐
1. Client Configuration ๐
1.1 Default Configuration ๐
// Use default configuration
httpConfig := config.DefaultHttpConfig()
1.2 Network Proxy ๐
// Use proxy if needed
httpConfig.WithProxy(config.NewProxy().
WithSchema("http").
WithHost("proxy.huaweicloud.com").
WithPort(80).
WithUsername("testuser").
WithPassword("password"))))
1.3 Connection ๐
// Seconds to wait for the server to send data before giving up
httpConfig.WithTimeout(120);
1.4 SSL Certification ๐
// Skip ssl certification checking while using https protocol if needed
httpConfig.WithIgnoreSSLVerification(true);
1.5 Custom Network Connection ๐
// Config network connection dial function if needed
func DialContext(ctx context.Context, network string, addr string) (net.Conn, error) {
return net.Dial(network, addr)
}
httpConfig.WithDialContext(DialContext)
2. Credentials Configuration ๐
There are two types of Huawei Cloud services, regional
services and global
services.
Global services contain BSS, DevStar, EPS, IAM, RMS.
For regional
services' authentication, projectId is required to initialize basic.NewCredentialsBuilder(). For global
services' authentication, domainId is required to initialize global.NewCredentialsBuilder().
Parameter description
:
ak
is the access key ID for your account.
sk
is the secret access key for your account.
projectId
is the ID of your project depending on your region which you want to operate.
domainId
is the account ID of HUAWEI CLOUD.
securityToken
is the security token when using temporary AK/SK.
You could use permanent AK plus SK or use temporary AK plus SK plus SecurityToken to complete credentials'
configuration.
2.1 Use Permanent AK&SK ๐
// Regional Services
basicCredentials := basic.NewCredentialsBuilder().
WithAk(ak).
WithSk(sk).
WithProjectId(projectId).
Build()
// Global Services
globalCredentials := global.NewCredentialsBuilder().
WithAk(ak).
WithSk(sk).
WithDomainId(domainId).
Build()
Notice:
- projectId/domainId supports automatic acquisition in version
0.0.26-beta
or later, if you want to use this
feature, you need to provide the ak and sk of your account and the id of the region, and then build your client
instance with method WithRegion()
, detailed example could refer
to 3.2 Initialize client with specified Region
.
2.2 Use Temporary AK&SK ๐
It's required to obtain temporary access key, security key and security token first, which could be obtained through
permanent access key and security key or through an agency.
Obtaining a temporary access key token through permanent access key and security key, you could refer to
document: https://support.huaweicloud.com/en-us/api-iam/iam_04_0002.html . The API mentioned in the document above
corresponds to the method of CreateTemporaryAccessKeyByToken
in IAM SDK.
Obtaining a temporary access key and security token through an agency, you could refer to
document: https://support.huaweicloud.com/en-us/api-iam/iam_04_0101.html . The API mentioned in the document above
corresponds to the method of CreateTemporaryAccessKeyByAgency
in IAM SDK.
// Regional Services
basicCredentials := basic.NewCredentialsBuilder().
WithAk(ak).
WithSk(sk).
WithProjectId(projectId).
WithSecurityToken(securityToken).
Build()
// Global Services
globalCredentials := global.NewCredentialsBuilder().
WithAk(ak).
WithSk(sk).
WithDomainId(domainId).
WithSecurityToken(securityToken).
Build()
3. Client Initialization ๐
There are two ways to initialize the {Service}Client, you could choose one you preferred.
3.1 Initialize the {Service}Client with specified Endpoint ๐
// Specify the endpoint, take the endpoint of VPC service in region of cn-north-4 for example
endpoint := "https://vpc.cn-north-4.myhuaweicloud.com"
// Initialize the credentials, you should provide projectId or domainId in this way, take initializing BasicCredentials for example
basicAuth := basic.NewCredentialsBuilder().
WithAk(ak).
WithSk(sk).
WithProjectId(projectId).
Build()
// Initialize specified New{Service}Client, take initializing the regional service VPC's VpcClient for example
client := vpc.NewVpcClient(
vpc.VpcClientBuilder().
WithEndpoint(endpoint).
WithCredential(basicCredentials).
WithHttpConfig(config.DefaultHttpConfig()).
Build())
where:
-
endpoint
varies with services and regions,
see Regions and Endpoints to obtain correct endpoint.
-
When you meet some trouble in getting projectId using the specified region way, you could use this way instead.
3.2 Initialize the {Service}Client with specified Region (Recommended) ๐
import (
// dependency for region module
"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iam/v3/region"
)
// Initialize the credentials, projectId or domainId could be unassigned in this situation, take initializing GlobalCredentials for example
globalCredentials := global.NewCredentialsBuilder().
WithAk(ak).
WithSk(sk).
// domainId could be unassigned in this situation
Build()
// Initialize specified New{Service}Client, take initializing the global service IAM's NewIamClient for example
client := iam.NewIamClient(
iam.IamClientBuilder().
WithRegion(region.CN_NORTH_4).
WithCredential(globalCredentials).
WithHttpConfig(config.DefaultHttpConfig()).
Build())
Notice:
-
If you use region
to initialize {Service}Client, projectId/domainId supports automatic acquisition, you don't need
to configure it when initializing Credentials.
-
Multiple ProjectId situation is not supported.
-
Supported region list: af-south-1, ap-southeast-1, ap-southeast-2, ap-southeast-3, cn-east-2, cn-east-3, cn-north-1,
cn-north-4, cn-south-1, cn-southwest-2, ru-northwest-2. You may get exception such as Unsupported regionId
if your
region don't in the list above.
Comparison of the two ways:
Initialization |
Advantages |
Disadvantage |
Specified Endpoint |
The API can be invoked successfully once it has been published in the environment. |
You need to prepare projectId and endpoint yourself. |
Specified Region |
No need for projectId and endpoint, it supports automatic acquisition if you configure it in the right way. |
The supported services and regions are limited. |
4. Send Requests and Handle Responses ๐
// send a request and print response, take interface of ListVpcs for example
limit := int32(1)
request := &model.ListVpcsRequest{
Limit: &limit,
}
response, err := client.ListVpcs(request)
if err == nil {
fmt.Printf("%+v\n\n", response.Vpcs)
} else {
fmt.Println(err)
}
4.1 Exceptions ๐
Level 1 |
Notice |
ServiceResponseError |
service response error |
url.Error |
connect endpoint error |
response, err := client.ListVpcs(request)
if err == nil {
fmt.Printf("%+v\n\n", response.Vpcs)
} else {
fmt.Println(err)
}
5. Troubleshooting ๐
5.1 Original HTTP Listener ๐
In some situation, you may need to debug your http requests, original http request and response information will be
needed. The SDK provides a listener function to obtain the original encrypted http request and response information.
โ Warning: The original http log information is used in debugging stage only, please do not print the original http header or body in the production environment. This log information is not encrypted and contains sensitive data such as the password of your ECS virtual machine, or the password of your IAM user account, etc. When the response body is binary content, the body will be printed as "***" without detailed information.
func RequestHandler(request http.Request) {
fmt.Println(request)
}
func ResponseHandler(response http.Response) {
fmt.Println(response)
}
client := vpc.NewVpcClient(
vpc.VpcClientBuilder().
WithEndpoint("{your endpoint}").
WithCredential(
basic.NewCredentialsBuilder().
WithAk("{your ak string}").
WithSk("{your sk string}").
WithProjectId("{your project id}").
Build()).
WithHttpConfig(config.DefaultHttpConfig().
WithIgnoreSSLVerification(true).
WithHttpHandler(httphandler.
NewHttpHandler().
AddRequestHandler(RequestHandler).
AddResponseHandler(ResponseHandler))).
Build())
6. Upload and download files ๐
Take the interface CreateImageWatermark
of the service Data Security Center
as an example, this interface needs to upload an image file and return the watermarked image file stream:
package main
import (
"fmt"
"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/def"
dsc "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dsc/v1"
"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dsc/v1/model"
"os"
)
func createImageWatermark(client *dsc.DscClient) {
// Open the file.
file, err := os.Open("demo.jpg")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
body := &model.CreateImageWatermarkRequestBody{
File: def.NewFilePart(file),
BlindWatermark: def.NewMultiPart("test_watermark"),
}
request := &model.CreateImageWatermarkRequest{Body: body}
response, err := client.CreateImageWatermark(request)
if err == nil {
fmt.Printf("%+v\n", response)
} else {
fmt.Println(err)
return
}
// Download the file.
result, err := os.Create("result.jpg")
if err != nil {
fmt.Println(err)
return
}
response.Consume(result)
}
func main() {
ak := "{your ak string}"
sk := "{your sk string}"
endpoint := "{your endpoint string}"
projectId := "{your project id}"
credentials := basic.NewCredentialsBuilder().
WithAk(ak).
WithSk(sk).
WithProjectId(projectId).
Build()
client := dsc.NewDscClient(
dsc.DscClientBuilder().
WithEndpoint(endpoint).
WithCredential(credentials).
Build())
createImageWatermark(client)
}