Hands-On RESTful Web Services with Go
上QQ阅读APP看书,第一时间看更新

ServeMux – a basic router in Go

ServeMux is an HTTP request multiplexer. The HandleFunc we used in the preceding section is actually a method of ServeMux. By using ServeMux, we can handle multiple routes. We can also create our own multiplexer. A multiplexer handles the logic of separating routes with a function called ServeHTTP. So, if we create a Go struct with the ServeHTTP method, it can do the job as the in-built multiplexer.

Consider a route as a key in a Go dictionary (map) and a multiplexer as its value. Go finds the multiplexer from the route and tries to execute the ServeHTTP function. In the following section, we will see the usage of ServeMux by creating an API that generates UUID strings.