doudou130216 2017-12-07 20:55
浏览 1584
已采纳

如何在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!
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB yalmip 可转移负荷的简单建模出错,如何解决?
  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?