Vipercold
Vipercold

Reputation: 609

How to properly set path params in url using golang http client?

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?

Upvotes: 6

Views: 10609

Answers (2)

tharinduwijewardane
tharinduwijewardane

Reputation: 2843

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
}

Upvotes: 1

JT.
JT.

Reputation: 482

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
}

Upvotes: -3

Related Questions