ServeMux is an HTTP request multiplexer. The HandleFunc
we used in the preceding section is actually a method of ServeMux. By creating a new ServeMux, we can handle multiple routes. Before that, we can also create our own multiplexer. A multiplexer just handles the logic of separating routes with a function called ServeHTTP
. So if we create a new struct with the ServeHTTP
method, it can do the job.
Consider a route as a key in a dictionary (map), then the handler as its value. The router finds the handler from the route and tries to execute the ServeHTTP
function. Let us create a program called customMux.go
and see this implementation in action:
package main import ( "fmt" "math/rand" "net/http" ) // CustomServeMux is a struct which can be a multiplexer type CustomServeMux struct { } // This is the function handler to be overridden func (p *CustomServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { giveRandom...