ProgramGuru

Handling Request Bodies

Start with Handling Request Bodies

In this lesson, explore handling request bodies through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of handling request bodies.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

The request body is a stream of bytes. For JSON input, use json.Decoder on r.Body. Bound incoming body sizes to protect resources and reject malformed payloads.

In a real handler, check the Content-Type and ensure the payload contains exactly the expected JSON value when that is your contract.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for request bodyA valid HTTP request still needs bounded parsing.POST JSON bodyStep 1Limit body sizeStep 2Decode and validateStep 3ReplyStep 4A valid HTTP request still needs bounded parsing.
A valid HTTP request still needs bounded parsing.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
)

func main() {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var input struct {
			Name string `json:"name"`
		}
		r.Body = http.MaxBytesReader(w, r.Body, 1024)
		if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
			http.Error(w, "invalid JSON", 400)
			return
		}
		fmt.Fprint(w, "Hello, ", input.Name)
	})
	rec := httptest.NewRecorder()
	request := httptest.NewRequest("POST", "/", strings.NewReader(`{"name":"Mina"}`))
	handler.ServeHTTP(rec, request)
	fmt.Print(rec.Body.String())
}

Output

Hello, Mina

Trace what the program does

The decoder reads the supplied JSON into a struct. The body size is capped, and the handler responds Hello, Mina.

Avoid common mistakes

  • Avoid reading unlimited request bodies into memory.
  • Validate required fields after successful decoding; valid JSON can still be semantically invalid.

Try it yourself

Reject an empty name with a 400 response and test both valid and invalid bodies.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What helps protect a JSON handler from extremely large input?
Choose one answer. You can try again.

Answer and explanation

http.MaxBytesReader

Correct. The decoder reads the supplied JSON into a struct.

What you should remember

You have practiced Handling Request Bodies in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Sending HTTP Responses →