0
A := 123
B := "xyz"
b := bytes.NewBufferString("a=" + A + "&b=" + B)
r.Body = ioutil.NopCloser(b)

Is there a better way of setting variables a and b before the POST request is sent?

icza
  • 389,944
  • 63
  • 907
  • 827
exebook
  • 32,014
  • 33
  • 141
  • 226

1 Answers1

3

Certain characters in form keys and values need to be escaped, such as & or =. So to avoid those mistakes, best is to use the url.Values type.

It maps string keys to list of string values. So if you have a value other than string, you have to convert it to string first. Easiest is to use fmt.Sprint() or strconv.Itoa() (for more options see Golang: format a string without printing?).

vs := url.Values{}
vs.Set("a", fmt.Sprint(123))
vs.Set("b", "xyz")
vs.Set("tricky", "= & =")
b := bytes.NewBufferString(vs.Encode())

url.Values knows how to escape keys and values properly. The above vs.Encode() for example outputs (try it on the Go Playground):

a=123&b=xyz&tricky=%3D+%26+%3D

Note:

As url.Values is just a map (with map[string][]string as its underlying type), you can also use a simple composite literal to create and populate it:

vs := url.Values{
    "a":      {strconv.Itoa(123)},
    "b":      {"xyz"},
    "tricky": {"= & ="},
}
b := bytes.NewBufferString(vs.Encode())

Try this variant on the Go Playground.

icza
  • 389,944
  • 63
  • 907
  • 827