Skip to content

Golang HTTP Request With JSON Body

Just use this snippet which sends a post request with a JSON body. It saves your time :).

I know you are not comfortable with bytes and buffers but this is an important part of Golang!

First, encode your struct into JSON:

reqBody, err := json.Marshal(map[string]string{
	"username": "morteza",
})

http.POST() method needs an io.Reader then use bytes.NewBuffer() which satisfies this interface:

bytes.NewBuffer(reqBody)

That’s it!

Enjoy this simple snippet in your project:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

const (
	apiUrl = "https://www.code-paste.com/api/v1/"
)

func main() {
	reqBody, err := json.Marshal(map[string]string{
		"username": "morteza",
	})

	if err != nil {
		log.Fatalf("failed to marshal body: %s", err)
	}

	resp, err := http.Post(
		apiUrl,
		"application/json",
		bytes.NewBuffer(reqBody), // or if you have string: bytes.NewBuffer([]byte(`{"username": "morteza"}"`))
	)
	if err != nil {

		log.Fatalf("failed to post request: %s", err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		log.Fatalf("failed to read body: %s", err)
	}

	fmt.Println(string(body))
}

Leave a Reply

Your email address will not be published. Required fields are marked *