尝试附加到现有的queryString,但是为'?'进行查询字符串的行将被替换为'%3'
server := "server.com"
endpoint:= "/buildWithParameters?token=<top_secret>"
// concat server and build job
u, err := url.Parse(server)
u.Path = path.Join(u.Path, endpoint)
endpoint := u.String()
// since we are appending to existing querystring, request is needed for parsing
req, err := http.NewRequest("POST", endpoint, nil)
if err != nil {
return fmt.Errorf("Error creating post request: (%v)", err)
}
// read existing query string
q := req.URL.Query()
q.Add("key", "value")
req.URL.RawQuery = q.Encode()
log.Println(req.URL.String())
输出为:
https://server.com/job/jobbyjob/buildWithParameters%3Ftoken=<top_secret>?key=value
答案 0 :(得分:3)
那是因为要将查询字符串附加到路径,所以库正确地转义了?
以构成有效的URL。如果要将token=<top_secret>
视为查询的一部分,则需要将其添加到查询中:
endpoint:= "/buildWithParameters"
// ...
q.Add("token", "<top_secret>")
答案 1 :(得分:0)
正如@Flimzy指出的,这是导致我出现问题的Path库。解决了以下base.ResolveReference()方法:
// concat server and build job
u, err := url.Parse(server)
u.Path = path.Join(u.Path, endpoint)
endpoint := u.String()
替换为:
// concat server and build job
base, err := url.Parse(server)
endpoint, err := url.Parse(endpoint)
endpoint = base.ResolveReference(endpoint)
答案 2 :(得分:0)
您要使用url.Parse
创建它,然后将查询字符串附加到路径(通过转义它可以正确处理)。如果您以相反的方式进行操作(构造完整的URL,然后对其进行解析),则它可以完成其工作:
server := "server.com"
endpoint := "/buildWithParameters?token=<top_secret>"
// concat server and build job
u, err := url.Parse(path.Join(server, endpoint))