【发布时间】: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"]} <nil>
不明白为什么:(我在标题中传递公钥和签名,签名..我认为我在 hmac-sha512 中做对了。 我正在查询用户信息 url https://www.cryptsy.com/pages/apiv2/user,正如 api 站点中所述,它没有任何额外的查询变量,因此 nonce 是唯一需要的..
已经用谷歌搜索了 restfull api,但找不到任何答案 :( 开始不让我晚上睡觉,因为我认为我所做的有点正确.. 真的无法发现错误..
有没有人可以尝试帮助我解决这个问题?
非常感谢:)
【问题讨论】: