如何使用Golang的HTTP客户端正确设置URL中的路径参数?

huangapple go评论99阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2017年5月7日 07:38:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/43826412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定