适用于Bitfinex API V2.0的Golang客户端:如何发布经过身份验证的请求

时间:2017-09-14 20:12:18

标签: rest authentication go

我正在尝试使用Bitfinex REST API V2.0和here,其中描述了如何对请求进行身份验证。以下是我的golang实施:

func (c *Client) newAuthenticatedRequest(method string, refURL string, data map[string]interface{}) (*http.Request, error) {
    path := "auth/r/" + refURL
    rel, err := url.Parse(path)
    if err != nil {
        return nil, err
    }

    payload := "{}"
    if data != nil {
        p, err := json.Marshal(data)
        if err != nil {
            return nil, err
        }
        payload = string(p)
    }

    url := c.BaseURL.ResolveReference(rel)
    req, err := http.NewRequest(method, url.String(), strings.NewReader(payload))
    if err != nil {
        return nil, err
    }

    nonce := utils.GetNonce()
    req.Header.Add("Content-Type", "application/json")
    req.Header.Add("Accept", "application/json")
    req.Header.Add("bfx-nonce", nonce)
    req.Header.Add("bfx-apikey", c.APIKey)
    req.Header.Add("bfx-signature", c.signPayload("/api/v2/" + path + nonce + payload))

    return req, nil
}

func (c *Client) signPayload(payload string) string {
    sig := hmac.New(sha512.New384, []byte(c.APISecret))
    sig.Write([]byte(payload))
    return hex.EncodeToString(sig.Sum(nil))
}

func (c *Client) do(req *http.Request, v interface{}) (*Response, error) {
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, err
    }

    defer resp.Body.Close()

    response, err := newResponse(resp)
    if err != nil {
       return nil, err
    }

    if v != nil {
        err = json.Unmarshal(response.Body, v)
        if err != nil {
            return nil, err
        }
    }

    return response, nil
}

func (s *WalletsService) All() ([]Wallet, error) {
    req, err := s.client.newAuthenticatedRequest("POST", "wallets", nil)
    if err != nil {
        return nil, err
    }

    var w []Wallet
    _, err = s.client.do(req, &w)
    if err != nil {
        return nil, err
    }

    return w, nil
}

问题是当我POST一个请求时,我总是收到错误[10100] apikey: invalid。空载时将有效负载设置为{}是否正确?我尝试过任何可能的组合,但没办法。

0 个答案:

没有答案