liveBook · Manning

HTTP multiplexer

As explained in Go in Action, Second Edition

An HTTP multiplexer is a routing component that selects handlers for requests according to their paths.

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

How Go in Action, Second Edition covers it

How deep it goes
Explains route registration and method dispatch, but does not detail the multiplexer’s internal matching algorithm.
Examples
Uses a /hello endpoint with GET, POST, and unsupported PUT requests tested through a table-driven server test.
What it assumes
Builds from URL paths, routes, handler functions, and HTTP methods before assembling a multi-route server.
What you can do after
Configure HTTP routing with net/http and verify endpoint behavior using httptest.
How it connects
Connects routes, HTTP handlers, HTTP methods, status codes, and httptest server testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.