-4

I found how to send a POST with URL parameters, or how to send a POST with a JSON body, but I do not know how to combine them together (a request with both a URL with parameters, and a JSON body).

The code below (which is not correct) shows the commbination I am looking for. I can use either bytes.NewBuffer(jsonStr) or strings.NewReader(parm.Encode()) but not both.

package main import ( "bytes" "net/http" "net/url" "strings" ) func main() { var jsonStr = []byte(`{"title":"my request"}`) parm := url.Values{} parm.Add("token", "hello") req, err := http.NewRequest("POST", "https://postman-echo.com/post", bytes.NewBuffer(jsonStr), strings.NewReader(parm.Encode())) if err != nil { panic(err) } req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() } 

How to build a full POST call with all the components?

13
  • I don't think you should be trying to send the URL parameters in the request body. As you say, you can't use both (because an HTTP request is meant to have a single body, the URL is separate). Commented May 29, 2021 at 8:01
  • 2
    Those aren't URL parameters. URL parameters, by definition, are parameters to the URL. Commented May 29, 2021 at 8:35
  • @Flimzy yes I know, I am starting with Go and trying to port what I know from Python where a single call gets both the parameters and the body. Commented May 29, 2021 at 9:49
  • Curious. If you know that, I wonder why you said otherwise in your question. Commented May 29, 2021 at 17:53
  • 1
    @Flimzy " ... is not URL parameters" ahhhh, ok. I was reading a page where parm was used for both the body and the URL (in different examples) - this is where I got it wrong. Commented May 29, 2021 at 18:14

1 Answer 1

2

Use the only json as your request body, and apply the URL parameters like this:

req.URL.RawQuery = parm.Encode() 

From Go doing a GET request and building the Querystring

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.