A payload is the content-bearing part of an HTTP request: the request body carries data submitted to a server. It complements path parameters, query parameters, and headers as a way to provide input to an API. section 8.2.3 section 8.2.2
A request-body payload is shaped and processed through a small API contract:
- Choose a representation, such as a JSON object containing only the fields the operation needs. section 8.2.3
- Define a Go structure for the payload and use JSON tags to map fields to JSON names. section 8.2.3
- Decode request.Body with json.NewDecoder, then return HTTP 400 when decoding fails. section 8.2.3
Submitting and decoding a guess
A Gordle guess uses PUT /games/{game_id} with the payload {"guess":"hello"}. The handler models it as GuessRequest and decodes it with json.NewDecoder(request.Body).Decode(&r). Invalid JSON produces a bad-request response. section 8.2.3
Listing 8.17 guess/handler.go: How to read a request body
// Read the request, containing the guess, from the body of the input.
r := api.GuessRequest{} #1
err := json.NewDecoder(request.Body).Decode(&r) #2
if err != nil {
http.Error(writer, err.Error(),
http.StatusBadRequest) #3
return
}
Inspect the complete Go handler fragment that reads a request body, decodes JSON, reports malformed input, and stops processing. section 8.2.3







