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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化