Updated on 2023-12-22 GMT+08:00

Go

This section uses IntelliJ IDEA as an example to describe how to integrate the Go SDK for API request signing. You can import the sample project in the code package, and integrate the signing SDK into your application by referring to the API calling example.

Preparing the IDEA Development Environment

  • Download IntelliJ IDEA from the IntelliJ IDEA official website and install it.
  • Download the Go installation package from the Go official website and install it.
  • To install the Go plug-in on IDEA, choose File > Settings.
    Figure 1 Installing the Go plug-in on IDEA

Obtaining the SDK

Download the SDK and demo.

Develop your application using the SDK and sample code.

Name

Description

core\escape.go

Used for escaping special characters.

core\signer.go

Signing SDK

demo.go

Sample code

Importing the Sample Project on IDEA

  1. Start IDEA and choose File > New > Project.

    On the displayed New Project page, choose Go and click Next.

  2. Click ..., select the directory where the SDK is decompressed, and click Finish.

  3. View the directory structure shown in the following figure.

Request Signing and API Calling

  1. Import the Go SDK (signer.go) to the project.

    import "./core"

  2. Generate a new signer and enter the AK and SK.

    s := core.Signer{
    // Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables.
    // In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK.
            Key: os.Getenv("HUAWEICLOUD_SDK_AK"),
            Secret: os.Getenv("HUAWEICLOUD_SDK_SK"),
    }

  3. Generate a new request, and specify the domain name, method, request URI, and body.

    //The following example shows how to set the request URL and parameters to query a VPC list.
    //Add a body if you have specified the PUT or POST method. Special characters, such as the double quotation mark ("), contained in the body must be escaped.
    r, _ := http.NewRequest("GET", "https://service.region.example.com/v1/{project_id}/vpcs?a=1", ioutil.NopCloser(bytes.NewBuffer([]byte(""))))

  4. Add other headers required for request signing or other purposes. For example, add the X-Project-Id header in multi-project scenarios or the X-Domain-Id header for a global service.

    /Add header parameters, for example, X-Domain-Id for invoking a global service and X-Project-Id for invoking a project-level service.
    r.Header.Add("X-Project-Id", "xxx")

  5. Execute the following function to add the X-Sdk-Date and Authorization headers for signing:

    s.Sign(r)

  6. Access the API and view the access result.

    resp, err := http.DefaultClient.Do(r)
    body, err := ioutil.ReadAll(resp.Body)