更新时间:2023-12-22 GMT+08:00
Go
本节以IntelliJ IDEA工具为例,介绍如何在Go环境中集成API请求签名的SDK。您可以直接导入示例工程体验,然后参考调用说明部分将签名SDK集成到您的应用中。
准备IDEA开发环境
- 获取并安装IntelliJ IDEA,可至IntelliJ IDEA官方网站下载。
- 获取并安装Go安装包,可至Go官方下载页面下载。
- 在IDEA中安装Go插件,请打开“File > Settings”,如下图所示。
图1 IDEA安装Go插件
获取SDK
根据解压后获取的SDK代码及示例代码进行开发。
名称 |
说明 |
---|---|
core\escape.go |
特殊字符转义 |
core\signer.go |
签名SDK |
demo.go |
示例代码 |
IDEA工程中导入示例
- 打开IDEA,选择菜单“File > New > Project”。
弹出“New Project”对话框,选择“Go”,单击“Next”。
- 单击“...”,在弹出的对话框中选择解压后的SDK路径,单击“Finish”。
- 完成工程创建后,目录结构如下。
请求签名与API调用
- 在工程中引入sdk(signer.go)。
import "./core"
- 生成一个新的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"), }
- 生成一个新的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(""))))
- 添加需要签名的其他头域,或者其他用途的头域,如多项目场景中添加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")
- 进行签名,执行此函数会在请求中添加用于签名的X-Sdk-Date头和Authorization头。
s.Sign(r)
- 访问API,查看访问结果。
resp, err := http.DefaultClient.Do(r) body, err := ioutil.ReadAll(resp.Body)
父主题: 签名SDK与demo