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 Struct for this.

This question is tagged with json rest go apiary

~ Asked on 2014-06-27 15:09:37

The Best Answer is


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))

~ Answered on 2014-06-27 15:33:16


you can just use post to post your json.

values := map[string]string{"username": username, "password": password}

jsonValue, _ := json.Marshal(values)

resp, err := http.Post(authAuthenticatorUrl, "application/json", bytes.NewBuffer(jsonValue))

~ Answered on 2016-11-05 09:25:17

Most Viewed Questions: