Documentation
¶
Overview ¶
Package router provides HTTP routing functionality built on top of the Gin web framework. It offers a flexible router list system, middleware support, authentication helpers, and header management utilities.
Key features:
- RouterList: Organize routes with optional grouping
- Middleware: Latency tracking, request context, access logging, error recovery
- Authentication: Authorization handlers with customizable check functions
- Headers: Manage HTTP headers across routes
Example usage:
routerList := router.NewRouterList(router.DefaultGinInit)
routerList.Register(http.MethodGet, "/api/health", healthHandler)
routerList.RegisterInGroup("/api/v1", http.MethodGet, "/users", usersHandler)
engine := routerList.Engine()
routerList.Handler(engine)
engine.Run(":8080")
See also:
- github.com/gin-gonic/gin for the underlying web framework
- github.com/nabbar/golib/logger for logging integration
- github.com/nabbar/golib/errors for error handling
Index ¶
- Constants
- func DefaultGinInit() *ginsdk.Engine
- func DefaultGinWithTrustedPlatform(trustedPlatform string) *ginsdk.Engine
- func DefaultGinWithTrustyProxy(trustyProxy []string) *ginsdk.Engine
- func GinAccessLog(log liblog.FuncLog) ginsdk.HandlerFunc
- func GinAddGlobalMiddleware(eng *ginsdk.Engine, middleware ...ginsdk.HandlerFunc) *ginsdk.Engine
- func GinEngine(trustedPlatform string, trustyProxy ...string) (*ginsdk.Engine, error)
- func GinErrorLog(log liblog.FuncLog) ginsdk.HandlerFunc
- func GinLatencyContext(c *ginsdk.Context)
- func GinRequestContext(c *ginsdk.Context)
- func Handler(routerList RouterList) http.Handler
- func RoutersHandler(engine *ginsdk.Engine)
- func RoutersRegister(method string, relativePath string, router ...ginsdk.HandlerFunc)
- func RoutersRegisterInGroup(group, method string, relativePath string, router ...ginsdk.HandlerFunc)
- func SetGinHandler(fct func(c *ginsdk.Context)) ginsdk.HandlerFunc
- type RegisterRouter
- type RegisterRouterInGroup
- type RouterList
Constants ¶
const ( // ErrorParamEmpty indicates that a required parameter was not provided or is empty. ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgRouter // ErrorConfigValidator indicates that configuration validation failed. ErrorConfigValidator // ErrorHeaderAuth indicates an invalid response code from authorization check. ErrorHeaderAuth // ErrorHeaderAuthMissing indicates that the Authorization header is missing from the request. ErrorHeaderAuthMissing // ErrorHeaderAuthEmpty indicates that the Authorization header is present but empty. ErrorHeaderAuthEmpty // ErrorHeaderAuthRequire indicates that authorization check failed and authentication is required. // This typically results in HTTP 401 Unauthorized. ErrorHeaderAuthRequire // ErrorHeaderAuthForbidden indicates that authorization check succeeded but the client is not authorized. // This typically results in HTTP 403 Forbidden. ErrorHeaderAuthForbidden )
Error codes for the router package. These codes are used with github.com/nabbar/golib/errors for structured error handling.
const ( // EmptyHandlerGroup is the identifier used for routes registered without a group. // Routes with this group are registered directly on the engine root. EmptyHandlerGroup = "<nil>" // GinContextStartUnixNanoTime is the context key for storing request start time in nanoseconds. // Used by GinLatencyContext middleware to calculate request duration. GinContextStartUnixNanoTime = "gin-ctx-start-unix-nano-time" // GinContextRequestPath is the context key for storing the sanitized request path. // Includes query parameters if present. Set by GinRequestContext middleware. GinContextRequestPath = "gin-ctx-request-path" // GinContextRequestUser is the context key for storing the authenticated user from URL. // Set by GinRequestContext middleware when user info is present in the request URL. GinContextRequestUser = "gin-ctx-request-user" )
Variables ¶
This section is empty.
Functions ¶
func DefaultGinInit ¶ added in v1.6.0
DefaultGinInit creates a new Gin engine with default middleware. The engine includes Logger and Recovery middleware from Gin.
This is the default initializer used by NewRouterList when no custom initializer is provided.
Returns a configured Gin engine ready to use.
func DefaultGinWithTrustedPlatform ¶ added in v1.7.4
DefaultGinWithTrustedPlatform creates a new Gin engine with trusted platform header. The engine includes Logger and Recovery middleware.
The trusted platform header is used to determine the client's real IP address when behind a CDN or load balancer (e.g., "X-CDN-IP", "X-Real-IP").
Parameters:
- trustedPlatform: Name of the header to trust for client IP
Returns a configured Gin engine with trusted platform set.
func DefaultGinWithTrustyProxy ¶ added in v1.6.0
DefaultGinWithTrustyProxy creates a new Gin engine with trusted proxy configuration. The engine includes Logger and Recovery middleware.
Trusted proxies are IP addresses or CIDR ranges that are allowed to set X-Forwarded-For, X-Real-IP, and other forwarding headers.
Parameters:
- trustyProxy: List of trusted proxy IP addresses or CIDR ranges
Returns a configured Gin engine with trusted proxies set.
func GinAccessLog ¶ added in v1.9.8
func GinAccessLog(log liblog.FuncLog) ginsdk.HandlerFunc
GinAccessLog is a middleware that logs HTTP access information. It should be used after GinLatencyContext and GinRequestContext to have access to timing and request path information.
The middleware logs:
- Client IP address
- Authenticated user (if any)
- Request timestamp
- Request duration
- HTTP method
- Request path with query parameters
- HTTP protocol version
- Response status code
- Response size in bytes
If log is nil or returns nil, no logging is performed.
Usage:
logFunc := func() logger.Logger { return myLogger }
engine.Use(router.GinLatencyContext)
engine.Use(router.GinRequestContext)
engine.Use(router.GinAccessLog(logFunc))
See also: github.com/nabbar/golib/logger
func GinAddGlobalMiddleware ¶ added in v1.9.8
GinAddGlobalMiddleware adds one or more middleware functions to the Gin engine. The middleware will be applied to all routes registered on the engine.
Parameters:
- eng: Gin engine to add middleware to
- middleware: One or more middleware handler functions
Returns the same engine for method chaining.
Example:
engine := gin.New() router.GinAddGlobalMiddleware(engine, router.GinLatencyContext, router.GinRequestContext)
func GinEngine ¶ added in v1.9.8
GinEngine creates a new Gin engine with optional trusted platform and proxies. Unlike the Default* functions, this does not add any middleware by default.
Parameters:
- trustedPlatform: Header name to trust for client IP (e.g., "X-Real-IP")
- trustyProxy: Optional list of trusted proxy IP addresses or CIDR ranges
Returns:
- *gin.Engine: Configured Gin engine
- error: Error from SetTrustedProxies if proxy configuration fails
Example:
engine, err := router.GinEngine("X-Forwarded-For", "127.0.0.1", "192.168.0.0/16")
if err != nil {
log.Fatal(err)
}
func GinErrorLog ¶ added in v1.9.8
func GinErrorLog(log liblog.FuncLog) ginsdk.HandlerFunc
GinErrorLog is a middleware that handles panic recovery and error logging. It catches panics, logs errors from the Gin context, and sends appropriate HTTP responses. Should be used with GinRequestContext to have access to the request path.
The middleware:
- Recovers from panics and converts them to errors
- Detects broken pipe errors (client disconnected)
- Logs all errors attached to the Gin context
- Logs recovered panics
- Returns 500 Internal Server Error for panics (except broken pipes)
Special handling:
- Broken pipe errors: Connection is aborted without writing status
- Other panics: Returns HTTP 500 status
If log is nil or returns nil, errors are recovered but not logged.
Usage:
logFunc := func() logger.Logger { return myLogger }
engine.Use(router.GinRequestContext)
engine.Use(router.GinErrorLog(logFunc))
See also:
- github.com/nabbar/golib/logger for logging
- github.com/nabbar/golib/errors for error types
func GinLatencyContext ¶ added in v1.9.8
GinLatencyContext is a middleware that records the request start time. It stores the current time in nanoseconds in the Gin context under the key GinContextStartUnixNanoTime. This allows subsequent middleware or handlers to calculate request latency.
Usage:
engine.Use(router.GinLatencyContext)
To calculate latency in a handler:
startTime := time.Unix(0, c.GetInt64(router.GinContextStartUnixNanoTime)) latency := time.Since(startTime)
func GinRequestContext ¶ added in v1.9.8
GinRequestContext is a middleware that extracts and stores request information. It sanitizes and stores the request path (with query parameters) and username (if present in the URL) in the Gin context.
Stored context keys:
- GinContextRequestPath: Sanitized request path with query string
- GinContextRequestUser: Username from URL (if present)
The sanitization prevents log injection attacks by removing newlines, tabs, etc.
Usage:
engine.Use(router.GinRequestContext)
func Handler ¶
func Handler(routerList RouterList) http.Handler
Handler creates an http.Handler from a RouterList. It initializes a Gin engine and applies all routes from the RouterList.
If routerList is nil, the global default router list is used instead.
Parameters:
- routerList: RouterList containing routes to register
Returns an http.Handler that can be used with http.Server.
Example:
routerList := router.NewRouterList(router.DefaultGinInit)
routerList.Register(http.MethodGet, "/health", healthHandler)
handler := router.Handler(routerList)
http.ListenAndServe(":8080", handler)
func RoutersHandler ¶
RoutersHandler applies all routes from the global default router list to the engine.
This is a convenience function for applications that use a single global router. For more complex applications, consider creating dedicated RouterList instances.
Parameters:
- engine: Gin engine to register routes on
func RoutersRegister ¶
func RoutersRegister(method string, relativePath string, router ...ginsdk.HandlerFunc)
RoutersRegister registers a route on the global default router list. The route is registered at root level (without a group).
This is a convenience function for applications that use a single global router. For more complex applications, consider creating dedicated RouterList instances.
Parameters:
- method: HTTP method (GET, POST, PUT, DELETE, etc.)
- relativePath: URL path for the route
- router: One or more handler functions
func RoutersRegisterInGroup ¶
func RoutersRegisterInGroup(group, method string, relativePath string, router ...ginsdk.HandlerFunc)
RoutersRegisterInGroup registers a route in a group on the global default router list.
This is a convenience function for applications that use a single global router. For more complex applications, consider creating dedicated RouterList instances.
Parameters:
- group: Group path prefix
- method: HTTP method (GET, POST, PUT, DELETE, etc.)
- relativePath: URL path for the route (will be prefixed with group)
- router: One or more handler functions
func SetGinHandler ¶
func SetGinHandler(fct func(c *ginsdk.Context)) ginsdk.HandlerFunc
SetGinHandler is a type conversion helper that converts a function to HandlerFunc. This is useful when you have a function that matches the HandlerFunc signature but needs explicit type conversion.
Parameters:
- fct: Function with signature func(*gin.Context)
Returns the function as a gin.HandlerFunc type.
Types ¶
type RegisterRouter ¶
type RegisterRouter func(method string, relativePath string, router ...ginsdk.HandlerFunc)
RegisterRouter is a function type for registering routes without a group. It takes an HTTP method, relative path, and one or more handler functions.
type RegisterRouterInGroup ¶
type RegisterRouterInGroup func(group, method string, relativePath string, router ...ginsdk.HandlerFunc)
RegisterRouterInGroup is a function type for registering routes within a group. It takes a group path, HTTP method, relative path, and one or more handler functions.
type RouterList ¶
type RouterList interface {
// Register adds a route without a group (registered at root level).
// Multiple handlers can be provided and will be executed in order.
Register(method string, relativePath string, router ...ginsdk.HandlerFunc)
// RegisterInGroup adds a route within a specified group.
// The group path is prefixed to the relative path.
// Multiple routes can be registered in the same group.
RegisterInGroup(group, method string, relativePath string, router ...ginsdk.HandlerFunc)
// RegisterMergeInGroup adds or replaces a route in a group.
// If a route with the same method and path already exists in the group,
// its handlers are replaced with the new ones.
RegisterMergeInGroup(group, method string, relativePath string, router ...ginsdk.HandlerFunc)
// Handler applies all registered routes to the given Gin engine.
// Routes are organized by group and registered accordingly.
Handler(engine *ginsdk.Engine)
// Engine returns a new Gin engine instance using the configured init function.
// If no init function was provided, DefaultGinInit is used.
Engine() *ginsdk.Engine
}
RouterList manages a collection of HTTP routes with optional grouping. It provides methods to register routes, organize them into groups, and apply them to a Gin engine.
All methods are safe for concurrent use.
func NewRouterList ¶
func NewRouterList(initGin func() *ginsdk.Engine) RouterList
NewRouterList creates a new RouterList instance with the specified Gin engine initializer. If initGin is nil, DefaultGinInit will be used when Engine() is called.
Example:
routerList := NewRouterList(func() *gin.Engine {
engine := gin.New()
engine.Use(gin.Logger(), gin.Recovery())
return engine
})
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package auth provides HTTP authorization middleware for Gin-based applications.
|
Package auth provides HTTP authorization middleware for Gin-based applications. |
|
Package authheader provides HTTP authorization header constants and helper functions.
|
Package authheader provides HTTP authorization header constants and helper functions. |
|
Package header provides HTTP header management for Gin-based applications.
|
Package header provides HTTP header management for Gin-based applications. |