doudou130216 2017-12-07 20:55 采纳率: 0%
浏览 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!
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求计算赫斯特(Hurst)指数
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大