doudou130216 2017-12-07 20:55 采纳率: 0%
浏览 1585
已采纳

如何在HTTP GET请求中添加URL查询参数?

I am trying to add a query parameter to a HTTP GET request but somehow methods pointed out on SO (e.g. here) don't work.

I have the following piece of code:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    req, err := http.NewRequest("GET", "/callback", nil)
    req.URL.Query().Add("code", "0xdead 0xbeef")
    req.URL.Query().Set("code", "0xdead 0xbeef")
    // this doesn't help
    //req.URL.RawQuery = req.URL.Query().Encode()

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("URL      %+v
", req.URL)
    fmt.Printf("RawQuery %+v
", req.URL.RawQuery)
    fmt.Printf("Query    %+v
", req.URL.Query())
}

which prints:

URL      /callback
RawQuery 
Query    map[]

Any suggestions on how to achieve this?

Playground example: https://play.golang.org/p/SYN4yNbCmo

  • 写回答

1条回答 默认 最新

  • dsimib1625 2017-12-07 21:02
    关注

    Check the docs for req.URL.Query():

    Query parses RawQuery and returns the corresponding values.

    Since it "parses RawQuery and returns" the values what you get is just a copy of the URL query values, not a "live reference", so modifying that copy does nothing to the original query. In order to modify the original query you must assign to the original RawQuery.

    q := req.URL.Query() // Get a copy of the query values.
    q.Add("code", "0xdead 0xbeef") // Add a new value to the set.
    req.URL.RawQuery = q.Encode() // Encode and assign back to the original query.
    
    // URL      /callback?code=0xdead+0xbeef
    // RawQuery code=0xdead+0xbeef
    // Query    map[code:[0xdead 0xbeef]]
    

    Note that your original attempt to do so didn't work because it simply parses the query values, encodes them, and assigns them right back to the URL:

    req.URL.RawQuery = req.URL.Query().Encode()
    // This is basically a noop!
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证