我有一個反向代理,它從第 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[size]=100&page[number]=%s\n", key), nil)
// more stuff down here but omitted for brevity.
}
查看第http.NewRequest3 方 api 請求,該%s\n部分將是它們key傳遞給page parameter.
如何正確將此變數傳遞給 url?在 python 中,我希望使用的是 f 字串。不確定我是否正確地為 Go 做這件事。
編輯:使用 url.Vaues() 的新實作
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))
params := url.Values{
"page[size]": []string{"100"},
"page[" key "]": []string{"1"},
}
u := &url.URL{
Scheme: "https",
Host: "url.com",
Path: "/path",
RawQuery: params.Encode(),
}
// create http client to make GET request
client := &http.Client{}
// create a variable for the JSON model expected from Terraform Cloud API
var data models.TerraformResponse
req, err := http.NewRequest("GET", u.String(), nil)
}
uj5u.com熱心網友回復:
您可能應該使用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%[size%]=100&page%[%s%]=1",
url.QueryEscape(key))
該url.QueryEscape()函式對字串中的字符進行轉義,以便可以安全地將其放置在 URL 查詢中。如果您使用url.Values和構造 URL,則沒有必要url.URL。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/429827.html
標籤:走
上一篇:如何在GO中使用毫秒(字串)將毫秒(uint64)轉換為時間格式RFC3999
下一篇:Go中的介面字面量
