我试图将一个查询参数添加到HTTP GET请求,但不知何故SO上指出的方法(例如 here)不起作用. 我有以下代码: package mainimport ( "fmt" "log" "net/http")func main() { req, err := http.NewRequest("GET", "/callbac
我有以下代码:
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\n", req.URL) fmt.Printf("RawQuery %+v\n", req.URL.RawQuery) fmt.Printf("Query %+v\n", req.URL.Query()) }
打印:
URL /callback RawQuery Query map[]
有关如何实现这一目标的任何建议?
游乐场示例:https://play.golang.org/p/SYN4yNbCmo
检查req.URL.Query()
的文档:
Query parses RawQuery and returns the corresponding values.
由于它“解析RawQuery并返回”,所获得的值只是URL查询值的副本,而不是“实时引用”,因此修改该副本不会对原始查询产生任何影响.要修改原始查询,必须分配给原始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]]
请注意,您这样做的原始尝试不起作用,因为它只是解析查询值,对它们进行编码,并将它们直接分配回URL:
req.URL.RawQuery = req.URL.Query().Encode() // This is basically a noop!