6

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?

5
  • 1
    Build the URL with fmt.Sprintf Commented May 6, 2017 at 23:46
  • Cool... there's some more elegant way to do this? or just using another http client library? Commented May 6, 2017 at 23:48
  • are you looking for url api ? golang.org/pkg/net/url/#example_ParseQuery Commented May 7, 2017 at 11:15
  • More elegant how? You're injecting a string into another string, Sprintf does precisely that. What specifically are you looking for beyond "put string x at this position in string y"? Commented May 7, 2017 at 21:26
  • Probably pkg.go.dev/path#Join Commented May 23, 2022 at 17:26

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

-3

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
}

1 Comment

This adds query params and not path params

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.