A game service needs to create games, accept guesses, and report game status. Each HTTP endpoint pairs a path with a method: the path identifies a resource, while the method identifies the requested action. Use `/games` for the collection and `/games/{game_id}` when addressing one game. section 8.2
Choose the method to match the action:
- GET accesses a resource. section 8.2
- POST creates a resource or asks for data to be processed. section 8.2
- PUT updates a resource. section 8.2
- DELETE deletes a resource. section 8.2
GET, PUT, and DELETE should be idempotent: repeating a request should leave the resource in the same state as making it once. Use POST instead for a non-idempotent endpoint, and document any API behavior that is not idempotent. section 8.2
Create a game with POST /games
Creating a game does not require input, but the response needs an ID for later guess and status requests. Choose `POST /games` and return that ID. If a resource ID is already known, PUT can instead be suitable for creation—for example, a book at `/books/9781633438804`. section 8.2.1 section 8.2.1
In Go, a handler can reject `req.Method != http.MethodPost` with `http.StatusMethodNotAllowed`; a method-and-path router registration is another option. A plain `curl -v localhost:8080/games` sends GET and receives 405, while `curl -v -X POST localhost:8080/games` reaches the creation handler. Set `http.StatusCreated` before writing the response body: writing first produces an unwanted default 200 response. Test the POST handler with `http.NewRequest` and `httptest.NewRecorder`, checking for 201 and the expected JSON response. 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 registers the HTTP method and resource path together, making `POST /games` the route to the creation handler. section 8.2.1









