Create a json payload in Go Lang POST request?

Zahid Sumon picture Zahid Sumon · Feb 12, 2018 · Viewed 12.4k times · Source
request, err := http.NewRequest("POST", url,bytes.NewBuffer(**myJsonPayload**))

I am new in Go and trying to make post request with dynamic 'myJsonPayload', which will be changing for different request.

Answer

jrefior picture jrefior · Feb 12, 2018

Use Marshal in the encoding/json package of Go's standard library to encode your data as JSON.

Signature:

func Marshal(v interface{}) ([]byte, error)

Example from package docs, where input data happens to be a struct type with int, string, and string slice field types:

type ColorGroup struct {
    ID     int
    Name   string
    Colors []string
}
group := ColorGroup{
    ID:     1,
    Name:   "Reds",
    Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := json.Marshal(group)