【问题标题】:Need some help on how to implement an restfull api app based on golang需要一些关于如何实现基于golang的restful api应用程序的帮助
【发布时间】:2015-07-29 23:49:12
【问题描述】:

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

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

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

通过将以下变量发送到请求头Key中来执行授权

  • 公共 API 密钥。
  • 所有查询数据 (nonce=blahblah&limit=blahblah) 根据 HMAC-SHA512 方法由密钥签名。您的密钥和公钥可以从您的帐户设置页面生成。每个请求都需要一个唯一的 nonce。 (建议使用带微秒的 unix 时间戳)

对于这个认证部分,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"]} &lt;nil&gt;

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

已经用谷歌搜索了 restfull api,但找不到任何答案 :( 开始不让我晚上睡觉,因为我认为我所做的有点正确.. 真的无法发现错误..

有没有人可以尝试帮助我解决这个问题?

非常感谢:)

【问题讨论】:

    标签: python api go


    【解决方案1】:

    我看到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 等。

    【讨论】:

    • 真的很抱歉!第一次在stackoverflow上发帖。编辑了代码,现在可以复制粘贴并执行。我想当我将响应传递给 ComputeHmac512Hex 方法时,我可能会丢失某种编码。
    • 我马上试试!是的,我只在没有参数的情况下完成了它,因为我认为 info url 不再需要参数,而是 nonce。仍然不确定,但是正确的实现应该是完整的参数。但我认为查询数据(参数)将被添加到标题而不是 rawurl,至少这是我从他们对发送给他们的变量的描述中得到的。 更新刚刚尝试但仍然无法正常工作,我可能缺少对结果的编码:x python代码:queryStr = urllib.urlencode(query)
    • 很可能您还需要发送参数:docs.python-requests.org/en/latest/user/quickstart/…
    • 它们肯定被添加到查询字符串中,所以请尝试使用完整的 URL。
    • 添加了这个代码: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 ) ... 像这样?还是做不到
    猜你喜欢
    • 2017-08-05
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    相关资源
    最近更新 更多