How to Parse a JSON Request with Go

A pretty common task with any web server is the need to parse a request. The code below is a pretty bare bones approach to parsing a JSON request.

package main

import (

func main() {
	http.HandleFunc("/", handler)
	log.Fatal(http.ListenAndServe(":8080", nil))

func handler(w http.ResponseWriter, r *http.Request) {

	// Create struct
	var request Request

	// Attempt to read request body
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&request)
	if err != nil {
		http.Error(w, "The request body format is invalid", 400)

	// Print name

type Request struct {
	Name	string		`json:"name"`