我有一個反向代理,它從第 3 方 API 返回正文響應。這個第 3 方 API 使用分頁,所以我的反向代理路徑需要頁碼參數。我無法fmt.Sprint將參數從反向代理 URL 傳遞到 3rd Party API 請求。func (s *Server) getReverseProxy(w http.ResponseWriter, r *http.Request) { keys, ok := r.URL.Query()["page"] if !ok || len(keys[0]) < 1 { log.Println("Url Param 'page' is missing") return } // Query()["key"] will return an array of items, // we only want the single item. key := keys[0] log.Println("Url Param 'page' is: " + string(key)) // create http client to make GET request to reverse-proxy client := &http.Client{} // create 3rd party request // creating this request is causing me the issue due to the page parameter req, err := http.NewRequest("GET", fmt.Sprint("https://url.com/path?&page%5Bsize%5D=100&page%5Bnumber%5D=%s\n", key), nil) // more stuff down here but omitted for brevity.}查看第http.NewRequest3 方 api 請求,該%s\n部分將是它們key傳遞給page parameter.如何正確將此變量傳遞給 url?在 python 中,我希望使用的是 f 字符串。不確定我是否正確地為 Go 做這件事。
1 回答

牛魔王的故事
TA貢獻1830條經驗 獲得超3個贊
您可能應該使用net/url包構建 URL 和查詢。這樣做的好處是更安全。
params := url.Values{
"page[size]": []string{"100"},
"page[" + key + "]": []string{"1"},
}
u := &url.URL{
Scheme: "https",
Host: "url.com",
Path: "/path",
RawQuery: params.Encode(),
}
req, err := http.NewRequest("GET", u.String(), nil)
嘗試使用fmt.Sprintf()構造 URL 更有可能適得其反。
如果要使用 構造 URL fmt.Sprintf,則需要轉義%格式字符串中的所有 ,并轉義參數中的特殊字符。
fmt.Sprint("https://url.com/path?&page%%5Bsize%%5D=100&page%%5B%s%%5D=1",
url.QueryEscape(key))
該url.QueryEscape()函數對字符串中的字符進行轉義,以便可以安全地將其放置在 URL 查詢中。如果您使用url.Values和構造 URL,則沒有必要url.URL。
- 1 回答
- 0 關注
- 113 瀏覽
添加回答
舉報
0/150
提交
取消