将 fmt.Sprint spring 转换为适用于 URL 参数的方法
时间:2024-03-04
浏览:465
作者:佚名
本篇文章给大家分享《将 fmt.Sprint spring 转换为适用于 URL 参数的方法》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
我有一个反向代理,它从第 3 方 api 返回正文响应。此第 3 方 api 使用分页,因此我的反向代理路径需要页码参数。
我在使用 fmt.sprint 将参数从反向代理 url 传递到第 3 方 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 3rd party api 请求,%s\n 部分将是为 key 传递给 page 参数 的位置。
如何正确地将这个变量传递给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)
}正确答案
您可能应该使用 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,则不需要。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《将 fmt.Sprint spring 转换为适用于 URL 参数的方法》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
