python - 将python代码转换为Go进行json编码
问题描述
我写了这个python代码 -
import json
import time
import hmac
import hashlib
import requests
secret = "somekey"
url = f"https://api.coindcx.com/exchange/v1/orders/status"
timeStamp = int(round(time.time() * 1000))
body = {
"id": "ead19992-43fd-11e8-b027-bb815bcb14ed",
"timestamp": timeStamp
}
json_body = json.dumps(body, separators=(',', ':'))
signature = hmac.new(secret.encode('utf-8'), json_body.encode('utf-8'), hashlib.sha256).hexdigest()
print(signature)
headers = {
'Content-Type': 'application/json',
'X-AUTH-APIKEY': "someapikey",
'X-AUTH-SIGNATURE': signature
}
response = requests.post(url, data=json_body, headers=headers)
print(response)
在 Go 中,我尝试这样写 -
type GetOrderStatusInput struct {
ID string `json:"id"`
Timestamp int64 `json:"timestamp"`
}
timestamp := time.Now().UnixNano() / 1000000
getOrderStatusInput := GetOrderStatusInput{
ID: "ead19992-43fd-11e8-b027-bb815bcb14ed",
Timestamp: timestamp,
}
但无法弄清楚如何在这里进行 json 编码和 hmac。
解决方案
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func main() {
secret := "somekey"
url := "https://api.coindcx.com/exchange/v1/orders/status"
type GetOrderStatusInput struct {
ID string `json:"id"`
Timestamp int64 `json:"timestamp"`
}
timestamp := time.Now().UnixNano() / 1000000
getOrderStatusInput := GetOrderStatusInput{
ID: "ead19992-43fd-11e8-b027-bb815bcb14ed",
Timestamp: timestamp,
}
jsonBytes, err := json.Marshal(getOrderStatusInput)
if err != nil {
// handle error
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(jsonBytes)
signature := mac.Sum(nil)
jsonBody := bytes.NewReader(jsonBytes)
req, _ := http.NewRequest("POST", url, jsonBody)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-AUTH-APIKEY", "someapikey")
req.Header.Set("X-AUTH-SIGNATURE", string(signature))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
推荐阅读
- javascript - Selenium Chrome 驱动程序:点击功能的 Javascript。元素不可见或没有任何反应
- python - 使用作为 Cron 作业运行的 Python 脚本的问题 Ping
- laravel - Laravel 未定义的请求变量
- jquery - JSP Ajax表单提交到servlet put方法不起作用
- python - 熊猫时间序列箱线图
- python - Django assertTemplateUsed fails after redirect
- sql - What is type of relationship between tables?
- json - 如何使用 jq 在字符串中漂亮地打印 JSON?
- java - 美元和美分柜台
- azure-active-directory - oid 在 AAD 中的所有租户中是否唯一?