Course › Week 5 · HTTP services with net/http › Day 2 · lesson 30 of 42 · 20 min reading + 60–75 min practice
JSON in and out, with validation
Decode request bodies into structs, validate them like a Form Request, and answer 422.
In Laravel a Form Request validates the body before the controller runs, and a failure becomes a 422 with message and errors without a line of yours. In Go the handler reads the body, decodes it, checks it and answers each failure itself.
That is three kinds of failure, and they get different statuses: the body is not JSON at all (415 or 400), it is too large (413), or it is JSON with wrong values (422). Today builds a POST /api/bookings that answers all of them the way a Laravel client expects.
Reading the body
1. Decode, with a limit and a type check
r.Body is an io.Reader (the JSON lesson decoded readers). Two checks come first. The Content-Type header must say JSON, or the answer is 415 Unsupported Media Type. And http.MaxBytesReader wraps the body so that reading more than maxBodyBytes fails: without it, one client can send a gigabyte and fill the server’s memory.
decodeJSON answers the request itself when something is wrong and returns false, so each handler is two lines: decode or return.
package main
import (
"encoding/json/v2"
"errors"
"log/slog"
"net/http"
"os"
"strings"
)
// StoreBooking is the body of POST /api/bookings. Pointers tell a missing field from a zero one.
type StoreBooking struct {
Guest *string `json:"guest"`
Nights *int `json:"nights"`
Email string `json:"email"`
}
// writeJSON sends v as a JSON response with the given status.
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.MarshalWrite(w, v, json.Deterministic(true)); err != nil {
slog.Error("writing the response", "err", err)
}
}
// maxBodyBytes is the largest request body accepted: a booking is a few hundred bytes.
const maxBodyBytes = 64 * 1024
// decodeJSON reads the request body into dst. On failure it has already answered the request, and
// returns false.
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
if mediaType := r.Header.Get("Content-Type"); !strings.HasPrefix(mediaType, "application/json") {
writeJSON(w, http.StatusUnsupportedMediaType, map[string]string{"message": "The request body must be JSON."})
return false
}
body := http.MaxBytesReader(w, r.Body, maxBodyBytes)
if err := json.UnmarshalRead(body, dst); err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"message": "The request body is too large."})
return false
}
writeJSON(w, http.StatusBadRequest, map[string]string{"message": "The request body is not valid JSON: " + err.Error()})
return false
}
return true
}
func storeBooking(w http.ResponseWriter, r *http.Request) {
var req StoreBooking
if !decodeJSON(w, r, &req) {
return
}
writeJSON(w, http.StatusCreated, map[string]any{"data": req})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("POST /api/bookings", storeBooking)
slog.Info("listening", "addr", ":8080")
if err := http.ListenAndServe(":8080", mux); err != nil {
slog.Error("server stopped", "err", err)
os.Exit(1)
}
}
HTTP/1.1 201 Created
Content-Type: application/json
Content-Length: 49
{"data":{"guest":"Astrid","nights":3,"email":""}}HTTP/1.1 400 Bad Request
Content-Type: application/json
Content-Length: 90
{"message":"The request body is not valid JSON: jsontext: unexpected EOF after offset 31"}HTTP/1.1 415 Unsupported Media Type
Content-Type: application/json
Content-Length: 44
{"message":"The request body must be JSON."}HTTP/1.1 413 Request Entity Too Large
Content-Type: application/json
Content-Length: 44
Connection: close
{"message":"The request body is too large."}2026/12/03 19:03:22 INFO listening addr=:8080Four requests: a good one, a JSON body cut off (400, with the decoder’s reason), a form-encoded body (415), and big.json, a body with a 70 KB guest name (413; -d @file makes curl send a file). *http.MaxBytesError is the error type the reader returns past the limit, found with errors.As (the error-wrapping lesson).
The response echoes the decoded struct: guest and nights came out of their pointers, and email, not sent, is "". That is the place to validate.
Validating
2. Rules, and a 422 like Laravel’s
validate checks each field and collects messages in a validationErrors, a named map type with an add method (the methods lesson). The pointer fields tell “not sent” (nil) from “sent as 0”, so nights: 0 gets the range message, not the required one. The messages are Laravel’s own wording, so the frontend shows the same text it already shows for PHP endpoints.
utf8.RuneCountInString counts characters, not bytes: len of “Jørgen” is 7, its rune count is 6, and Laravel’s max:255 counts characters. mail.ParseAddress checks an address the way mail software reads it.
package main
import (
"encoding/json/v2"
"errors"
"log/slog"
"net/http"
"net/mail"
"os"
"strings"
"unicode/utf8"
)
// StoreBooking is the body of POST /api/bookings. Pointers tell a missing field from a zero one.
type StoreBooking struct {
Guest *string `json:"guest"`
Nights *int `json:"nights"`
Email string `json:"email"`
}
// writeJSON sends v as a JSON response with the given status.
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.MarshalWrite(w, v, json.Deterministic(true)); err != nil {
slog.Error("writing the response", "err", err)
}
}
// maxBodyBytes is the largest request body accepted: a booking is a few hundred bytes.
const maxBodyBytes = 64 * 1024
// decodeJSON reads the request body into dst. On failure it has already answered the request, and
// returns false.
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
if mediaType := r.Header.Get("Content-Type"); !strings.HasPrefix(mediaType, "application/json") {
writeJSON(w, http.StatusUnsupportedMediaType, map[string]string{"message": "The request body must be JSON."})
return false
}
body := http.MaxBytesReader(w, r.Body, maxBodyBytes)
if err := json.UnmarshalRead(body, dst); err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"message": "The request body is too large."})
return false
}
writeJSON(w, http.StatusBadRequest, map[string]string{"message": "The request body is not valid JSON: " + err.Error()})
return false
}
return true
}
// validationErrors is Laravel's shape: each field with its messages.
type validationErrors map[string][]string
func (v validationErrors) add(field, message string) {
v[field] = append(v[field], message)
}
// validate checks a StoreBooking the way a Form Request's rules() would.
func validate(req StoreBooking) validationErrors {
errs := validationErrors{}
switch {
case req.Guest == nil || strings.TrimSpace(*req.Guest) == "":
errs.add("guest", "The guest field is required.")
case utf8.RuneCountInString(*req.Guest) > 255:
errs.add("guest", "The guest field must not be greater than 255 characters.")
}
switch {
case req.Nights == nil:
errs.add("nights", "The nights field is required.")
case *req.Nights < 1 || *req.Nights > 28:
errs.add("nights", "The nights field must be between 1 and 28.")
}
if req.Email != "" {
if _, err := mail.ParseAddress(req.Email); err != nil || !strings.Contains(req.Email, ".") {
errs.add("email", "The email field must be a valid email address.")
}
}
return errs
}
// writeValidation answers 422 the way Laravel does: the first message, and every field's messages.
func writeValidation(w http.ResponseWriter, errs validationErrors) {
first := ""
for _, field := range []string{"guest", "nights", "email"} {
if messages, ok := errs[field]; ok {
first = messages[0]
break
}
}
writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"message": first, "errors": errs})
}
func storeBooking(w http.ResponseWriter, r *http.Request) {
var req StoreBooking
if !decodeJSON(w, r, &req) {
return
}
if errs := validate(req); len(errs) > 0 {
writeValidation(w, errs)
return
}
const id = 5524 // stands in for the insert ... returning id of the Postgres lesson
w.Header().Set("Location", "/api/bookings/5524")
writeJSON(w, http.StatusCreated, map[string]any{"data": map[string]any{"id": id, "guest": strings.TrimSpace(*req.Guest), "nights": *req.Nights}})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("POST /api/bookings", storeBooking)
slog.Info("listening", "addr", ":8080")
if err := http.ListenAndServe(":8080", mux); err != nil {
slog.Error("server stopped", "err", err)
os.Exit(1)
}
}
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/bookings/5524
Content-Length: 49
{"data":{"guest":"Jørgen","id":5524,"nights":3}}HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
Content-Length: 209
{"errors":{"email":["The email field must be a valid email address."],"guest":["The guest field is required."],"nights":["The nights field must be between 1 and 28."]},"message":"The guest field is required."}HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
Content-Length: 196
{"errors":{"email":["The email field must be a valid email address."],"guest":["The guest field is required."],"nights":["The nights field is required."]},"message":"The guest field is required."}2026/12/03 19:03:23 INFO listening addr=:8080The second request fails three rules, and the 422 lists every field with its message, message being the first one, exactly as Laravel’s handler builds it. v2 writes a map’s keys in no fixed order by default; writeJSON passes json.Deterministic(true), which sorts them, so the same errors always give the same bytes, which tests and caches rely on.
201 Created with a Location header is the HTTP answer to a POST that created something. const id = 5524 stands in for the database insert of the Postgres lesson; the next lesson connects the handler to a real pool.
3. Why not a validation library
Libraries like go-playground/validator read rules from struct tags (validate:"required,max=255"), the closest thing to Laravel’s rules() array. They are widely used, and the messages they produce need translating into your API’s wording anyway.
For a small service with a few endpoints, plain functions like validate are easier to read, test and change, and need no dependency. The rule of this course applies: a third-party module only where the standard library has no answer.
Coming from PHP
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
final class StoreBookingRequest extends FormRequest
{
/** @return array<string, list<string>> */
public function rules(): array
{
return [
'guest' => ['required', 'string', 'max:255'],
'nights' => ['required', 'integer', 'between:1,28'],
'email' => ['nullable', 'email'],
];
}
}
The three rules lines become about twenty lines of Go. In exchange, every check is a line you can read, step through and test without booting a framework, and each status code (400, 413, 415, 422) is a decision made in one place.
Laravel also caps the body (post_max_size in php.ini) and refuses non-JSON for $request->json(); those limits are just outside your code. In Go they are part of the handler, and forgetting MaxBytesReader is the classic omission.
PracticeLearn Go with Tests: JSON, routing and embedding; a test for validate
Do JSON, routing and embedding in Learn Go with Tests.
Exercise: test the rules
Write a table test for validate (the tests lesson): each case is a StoreBooking, written with small helper functions str(s string) *string and num(n int) *int to make the pointers, and the expected validationErrors. Compare with maps.EqualFunc and slices.Equal. Cover every message, a valid booking with no email, and a 255-character name in Danish letters.
Remember
- Check the
Content-Typeand wrap the body inhttp.MaxBytesReaderbefore decoding. - 400 for a body that is not JSON, 413 too large, 415 wrong type, 422 wrong values, in Laravel’s shape.
- Encode responses with
json.Deterministic(true)when maps are in them.
Tomorrow: handlers as methods on a struct that holds the database pool, and one function that turns every error into the right status.