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 (
	"encoding/json"
	"log"
	"net/http"
)

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

	// Print name
	log.Println(request.Name)
}

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