英文:
How to properly set path params in url using golang http client?
问题
我正在使用net/http包,我想要在POST请求的URL中设置动态值:
http://myhost.com/v1/sellers/{id}/whatever
我该如何设置这个路径参数中的id值?
英文:
I'm using net/http package and i would like to set dynamic values to an POST url:
http://myhost.com/v1/sellers/{id}/whatever
How can i set id values in this path parameter?
答案1
得分: 1
你可以使用path.Join来构建URL。你可能还需要对从外部接收到的路径参数进行pathEscape,以便可以安全地放置在路径中。
url1 := path.Join("http://myhost.com/v1/sellers", url.PathEscape(id), "whatever")
req, err := http.NewRequest(http.MethodPost, url1, body)
if err != nil {
return err
}
英文:
You can use path.Join to build the url. You may also need to pathEscape the path-params received externally so that they can be safely placed within the path.
url1 := path.Join("http://myhost.com/v1/sellers", url.PathEscape(id), "whatever")
req, err := http.NewRequest(http.MethodPost, url1, body)
if err != nil {
return err
}
答案2
得分: 0
如果你想在发送服务器请求之前向URL添加参数,可以像这样操作:
const (
sellersURL = "http://myhost.com/v1/sellers"
)
q := url.Values{}
q.Add("id", "1")
req, err := http.NewRequest("POST", sellersURL, strings.NewReader(q.Encode()))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Close = true
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
以上代码会将参数添加到URL中,并发送POST请求到指定的URL。
英文:
If you are trying to add params to a URL before you make a server request you can do something like this.
const (
sellersURL = "http://myhost.com/v1/sellers"
)
q := url.Values{}
q.Add("id", "1")
req, err := http.NewRequest("POST", sellersURL, strings.NewReader(q.Encode()))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Close = true
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论