我正在尝试将查询参数添加到 HTTP GET 请求,但不知何故,在 SO 上指出的方法(例如 here)不起作用。
我有以下代码:
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[]
关于如何实现这一点有什么建议吗?
Playground 示例: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!
关于http - 如何将 URL 查询参数添加到 HTTP GET 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47703627/