英文:
How to make fmt.Sprint spring work for parameters in a URL?
问题
我有一个反向代理,用于返回来自第三方API的响应体。这个第三方API使用分页,所以我的反向代理路径需要包含页码参数。
我在使用fmt.Sprint
将参数从反向代理URL传递给第三方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.NewRequest
的第三方API请求,%s\n
部分是用于传递key
作为page parameter
的地方。
我应该如何正确地将这个变量传递给URL?在Python中,我想要使用的是f-string。不确定我是否正确地在Go中使用了它。
编辑:
使用url.Values()
的新实现:
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)
}
英文:
I have a reverse-proxy that returns body responses from a 3rd party API. This 3rd party API uses pagination, so my reverse-proxy path requires parameters for page number.
I'm having trouble using fmt.Sprint
to pass the parameter from the reverse-proxy URL to 3rd Party API request.
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.
}
Looking at the http.NewRequest
3rd party api request, the %s\n
part would be where they key
is passed for the page parameter
.
How can I correctly pass this variable to the url? In python what I'm looking to use is an f-string. Not sure im doing that correctly for Go.
EDIT:
New implementation using 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)
}
答案1
得分: 4
你应该使用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可能更容易出错。
如果你想使用fmt.Sprintf
构建URL,你需要转义格式字符串中的所有%
,并转义参数中的特殊字符。
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,这个函数就不是必需的。
英文:
You should probably be constructing the URL and query using the net/url
package. This has the advantage that it is much safer.
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)
Trying to use fmt.Sprintf()
to construct URLs is a bit more likely to backfire.
If you want to construct a URL with fmt.Sprintf
, you’ll need to escape all the %
in the format string, and escape special characters in the arguments.
fmt.Sprint("https://url.com/path?&page%%5Bsize%%5D=100&page%%5B%s%%5D=1",
url.QueryEscape(key))
The url.QueryEscape()
function escapes the characters in a string so it can be safely placed in a URL query. It’s not necessary if you construct the URL with url.Values
and url.URL
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论