将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))
}

最新更新