Ladislav Prskavec Ladislav Prskavec - 1 month ago 6
JSON Question

How do I send a json string in a POST request in Go

I tried working with Apiary and made a 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 doesn't send JSON properly, but I don't know why. The JSON string 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))