An HTTP multiplexer tracks routes and selects the handler attached to a request path. In Go, handlers are registered on an http.ServeMux. section 8.6
A practical multiplexer setup:
- Register a handler for /hello. section 8.6
- Dispatch GET and POST requests to separate handlers. section 8.6
- Return a not-found response for unsupported methods. section 8.6
Testing a routed server
Create an http.NewServeMux, mount the hello handler, start an httptest.NewServer, and table-test GET, POST, and PUT requests against /hello. section 8.6
Listing 8.31 handler.go: Handler with a route
func HelloHandler(mux *http.ServeMux) { #1
mux.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request) {
switch req.Method { #2
case http.MethodGet:
HelloGet(w, req)
case http.MethodPost:
HelloPost(w, req)
default: #3
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("invalid hello method"))
}
})
}
Browse the route registration that dispatches requests by method. section 8.6
