dongshuo8756 2013-12-16 17:30
浏览 45
已采纳

Golang与PHP https调用的标头结果不同

I am trying to implement Vault of Satoshi's API in Google App Engine Go. Their reference API is in PHP:

<?php
$serverURL   = 'https://api.vaultofsatoshi.com';
$apiKey      = 'ENTER_YOUR_API_KEY_HERE';
$apiSecret   = 'ENTER_YOUR_API_SECRET_HERE';
function usecTime() {
    list($usec, $sec) = explode(' ', microtime());
    $usec = substr($usec, 2, 6);
    return intval($sec.$usec);
}
$url      = 'https://api.vaultofsatoshi.com';
$endpoint = '/info/currency';
$url = $serverURL . $endpoint;

$parameters= array();
$parameters['nonce']    = usecTime();
$data = http_build_query($parameters);

$httpHeaders = array(
    'Api-Key: '   . $apiKey,
    'Api-Sign:'   . base64_encode(hash_hmac('sha512', $endpoint . chr(0) . $data, $apiSecret)),
);
// Initialize the PHP curl agent
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "something specific to me");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch); 
curl_close($ch); 
echo $output;
?>

My Go code looks like this:

func GenerateSignatureFromValues(secretKey string, endpoint string, values url.Values) string {
    query:=[]byte(values.Encode())
    toEncode:=[]byte(endpoint)
    toEncode = append(toEncode, 0x00)
    toEncode = append(toEncode, query...)
    key:=[]byte(secretKey)
    hmacHash:=hmac.New(sha512.New, key)
    hmacHash.Write(toEncode)
    answer := hmacHash.Sum(nil)
    return base64.StdEncoding.EncodeToString(([]byte(strings.ToLower(hex.EncodeToString(answer)))))
}

func Call(c appengine.Context) map[string]interface{} {
    serverURL:="https://api.vaultofsatoshi.com"
    apiKey:="ENTER_YOUR_API_KEY_HERE"
    apiSecret:="ENTER_YOUR_API_SECRET_HERE"
    endpoint:="/info/order_detail"
    tr := urlfetch.Transport{Context: c}
    values := url.Values{}
    values.Set("nonce", strconv.FormatInt(time.Now().UnixNano()/1000, 10))
    signature:=GenerateSignatureFromValues(apiSecret, endpoint, values)
    req, _:=http.NewRequest("POST", serverURL+endpoint, nil)
    req.Form=values
    req.Header.Set("Api-Key", apiKey)
    req.Header.Set("Api-Sign", signature)
    resp, err:=tr.RoundTrip(req)
    if err != nil {
        c.Errorf("API post error: %s", err)
        return nil
    }
    defer resp.Body.Close()
    body, _:= ioutil.ReadAll(resp.Body)
    result := make(map[string]interface{})
    json.Unmarshal(body, &result)
    return result
}

Both of those pieces of code generate the same signature for the same input. However, when I run the PHP code (with the proper Key and Secret), the server responds with a proper response, but while I run the Go code, the server responds with "Invalid signature". This error indicates that the HTTP request generated by Go must be somehow malformed - either HTTP Header's values are wrong (if the header values are completely missing a different error appears), or the way the POST fields are encoded is wrong for some reason.

Can anyone help me find some reason why those two pieces of code generate different HTTP requests and how can I make Go generate requests like the PHP code?

  • 写回答

1条回答 默认 最新

  • dongsui5464 2013-12-16 18:18
    关注

    See the documentation for Request.Form:

     // Form contains the parsed form data, including both the URL
     // field's query parameters and the POST or PUT form data.
     // This field is only available after ParseForm is called.
     // The HTTP client ignores Form and uses Body instead.
     Form url.Values
    

    Specifically "HTTP client ignores Form and uses Body instead."

    With this line:

    req, _:= http.NewRequest("POST", serverURL+endpoint, nil)
    

    You should use this instead of nil:

    bytes.NewBufferString(values.Encode())
    

    Also keep in mind that the order of map is not guaranteed. url.Values is map[string][]string. So you should be using Encode() once and use the same result in the body and signature. There is a chance that by using Encode() twice the order could be different. This is an important difference between Go and PHP.

    You should also make a habit of handling error instead of ignoring it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用