The following example demonstrates how to use routegroup to organize a real-world web service. It showcases:
- Mounting a base router: Using
routegroup.Mount(http.NewServeMux(), s.rootURL) to create a bundle with a base path. - Global Middleware: Applying middleware to the entire router using
.Use(). - Route Grouping: Using
.Group().Route(func(b *routegroup.Bundle) { ... }) to create logical segments (like /admin) with their own middleware stack. - Middleware Scoping: Using
.With(middleware) to apply specific middleware to a subset of routes within a group without affecting the rest of the group. - Nested Routing: Using
.Mount(path).Route(...) to create deeply nested route hierarchies. - Static File Serving: Integrating standard
http.FileServer with routegroup patterns.
// Routes returns http.Handler that handles all the routes for the Service.
func (s *Service) Routes() http.Handler {
router := routegroup.Mount(http.NewServeMux(), s.rootURL)
// add common middlewares
router.Use(rest.Maybe(handlers.CompressHandler, func(*http.Request) bool { return !s.skipGZ }))
router.Use(rest.Throttle(s.limitActiveReqs))
router.Use(s.middleware.securityHeaders(s.skipSecurityHeaders))
// prepare csrf middleware
csrfMiddleware := s.middleware.csrf(s.skipCSRFCheck)
// add open routes
router.HandleFunc("GET /login", s.loginPageHandler)
router.HandleFunc("POST /login", s.loginCheckHandler)
router.HandleFunc("GET /logout", s.logoutHandler)
// add routes with auth middleware
router.Group().Route(func(auth *routegroup.Bundle) {
auth.Use(s.middleware.Auth())
auth.HandleFunc("GET /update", s.pwdUpdateHandler)
auth.With(csrfMiddleware).HandleFunc("PUT /update", s.pwdUpdateHandler)
})
// add admin routes
router.Mount("/admin").Route(func(admin *routegroup.Bundle) {
admin.Use(s.middleware.Auth("admin"))
admin.Use(s.middleware.AdminOnly)
admin.HandleFunc("GET /", s.admin.renderHandler)
admin.With(csrfMiddleware).Route(func(csrf *routegroup.Bundle) {
csrf.HandleFunc("DELETE /sessions", s.admin.deleteSessionsHandler)
csrf.HandleFunc("POST /user", s.admin.addUserHandler)
csrf.HandleFunc("DELETE /user", s.admin.deleteUserHandler)
})
})
router.HandleFunc("GET /static/*", s.fileServerHandlerFunc())
return router
}