python - 需要一些关于如何实现基于 golang 的 restful api 应用程序的帮助

标签 python api go

我的编码技能有点低:) 最近我开始学习 golang 以及如何处理 Api 通信应用程序。自学以来一直很开心,golang 正在证明自己是一门具有挑战性的语言,最终收获颇丰(代码感^^)。

一直在尝试基于他们的 API V2(BETA)为 golang 创建一个 cryptsy api 库,这是一个 restfull api。他们在他们的 api 网站上有一个 python 库 https://github.com/ScriptProdigy/CryptsyPythonV2/blob/master/Cryptsy.py .

到目前为止,已经能够让公共(public)访问正常工作,但由于身份验证部分,我在私有(private)访问上遇到了非常困难的事情。我发现他们在其网站上提供的有关如何实现它的信息有点令人困惑:(

Authorization is performed by sending the following variables into the request header Key

  • Public API key.
  • All query data (nonce=blahblah&limit=blahblah) signed by a secret key according to HMAC-SHA512 method. Your secret key and public keys can be generated from your account settings page. Every request requires a unique nonce. (Suggested to use unix timestamp with microseconds)

对于此身份验证部分,python 代码如下:

def _query(self, method, id=None, action=None, query=[], get_method="GET"):
    query.append(('nonce', time.time()))
    queryStr = urllib.urlencode(query)

    link = 'https://' + self.domain + route

    sign = hmac.new(self.PrivateKey.encode('utf-8'), queryStr, hashlib.sha512).hexdigest()

    headers = {'Sign': sign, 'Key': self.PublicKey.encode('utf-8')}

在 golang 中走到了这一步:

package main

import(

    "crypto/hmac"
    "crypto/sha512"
    "encoding/hex"
    "encoding/json"
    "errors"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
    "time"

)

const (

    API_BASE_CRY    = "https://api.cryptsy.com/api/"
    API_VERSION_CRY = "v2"
    API_KEY_CRY     = "xxxxx"
    API_SECRET_CRY  = "xxxxxxxxxxxx"
    DEFAULT_HTTPCLIENT_TIMEOUT = 30 // HTTP client timeout
)

type clientCry struct {
    apiKey     string
    apiSecret  string
    httpClient *http.Client
}

type Cryptsy struct {
    clientCry *clientCry
}

type CryptsyApiRsp struct {
    Success bool            `json:"success"`
    Data    json.RawMessage `json:"data"`
}

func NewCry(apiKey, apiSecret string) *Cryptsy {
    clientCry := NewClientCry(apiKey, apiSecret)
    return &Cryptsy{clientCry}
}

func NewClientCry(apiKey, apiSecret string) (c *clientCry) {
    return &clientCry{apiKey, apiSecret, &http.Client{}}
}

func ComputeHmac512Hex(secret, payload string) string {
    h := hmac.New(sha512.New, []byte(secret))
    h.Write([]byte(payload))
    return hex.EncodeToString(h.Sum(nil))
}

func (c *clientCry) doTimeoutRequestCry(timer *time.Timer, req *http.Request) (*http.Response, error) {

    type data struct {
       resp *http.Response
       err  error
    }

    done := make(chan data, 1)
    go func() {
       resp, err := c.httpClient.Do(req)
       done <- data{resp, err}
    }()

    select {
       case r := <-done:
       return r.resp, r.err
       case <-timer.C:
          return nil, errors.New("timeout on reading data from Bittrex API")
    }
}

func (c *clientCry) doCry(method string, ressource string, payload string, authNeeded bool) (response []byte, err error) {
    connectTimer := time.NewTimer(DEFAULT_HTTPCLIENT_TIMEOUT * time.Second)

    var rawurl string        

    nonce := time.Now().UnixNano()
    result :=  fmt.Sprintf("nonce=%d", nonce)
    rawurl = fmt.Sprintf("%s%s/%s?%s", API_BASE_CRY ,API_VERSION_CRY , ressource, result )
    req, err := http.NewRequest(method, rawurl, strings.NewReader(payload))

    sig := ComputeHmac512Hex(API_SECRET_CRY, result)

    req.Header.Add("Sign", sig)
    req.Header.Add("Key", API_KEY_CRY )

    resp, err := c.doTimeoutRequestCry(connectTimer, req)
    defer resp.Body.Close()

    response, err = ioutil.ReadAll(resp.Body)
    fmt.Println(fmt.Sprintf("reponse %s", response), err)
    return response, err
}

func main() {

    crypsy := NewCry(API_KEY_CRY, API_SECRET_CRY)
    r, _ := crypsy.clientCry.doCry("GET", "info", "", true) 
    fmt.Println(r)
}

我的输出是:

response {"success":false,"error":["Must be authenticated"]} <nil>

不明白为什么 :( 我在 header 中传递公钥和签名,签名..我认为我在 hmac-sha512 中做对了。 我正在查询用户信息 url https://www.cryptsy.com/pages/apiv2/user ,如 api 站点中所述,它没有任何额外的查询变量,因此 nonce 是唯一需要的。

在 google 上搜索了 restfull api,但没能找到任何答案 :( 开始不让我晚上 sleep ,因为我认为我所做的有点正确.. 真的无法发现错误..

有人可以帮我解决这个问题吗?

非常感谢:)

最佳答案

我看到了 result := fmt.Sprintf("%d", nonce) 的问题。 Python代码对应的代码应该是这样的

result :=  fmt.Sprintf("nonce=%d", nonce)

你能用这个修复程序检查一下吗?

我还可以观察到请求发送方式的主要差异。 Python 版本是 ( link ):

        ret = requests.get(link,
                           params=query,
                           headers=headers,
                           verify=False)

但是您的代码不会发送带有添加的随机数等的params。我认为它应该类似于

rawurl = fmt.Sprintf("%s%s/%s?%s", API_BASE_CRY ,API_VERSION_CRY , ressource, queryStr)

其中 queryStr 应包含 nonce 等

关于python - 需要一些关于如何实现基于 golang 的 restful api 应用程序的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31713050/

相关文章:

python - 在 Python 3 中使用 hashlib 计算文件的 md5 摘要

python - 推特(Tweepy): What counts as a search API call?

go - 忽略 librd kafka 中的测试

go - Gin-Gonic 中间件声明

python - 转换为 float 后,matplotlib 输出无法将字符串转换为 float

python - 如何使用 insert_many 安全地忽略重复键错误

当我能够使用索引打印相同的值时,Python 无法删除列表中的值索引

java - 什么是标记 (HTML) 生成的好技术?

python - 在Python中将文件直接上传到FTP服务器

gorm golang one2many 同一张表