Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a json payload for a POST request?

request, err := http.NewRequest("POST", url,bytes.NewBuffer(**myJsonPayload**))

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

like image 220
Zahid Sumon Avatar asked Feb 11 '18 23:02

Zahid Sumon


1 Answers

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)
like image 181
jrefior Avatar answered Oct 15 '22 21:10

jrefior