API签名指南-Go:请求签名与API调用

时间:2024-05-15 14:57:56

请求签名与API调用

  1. 在工程中引入sdk(signer.go)。

    import "./core"

  2. 生成一个新的Signer,分别输入AK和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. 生成一个新的Request,指定域名、方法名、请求url和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. 添加需要签名的其他头域,或者其他用途的头域,如多项目场景中添加X-Project-Id,或者全局服务场景中添加X-Domain-Id。

    /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. 进行签名,执行此函数会在请求中添加用于签名的X-Sdk-Date头和Authorization头。

    s.Sign(r)

  6. 访问API,查看访问结果。

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

support.huaweicloud.com/devg-apisign/api-sign-sdk-go.html