G42 Cloud Go Software Development Kit (Go SDK)
The G42 Cloud Go SDK allows you to easily work with G42 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 G42 Cloud Go SDK.
Requirements
-
To use G42 Cloud Go SDK, you must have G42 Cloud account as well as the Access Key (AK) and Secret key (SK) of the G42
Cloud account. You can create an AccessKey in the G42 Cloud console.
-
To use G42 Cloud Go SDK to access the APIs of specific service, please make sure you do have activated the service
in G42 Cloud console if needed.
-
G42 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 G42 Cloud Go SDK:
# Install the library of G42 Cloud Go SDK
go get github.com/g42cloud-sdk/g42cloud-sdk-go
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/g42cloud-sdk/g42cloud-sdk-go/services/{service}/{version}"
for vpc "github.com/g42cloud-sdk/g42cloud-sdk-go/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/g42cloud-sdk/g42cloud-sdk-go/core/auth/basic"
"github.com/g42cloud-sdk/g42cloud-sdk-go/core/config"
"github.com/g42cloud-sdk/g42cloud-sdk-go/core/httphandler"
vpc "github.com/g42cloud-sdk/g42cloud-sdk-go/services/vpc/v2"
"github.com/g42cloud-sdk/g42cloud-sdk-go/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 π
import "github.com/g42cloud-sdk/g42cloud-sdk-go/core/config"
// Use default configuration
httpConfig := config.DefaultHttpConfig()
1.2 Network Proxy π
// Use proxy if needed
httpConfig.WithProxy(config.NewProxy().
WithSchema("http").
WithHost("proxy.g42cloud.com").
WithPort(80).
WithUsername("testuser").
WithPassword("password"))))
1.3 Timeout Configuration π
// The default timeout is 120 seconds, which can be adjusted as needed
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 G42 Cloud services, regional
services and global
services.
Global services contain IAM.
For regional
services' authentication, projectId is required to initialize basic.NewCredentialsBuilder().
For global
services' authentication, domainId is required to initialize global.NewCredentialsBuilder().
The following authentications are supported:
- permanent AK&SK
- temporary AK&SK + SecurityToken
2.1 Use Permanent AK&SK π
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 G42 Cloud.
// Regional Services
basicCredentials := basic.NewCredentialsBuilder().
WithAk(ak).
WithSk(sk).
WithProjectId(projectId).
Build()
// Global Services
globalCredentials := global.NewCredentialsBuilder().
WithAk(ak).
WithSk(sk).
WithDomainId(domainId).
Build()
2.2 Use Temporary AK&SK π
It's required to obtain temporary AK&SK and security token first, which could be obtained through
permanent AK&SK or through an agency.A temporary access key and securityToken are issued by the system to IAM users, and can be valid for 15 minutes to 24 hours.
Parameter description:
ak
is the access key ID for your account.
sk
is the secret access key for your account.
securityToken
is the security token when using temporary AK/SK.
projectId
is the ID of your project depending on your region which you want to operate.
domainId
is the account ID of G42 Cloud.
// 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 π
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 := "${endpoint}"
// 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:
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 π
package main
import (
"fmt"
"os"
"github.com/g42cloud-sdk/g42cloud-sdk-go/core/auth/basic"
"github.com/g42cloud-sdk/g42cloud-sdk-go/core/def"
service "github.com/g42cloud-sdk/g42cloud-sdk-go/services/service/v1"
"github.com/g42cloud-sdk/g42cloud-sdk-go/services/service/v1/model"
)
func uploadAndDownloadFile(client *service.ServiceClient) {
// Open the file.
file, err := os.Open("demo.jpg")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
body := &model.UploadFileRequestBody{
File: def.NewFilePart(file),
FileName: def.NewMultiPart("rename.jpg"),
}
request := &model.UploadFileRequest{Body: body}
response, err := client.UploadFile(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 := service.NewServiceClient(
service.ServiceClientBuilder().
WithEndpoint(endpoint).
WithCredential(credentials).
Build())
uploadAndDownloadFile(client)
}
7. Retry For Request π
When a request encounters a network exception or flow control on the interface, the request needs to be retried. The
Go SDK provides the retry method for our users which could be used to the requests of GET
HTTP method.
If you want to use the retry method, the following parameters are required:
- maxRetryTimes: the max retry times
- retryCondition: a function, which determine the condition of when to retry
- backoffStrategy: calculate the wait duration before next retry
Take the interface ListVpcs
of VPC service for example, assume the request would retry at most 3 times,
retry when service responses an error, the code would be like the following:
// initialize the client
client := vpc.NewVpcClient(
vpc.VpcClientBuilder().
WithEndpoint("<input your endpoint>").
WithCredential(
basic.NewCredentialsBuilder().
WithAk("<input your ak>").
WithSk("<input your sk>").
WithProjectId("<input your project id>").
Build()).
Build())
// initialize the request
request := &model.ListVpcsRequest{}
// send the requet and retry when service responses an error
response, err := client.ListVpcsInvoker(request).WithRetry(3, func(i interface{}, err error) bool {
return err != nil
}, new(retry.None)).Invoke()
if err == nil {
fmt.Printf("%+v\n", response)
} else {
fmt.Printf("%+v\n", err)
}