6
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.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Zahid Sumon
  • 189
  • 1
  • 1
  • 6
  • 1
    I have tried the following: payload := []byte(`{ "abc":xyz, "test":"test", }`) jsonPayload, _ := json.Marshal(payload) request, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload)) This actually works but static payload. All I want to make it dynamic. – Zahid Sumon Feb 12 '18 at 04:22

3 Answers3

12

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)
jrefior
  • 4,092
  • 1
  • 19
  • 29
9

You can also use map for dynamically changing json payload. Below is the example code to do this.

payload := map[string]interface{}{"id":1, "name":"zahid"}
byts, _ := json.Marshal(payload)
fmt.Println(string(byts)) // {"id":1,"name":"zahid"}
Vikram Jakhar
  • 712
  • 1
  • 5
  • 13
1

You can also use json#Encoder.Encode:

package main

import (
   "bytes"
   "encoding/json"
   "net/http"
)

func main() {
   s, b := struct{Month, Day int}{12, 31}, new(bytes.Buffer)
   json.NewEncoder(b).Encode(s)
   r, err := http.NewRequest("POST", "https://stackoverflow.com", b)
   if err != nil {
      panic(err)
   }
   new(http.Client).Do(r)
}
Zombo
  • 1
  • 62
  • 391
  • 407