An HTTP handler receives a request and produces a response. In a Go web service, a router directs requests for an endpoint to its handler. The handler uses an http.ResponseWriter to set the status, headers, and body. section 8.1.1 section 8.7
Start a server with http.ListenAndServe(":8080", handlers.Mux()). The server keeps listening until stopped; the second argument supplies the handler that dispatches requests. An http.Handler implements ServeHTTP(ResponseWriter, *Request). For a small endpoint, register a function with a ServeMux using HandleFunc instead. section 8.1.2 section 8.2.1
Listing 8.10 internal/handlers/router.go: Setting the verb and path
package handlers
import (
"net/http"
"learngo-pockets/httpgordle/internal/api"
"learngo-pockets/httpgordle/internal/handlers/newgame"
)
// NewRouter returns a router that listens for requests
// to the following endpoints:
// - Create a new game;
//
// The provided router is ready to serve.
func NewRouter() *http.ServeMux {
r := http.NewServeMux()
r.HandleFunc(http.MethodPost+" "+api.NewGameRoute, #1
newgame.Handle) #1
return r
}
The router pairs POST and /games with the new-game handler, keeping request dispatch separate from endpoint logic. section 8.2.1
Create a game
For POST /games, a handler sets Content-Type to application/json, writes 201 Created, then encodes a game response to the writer. Test it with curl -v -X POST localhost:8080/games; a handler test can pass an http.NewRequest and httptest.NewRecorder directly to Handle, then check the status, header, and JSON body. section 8.2.1
Keep the response sequence and failure paths explicit:
- Reject an unsupported method with 405 Method Not Allowed and return, unless the router already restricts the method. section 8.2.1
- Call WriteHeader before Write when the response needs a status other than the default 200 OK; writing the body first makes a later WriteHeader ineffective. section 8.2.1 section 8.7
- For a JSON request body, decode request.Body into a request structure. On decoding failure, use http.Error with 400 Bad Request and return; supply a body when constructing the corresponding test request. section 8.2.3
- Once response headers have been sent, an encoding failure cannot be turned into a different HTTP status; log the failure. section 8.2.1 section 8.7





















