Service Mux
Service Mux
The goa HTTP request mux is in charge of dispatching incoming requests to the correct controller action. It implements the goa ServeMux interface which on top of the usual binding of HTTP method and path to handler also provides the ability to lookup registered handlers.
The ServeMux
interface
Handle method associates a
request HTTP method and path to a
MuxHandler which is a
function that accepts an http ResponseWriter and Request as well as an instance of url Values that
contain all the path and querystring parameters.
The code generated by goagen
automatically calls the Handle
function. Calling this function
directly is only needed to mount handlers that are not generated, for example handlers that may
provide supporting functionality that comes from third party packages. In particular wrapping a HTTP
handler from the stdlib http package is trivially done:
// assetHandler returns the handler in charge of serving static assets.
func assetHandler() goa.MuxHandler {
base := "/path/to/website/static/files"
h := gzip.FileServer(http.Dir(base))
return func(rw http.ResponseWriter, req *http.Request, v url.Values) {
h.ServeHTTP(rw, req)
}
}
Such handlers can be mounted on the service mux:
func main() {
service := goa.New("Service with assets")
service.Mux.Handle("GET", "/static/*asset", assetHandler())
// ...
}
Handling NotFound
The ServeMux
interface also exposes a HandleNotFound
method which sets the handler invoked when
a request is sent to a path that does not correspond to a registered handler. The Service
data
structure takes advantage of that function to register a generic not found handler which returns a
response with status code 404.