routergroup

package
v0.18.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 22, 2025 License: MIT Imports: 1 Imported by: 0

README

Router Groups

A RouterGroup can be used to group a collection of endpoints under the same prefix. It can also be used to define a set of Middleware that should apply to all endpoints registered on this group.

Usage

Example with public and private route groups:

router := http.NewServeMux()

// Public routes (no authentication needed)
publicGroup := routergroup.NewRouterGroup("/api/public", router)
publicGroup.Use(middleware.RequestIdMiddleware)
publicGroup.Use(middleware.AccessLogMiddleware)

// Private routes (authentication required)
authParams := middleware.NewAuthParams(jwtSecret, userRepo)
privateGroup := routergroup.NewRouterGroup("/api/private", router)
privateGroup.Use(middleware.RequestIdMiddleware)
privateGroup.Use(middleware.AccessLogMiddleware)
privateGroup.Use(func(next http.Handler) http.Handler {
    return middleware.Auth(next, authParams)
})

// Register routes
publicGroup.HandleFunc("GET", "/health", healthHandler)
privateGroup.HandleFunc("GET", "/users", getUsersHandler)

Custom middleware:

logTime := func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        next.ServeHTTP(w, r)
        log.Printf("Request took: %v", time.Since(start))
    })
}

apiGroup := routergroup.NewRouterGroup("/api", router)
apiGroup.Use(logTime)
apiGroup.HandleFunc("GET", "/items", getItemsHandler)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Middleware

type Middleware func(http.Handler) http.Handler

type RouterGroup

type RouterGroup struct {
	Prefix      string
	Middlewares []Middleware
	Mux         *http.ServeMux
}

func NewRouterGroup

func NewRouterGroup(prefix string, mux *http.ServeMux) *RouterGroup

func (*RouterGroup) HandleFunc

func (g *RouterGroup) HandleFunc(method string, pattern string, handlerFunc http.HandlerFunc)

func (*RouterGroup) Use

func (g *RouterGroup) Use(mw Middleware)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL