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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程