We can define the preceding route in two steps:
- First, define the path on the router:
r := mux.NewRouter()
- Next, define the handler on the router:
r.Path("/articles/{category}/{id:[0- 9]+}").HandlerFunc(ArticleHandler) //chaining is possible
Be aware that the method chained here is HandlerFunc and not HandleFunc, as shown in the preceding code. We can create a top-level path and add subpaths to different handlers easily in Mux using Subrouter:
r := mux.NewRouter()
s := r.PathPrefix("/articles").Subrouter()
s.HandleFunc("{id}/settings", settingsHandler)
s.HandleFunc("{id}/details", detailsHandler)
So all the URLs of the form http://localhost:8000/articles/123/settings redirect to settingsHandler and URLs of the form http://localhost:8000/articles/123/details redirect to the detailsHandler. This might be useful when we create a namespace for grouping particular URL paths.