dongyang7152 2013-12-16 17:30
浏览 83
已采纳

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条回答 默认 最新

  • dragon7713 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 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考