Ladislav Prskavec Ladislav Prskavec - 8 months ago 1365
JSON Question

Golang - How send json string in POST request

I try work with Apiary and make universal template to send JSON to mock server and have this code:

package main

import (

func main() {
url := ""
fmt.Println("URL:>", url)

s := napping.Session{}
h := &http.Header{}
h.Set("X-Custom-Header", "myvalue")
s.Header = h

var jsonStr = []byte(`
"title": "Buy cheese and bread for breakfast."

var data map[string]json.RawMessage
err := json.Unmarshal(jsonStr, &data)
if err != nil {

resp, err := s.Post(url, &data, nil, nil)
if err != nil {
fmt.Println("response Status:", resp.Status())
fmt.Println("response Headers:", resp.HttpResponse().Header)
fmt.Println("response Body:", resp.RawText())


this code don't send properly JSON, but I don't know why. JSON string is example can be different in every call. I can't use
for this.


I'm not familiar with napping, but using Golang's net/http package works fine (playground):

func main() {
    url := ""
    fmt.Println("URL:>", url)

    var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
    defer resp.Body.Close()

    fmt.Println("response Status:", resp.Status)
    fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))