A service with several endpoints needs a way to send each request to the right function. Create an http.ServeMux, register routes with its HandleFunc method, and pass the mux to http.ListenAndServe. ServeMux implements http.Handler, so it can serve as the server’s handler. section 8.2.1
HandleFunc takes a pattern and a function with the signature func(http.ResponseWriter, *http.Request). The function may be a package-level function or a method on a server struct. Keep registrations together in a function that builds and returns the router; endpoint logic can live elsewhere. section 8.2.1 section 11.1.1
Listing 8.4 internal/handlers/router.go: Handler to URL association
package handlers
import (
"net/http"
"learngo-pockets/httpgordle/internal/api"
"learngo-pockets/httpgordle/internal/newgame"
)
// Mux creates a multiplexer with all the endpoints for our service.
func Mux() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc(api.NewGameRoute, newgame.Handle) #1
return mux
}
The /games route is associated with newgame.Handle in one place, and the completed mux is returned for use by the server. section 8.2.1
A path-only pattern such as "/games" leaves the handler to check the request method. A method-and-path pattern such as http.MethodPost + " " + "/games" puts that condition in the registration. The same approach registers a server’s index method for GET requests to "/". section 8.2.1 section 11.1.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
}
This router registers the game-creation handler with a POST-and-path pattern rather than checking the method inside the handler. section 8.2.1
Try the game route
With a path-only registration and a handler that rejects non-POST requests, `curl -v localhost:8080/games` sends GET and receives `405 Method Not Allowed`. `curl -v -X POST localhost:8080/games` reaches the handler. The initial response says “Creating a new game”; the later handler sets `201 Created` before writing its response. section 8.2.1
