登录
首页 >  Golang >  Go问答

使用Go语言编码JSON格式数据

来源:stackoverflow

时间:2024-02-29 13:39:18 439浏览 收藏

本篇文章向大家介绍《使用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))
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>