Convert python code to Go for json encoding

huangapple go评论94阅读模式
英文:

Convert python code to Go for json encoding

问题

我已经翻译了你提供的代码段,如下所示:

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语言中,你可以这样编写代码:

import (
	"encoding/json"
	"fmt"
	"time"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"net/http"
	"bytes"
)

type GetOrderStatusInput struct {
	ID        string `json:"id"`
	Timestamp int64  `json:"timestamp"`
}

func main() {
	secret := "somekey"
	url := "https://api.coindcx.com/exchange/v1/orders/status"
	timeStamp := time.Now().UnixNano() / 1000000
	getOrderStatusInput := GetOrderStatusInput{
		ID:        "ead19992-43fd-11e8-b027-bb815bcb14ed",
		Timestamp: timeStamp,
	}

	jsonBody, err := json.Marshal(getOrderStatusInput)
	if err != nil {
		fmt.Println("Error encoding JSON:", err)
		return
	}

	signature := generateSignature(secret, jsonBody)
	fmt.Println(signature)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-AUTH-APIKEY", "someapikey")
	req.Header.Set("X-AUTH-SIGNATURE", signature)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	fmt.Println(resp)
}

func generateSignature(secret string, data []byte) string {
	h := hmac.New(sha256.New, []byte(secret))
	h.Write(data)
	signature := hex.EncodeToString(h.Sum(nil))
	return signature
}

希望这可以帮助到你!如果你有任何其他问题,请随时问我。

英文:

I have written this python code -

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)

In Go I tried writing it like this -

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, 	
}

But not able to figure out how to do json encoding and hmac here.

答案1

得分: 1

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 {
		// 处理错误
	}

	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 {
		// 处理错误
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// 处理错误
	}

	fmt.Println(string(body))
}

以上是给定的Go语言代码的翻译。

英文:
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))
}

huangapple
  • 本文由 发表于 2021年8月12日 14:50:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/68752838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定