Giter Club home page Giter Club logo

huaweicloud-sdk-go-v3's Introduction

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)
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.