Go 调用示例
Golang 调用 CatFee.IO Rest API 示例
前提条件
示例代码
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"net/url"
"time"
"io/ioutil"
"log"
)
const (
APIKey = "your_api_key" // 请替换为您的API Key
APISecret = "your_api_secret" // 请替换为您的API Secret
BaseURL = "https://api.catfee.io"
)
// 生成当前的时间戳(ISO 8601格式)
func generateTimestamp() string {
return time.Now().UTC().Format("2006-01-02T15:04:05.000Z")
}
// 构建请求路径,包括查询参数
func buildRequestPath(path string, queryParams map[string]string) string {
if len(queryParams) == 0 {
return path
}
queryString := "?"
for key, value := range queryParams {
queryString += fmt.Sprintf("%s=%s&", key, value)
}
// 去掉最后的"&"符号
queryString = queryString[:len(queryString)-1]
return path + queryString
}
// 使用 HMAC-SHA256 算法生成签名
func generateSignature(timestamp, method, requestPath string) string {
signString := timestamp + method + requestPath
mac := hmac.New(sha256.New, []byte(APISecret))
mac.Write([]byte(signString))
signature := mac.Sum(nil)
return base64.StdEncoding.EncodeToString(signature)
}
// 创建 HTTP 请求
func createRequest(url, method, timestamp, signature string) (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
// 设置请求头
req.Header.Add("Content-Type", "application/json")
req.Header.Add("CF-ACCESS-KEY", APIKey)
req.Header.Add("CF-ACCESS-SIGN", signature)
req.Header.Add("CF-ACCESS-TIMESTAMP", timestamp)
return client.Do(req)
}
func main() {
method := "POST" // 可以修改为 "GET", "PUT", "DELETE"
path := "/v1/order"
// 示例:创建订单
queryParams := map[string]string{
"quantity": "65000",
"receiver": "TRON_ADDRESS",
"duration": "1h",
}
// 生成请求头
timestamp := generateTimestamp()
requestPath := buildRequestPath(path, queryParams)
signature := generateSignature(timestamp, method, requestPath)
// 创建请求 URL
url := BaseURL + requestPath
// 发送请求
resp, err := createRequest(url, method, timestamp, signature)
if err != nil {
log.Fatal("Error making request:", err)
}
// 读取并输出响应
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("Error reading response:", err)
}
// 打印响应数据
fmt.Println("Response Status:", resp.Status)
fmt.Println("Response Body:", string(body))
}代码解析
注意事项
总结
Last updated