A ServeMux’s HandleFunc method registers a handler function for an HTTP pattern. The mux routes matching requests to that function and can itself be passed to http.ListenAndServe because it implements http.Handler. section 8.2.1 section 11.1.1
The method takes a pattern string and a function with the signature func(http.ResponseWriter, *http.Request). The handler can be an ordinary function or a method. Patterns can include an HTTP method, such as "POST /games" or "GET /". section 8.2.1 section 11.1.1
Register two routes
Save as main.go and run go run main.go: ```go package main import ( "io" "log" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, "Hello, world!") }) mux.HandleFunc("POST /games", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) _, _ = io.WriteString(w, "Creating a new game") }) log.Fatal(http.ListenAndServe(":8080", mux)) } ``` Try curl -v localhost:8080/ and curl -v -X POST localhost:8080/games. The POST handler sets 201 before writing the response body; writing the body first would send the default 200 status. section 8.2.1 section 11.1.1
Listing 11.3 server.go: Server struct
// Server serves all the HTML routes on this service.
type Server struct {} #1
func New() *Server... #2
// Router returns an HTTP handler that listens to all the proper paths.
func (s *Server) Router() http.Handler {
r := http.NewServeMux() #3
// Register each endpoint.
r.HandleFunc(http.MethodGet+" "+"/", s.index) #4
return r
}
A Server method can be registered directly as the handler for a method-qualified route. section 11.1.1
