Documentation
¶
Overview ¶
Package router provides HTTP routing functionality for the Velocity framework. It uses a custom radix tree for efficient route matching and supports RESTful resources, middleware, and a clean API for web applications.
Index ¶
- Constants
- func BuildPath(segments []Segment, params map[string]string) (string, error)
- func CurrentRoute(r *http.Request) string
- func GetParams(r *http.Request) map[string]string
- func GetRequestID(r *http.Request) string
- func GetRouteName(r *http.Request) string
- func GetRoutePattern(r *http.Request) string
- func Param(r *http.Request, name string) string
- func Params(r *http.Request) map[string]string
- func SetParams(r *http.Request, params map[string]string) *http.Request
- func SetRouteName(r *http.Request, name string) *http.Request
- func WithServices(r *http.Request, s *app.Services) *http.Request
- func Wrap(h HandlerFunc) http.HandlerFunc
- type CORSConfig
- type Context
- func (c *Context) Auth() any
- func (c *Context) BadRequest(message ...string) error
- func (c *Context) Bind(v interface{}) error
- func (c *Context) CSRF() any
- func (c *Context) Cache() *cache.Manager
- func (c *Context) Cookie(name string) (*http.Cookie, error)
- func (c *Context) Crypto() crypto.Encryptor
- func (c *Context) DB() *orm.Manager
- func (c *Context) Error(status int, message string) error
- func (c *Context) Events() events.Dispatcher
- func (c *Context) Exceptions() *exceptions.Handler
- func (c *Context) Forbidden(message ...string) error
- func (c *Context) Get(key string) interface{}
- func (c *Context) GetString(key string) string
- func (c *Context) HTML(status int, html string) error
- func (c *Context) Header(name string) string
- func (c *Context) HeaderInt64(name string, defaultValue ...int64) int64
- func (c *Context) IP() string
- func (c *Context) IsAjax() bool
- func (c *Context) JSON(status int, data interface{}) error
- func (c *Context) Log() log.Logger
- func (c *Context) Mail() mail.Mailer
- func (c *Context) Method() string
- func (c *Context) NoContent() error
- func (c *Context) NotFound(message ...string) error
- func (c *Context) Param(name string) string
- func (c *Context) ParamInt(name string) (int, error)
- func (c *Context) ParamInt64(name string) (int64, error)
- func (c *Context) Path() string
- func (c *Context) Query(name string) string
- func (c *Context) QueryBool(name string) bool
- func (c *Context) QueryDefault(name, defaultValue string) string
- func (c *Context) QueryFloat64(name string, defaultValue ...float64) float64
- func (c *Context) QueryInt(name string, defaultValue ...int) int
- func (c *Context) QueryInt64(name string, defaultValue ...int64) int64
- func (c *Context) Queue() queue.Driver
- func (c *Context) Redirect(status int, rawURL string) error
- func (c *Context) Scheduler() *scheduler.Scheduler
- func (c *Context) Services() *app.Services
- func (c *Context) Set(key string, value interface{})
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) SetHeader(name, value string)
- func (c *Context) SetServices(s *app.Services)
- func (c *Context) Status(status int) error
- func (c *Context) Storage() *storage.Manager
- func (c *Context) String(status int, text string) error
- func (c *Context) Unauthorized(message ...string) error
- func (c *Context) Validator() validation.Validator
- func (c *Context) View() any
- func (c *Context) WantsJSON() bool
- type Error
- type GroupDefinition
- func (g *GroupDefinition) AddChild(prefix string) *GroupDefinition
- func (g *GroupDefinition) AddRoute(method, path string, handler HandlerFunc) *RouteDefinition
- func (g *GroupDefinition) CommitToTree(tree *Tree, globalMiddlewares []MiddlewareFunc) error
- func (g *GroupDefinition) FullPrefix() string
- func (g *GroupDefinition) Use(middlewares ...MiddlewareFunc)
- type HandlerFunc
- type MatchResult
- type MiddlewareFunc
- func CORS(config CORSConfig) MiddlewareFunc
- func NewRateLimitGroup(limiters ...MiddlewareFunc) MiddlewareFunc
- func RateLimit(requests int, window time.Duration, opts ...RateLimitOption) MiddlewareFunc
- func RateLimitByIP(requests int, window time.Duration, opts ...RateLimitOption) MiddlewareFunc
- func RateLimitByKey(requests int, window time.Duration, keyFunc func(*Context) string, ...) MiddlewareFunc
- func RateLimitByKeyWithCleanupControl(requests int, window time.Duration, keyFunc func(*Context) string, ...) (*rateLimiterWithCleanup, MiddlewareFunc)
- func RateLimitWithStore(store RateLimitStore, keyFunc func(*Context) string, opts ...RateLimitOption) MiddlewareFunc
- func SecurityHeaders() MiddlewareFunc
- func Throttle(requests int, window time.Duration, opts ...RateLimitOption) MiddlewareFunc
- func ThrottleByKey(requests int, window time.Duration, keyFunc func(*Context) string, ...) MiddlewareFunc
- type Node
- type RateLimitConfig
- type RateLimitOption
- func WithBurst(burst int) RateLimitOption
- func WithCleanupInterval(interval time.Duration) RateLimitOption
- func WithMessage(message string) RateLimitOption
- func WithOnLimitReached(callback func(*Context)) RateLimitOption
- func WithSkip(skip func(*Context) bool) RateLimitOption
- func WithTrustedProxies(proxies []string) RateLimitOption
- type RateLimitStore
- type RequestFailed
- type RequestHandled
- type RequestRouted
- type RequestStarted
- type ResourceConfig
- type ResourceController
- type ResourceRoute
- type RouteConfig
- type RouteDefinition
- type RouteNotFoundError
- type Router
- type Segment
- type SegmentType
- type Tree
- type VelocityRouter
- type VelocityRouterV2
- func (r *VelocityRouterV2) Any(path string, handler HandlerFunc) RouteConfig
- func (r *VelocityRouterV2) Delete(path string, handler HandlerFunc) RouteConfig
- func (r *VelocityRouterV2) Get(path string, handler HandlerFunc) RouteConfig
- func (r *VelocityRouterV2) Group(prefix string, fn ...func(Router)) Router
- func (r *VelocityRouterV2) Handle() http.Handler
- func (r *VelocityRouterV2) Head(path string, handler HandlerFunc) RouteConfig
- func (r *VelocityRouterV2) Match(methods []string, path string, handler HandlerFunc) RouteConfig
- func (r *VelocityRouterV2) Options(path string, handler HandlerFunc) RouteConfig
- func (r *VelocityRouterV2) Patch(path string, handler HandlerFunc) RouteConfig
- func (r *VelocityRouterV2) Post(path string, handler HandlerFunc) RouteConfig
- func (r *VelocityRouterV2) Prefix(prefix string)
- func (r *VelocityRouterV2) Put(path string, handler HandlerFunc) RouteConfig
- func (r *VelocityRouterV2) Resource(path string, controller interface{}) ResourceRoute
- func (r *VelocityRouterV2) RouteURL(name string, params map[string]string) (string, error)
- func (r *VelocityRouterV2) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *VelocityRouterV2) SetInstanceEventDispatcher(fn func(event interface{}) error)
- func (r *VelocityRouterV2) SetServices(s *app.Services)
- func (r *VelocityRouterV2) Static(directory string)
- func (r *VelocityRouterV2) Use(middlewares ...MiddlewareFunc) Router
Constants ¶
const ( // RequestIDKey is the context key for the request ID RequestIDKey contextKey = "velocity.request_id" // RouterContextKey is the context key for the router context RouterContextKey contextKey = "velocity.router_context" // RoutePatternKey is the context key for the matched route pattern RoutePatternKey contextKey = "velocity.route_pattern" )
const ( // 1xx Informational StatusContinue = http.StatusContinue StatusSwitchingProtocols = http.StatusSwitchingProtocols StatusProcessing = http.StatusProcessing StatusEarlyHints = http.StatusEarlyHints // 2xx Success StatusOK = http.StatusOK StatusCreated = http.StatusCreated StatusAccepted = http.StatusAccepted StatusNonAuthoritativeInfo = http.StatusNonAuthoritativeInfo StatusNoContent = http.StatusNoContent StatusResetContent = http.StatusResetContent StatusPartialContent = http.StatusPartialContent StatusMultiStatus = http.StatusMultiStatus StatusAlreadyReported = http.StatusAlreadyReported StatusIMUsed = http.StatusIMUsed // 3xx Redirection StatusMultipleChoices = http.StatusMultipleChoices StatusMovedPermanently = http.StatusMovedPermanently StatusFound = http.StatusFound StatusSeeOther = http.StatusSeeOther StatusNotModified = http.StatusNotModified StatusUseProxy = http.StatusUseProxy StatusTemporaryRedirect = http.StatusTemporaryRedirect StatusPermanentRedirect = http.StatusPermanentRedirect // 4xx Client Errors StatusBadRequest = http.StatusBadRequest StatusPaymentRequired = http.StatusPaymentRequired StatusForbidden = http.StatusForbidden StatusNotFound = http.StatusNotFound StatusMethodNotAllowed = http.StatusMethodNotAllowed StatusNotAcceptable = http.StatusNotAcceptable StatusProxyAuthRequired = http.StatusProxyAuthRequired StatusRequestTimeout = http.StatusRequestTimeout StatusConflict = http.StatusConflict StatusGone = http.StatusGone StatusLengthRequired = http.StatusLengthRequired StatusPreconditionFailed = http.StatusPreconditionFailed StatusRequestEntityTooLarge = http.StatusRequestEntityTooLarge StatusRequestURITooLong = http.StatusRequestURITooLong StatusUnsupportedMediaType = http.StatusUnsupportedMediaType StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable StatusExpectationFailed = http.StatusExpectationFailed StatusTeapot = http.StatusTeapot StatusMisdirectedRequest = http.StatusMisdirectedRequest StatusUnprocessableEntity = http.StatusUnprocessableEntity StatusLocked = http.StatusLocked StatusFailedDependency = http.StatusFailedDependency StatusTooEarly = http.StatusTooEarly StatusUpgradeRequired = http.StatusUpgradeRequired StatusPreconditionRequired = http.StatusPreconditionRequired StatusTooManyRequests = http.StatusTooManyRequests StatusRequestHeaderFieldsTooLarge = http.StatusRequestHeaderFieldsTooLarge // 5xx Server Errors StatusInternalServerError = http.StatusInternalServerError StatusNotImplemented = http.StatusNotImplemented StatusBadGateway = http.StatusBadGateway StatusGatewayTimeout = http.StatusGatewayTimeout StatusHTTPVersionNotSupported = http.StatusHTTPVersionNotSupported StatusVariantAlsoNegotiates = http.StatusVariantAlsoNegotiates StatusInsufficientStorage = http.StatusInsufficientStorage StatusLoopDetected = http.StatusLoopDetected StatusNotExtended = http.StatusNotExtended StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired )
HTTP status code constants re-exported from net/http for convenience, so handler authors don't need to import net/http just for status codes.
const DefaultMaxBodySize int64 = 10 * 1024 * 1024
DefaultMaxBodySize is the default maximum request body size (10MB).
Variables ¶
This section is empty.
Functions ¶
func CurrentRoute ¶
CurrentRoute returns the current route name if it exists
func GetRequestID ¶ added in v0.4.0
GetRequestID extracts the request ID from the request context
func GetRouteName ¶ added in v0.2.0
GetRouteName retrieves the current route name from the request context
func GetRoutePattern ¶ added in v0.4.0
GetRoutePattern extracts the matched route pattern from the request context
func SetParams ¶ added in v0.2.0
SetParams stores route parameters in the request context Returns a new request with the parameters stored
func SetRouteName ¶ added in v0.2.0
SetRouteName stores the current route name in the request context
func WithServices ¶ added in v0.9.14
WithServices returns a copy of r whose context carries s.
func Wrap ¶
func Wrap(h HandlerFunc) http.HandlerFunc
Wrap converts a HandlerFunc to http.HandlerFunc
Types ¶
type CORSConfig ¶ added in v0.9.2
type CORSConfig struct {
// AllowedOrigins is a list of origins allowed to access the resource.
// Use []string{"*"} to allow all origins.
AllowedOrigins []string
// AllowedMethods is a list of HTTP methods allowed for cross-origin requests.
AllowedMethods []string
// AllowedHeaders is a list of headers allowed in cross-origin requests.
AllowedHeaders []string
// ExposedHeaders is a list of headers the browser is allowed to access.
ExposedHeaders []string
// AllowCredentials indicates whether the request can include credentials.
AllowCredentials bool
// MaxAge indicates how long preflight results can be cached.
MaxAge time.Duration
}
CORSConfig holds configuration for the CORS middleware.
func DefaultCORSConfig ¶ added in v0.9.2
func DefaultCORSConfig() CORSConfig
DefaultCORSConfig returns a CORSConfig with sensible defaults.
type Context ¶
type Context struct {
Response http.ResponseWriter
Request *http.Request
// contains filtered or unexported fields
}
Context wraps http.Request and http.ResponseWriter with helper methods
func NewContext ¶
func NewContext(w http.ResponseWriter, r *http.Request) *Context
NewContext creates a new Context from http.Request and http.ResponseWriter. If services were previously stashed on r.Context() (via the router pipeline), they are inherited automatically.
func NewContextV2 ¶ added in v0.2.0
func NewContextV2(w http.ResponseWriter, r *http.Request) *Context
NewContextV2 creates a new Context using the new param storage. Inherits services from r.Context() if present.
func (*Context) Auth ¶ added in v0.9.11
Auth returns the auth manager (*auth.Manager). Requires type assertion.
func (*Context) BadRequest ¶
BadRequest sends a 400 error response
func (*Context) CSRF ¶ added in v0.9.11
CSRF returns the CSRF protection instance (*csrf.CSRF). Requires type assertion.
func (*Context) Events ¶ added in v0.9.11
func (c *Context) Events() events.Dispatcher
Events returns the event dispatcher.
func (*Context) Exceptions ¶ added in v0.9.11
func (c *Context) Exceptions() *exceptions.Handler
Exceptions returns the exception handler.
func (*Context) HTML ¶
HTML sends an HTML response. WARNING: This method writes raw, unescaped HTML content. Callers must sanitize any user-supplied input before passing it to this method to prevent XSS attacks.
func (*Context) HeaderInt64 ¶ added in v0.8.0
HeaderInt64 returns a header value as int64, with optional default
func (*Context) IP ¶
IP returns the client IP address from RemoteAddr (with port stripped). This does NOT trust X-Forwarded-For or X-Real-IP by default to prevent IP spoofing. Use the rate limiter's WithTrustedProxies option for proxy-aware IP extraction.
func (*Context) ParamInt64 ¶ added in v0.8.0
ParamInt64 returns a route parameter as int64
func (*Context) QueryBool ¶ added in v0.8.0
QueryBool returns a query parameter as bool (handles "true", "1", "yes")
func (*Context) QueryDefault ¶
QueryDefault returns a query parameter or default value if not set
func (*Context) QueryFloat64 ¶ added in v0.8.0
QueryFloat64 returns a query parameter as float64, with optional default
func (*Context) QueryInt ¶ added in v0.8.0
QueryInt returns a query parameter as int, with optional default
func (*Context) QueryInt64 ¶ added in v0.8.0
QueryInt64 returns a query parameter as int64, with optional default
func (*Context) Redirect ¶
Redirect redirects to a URL with the given status code. The URL is validated to prevent open redirects: only relative paths and same-host URLs are allowed. Absolute URLs to external domains redirect to "/".
func (*Context) SetServices ¶ added in v0.9.11
SetServices sets the service container on this context and stashes it on r.Context() so that any downstream Wrap / NewContext inherits it.
func (*Context) Unauthorized ¶
Unauthorized sends a 401 error response
func (*Context) Validator ¶ added in v0.9.11
func (c *Context) Validator() validation.Validator
Validator returns the validator.
type GroupDefinition ¶ added in v0.2.0
type GroupDefinition struct {
// contains filtered or unexported fields
}
GroupDefinition holds group configuration for deferred registration
func NewGroupDefinition ¶ added in v0.2.0
func NewGroupDefinition(prefix string, parent *GroupDefinition) *GroupDefinition
NewGroupDefinition creates a new group definition
func (*GroupDefinition) AddChild ¶ added in v0.2.0
func (g *GroupDefinition) AddChild(prefix string) *GroupDefinition
AddChild creates and adds a child group
func (*GroupDefinition) AddRoute ¶ added in v0.2.0
func (g *GroupDefinition) AddRoute(method, path string, handler HandlerFunc) *RouteDefinition
AddRoute adds a route to the group
func (*GroupDefinition) CommitToTree ¶ added in v0.2.0
func (g *GroupDefinition) CommitToTree(tree *Tree, globalMiddlewares []MiddlewareFunc) error
CommitToTree adds all routes in this group and children to the tree
func (*GroupDefinition) FullPrefix ¶ added in v0.2.0
func (g *GroupDefinition) FullPrefix() string
FullPrefix returns the complete prefix including parent prefixes
func (*GroupDefinition) Use ¶ added in v0.2.0
func (g *GroupDefinition) Use(middlewares ...MiddlewareFunc)
Use adds middleware to the group Middleware is applied during CommitToTree, so it works whether called before or after routes
type HandlerFunc ¶
HandlerFunc is the Velocity handler function signature
type MatchResult ¶ added in v0.2.0
type MatchResult struct {
Handler HandlerFunc
Params map[string]string
Name string
Path string
// contains filtered or unexported fields
}
MatchResult contains the matched route info
type MiddlewareFunc ¶
type MiddlewareFunc func(next HandlerFunc) HandlerFunc
MiddlewareFunc is the Velocity middleware function signature
func CORS ¶ added in v0.9.2
func CORS(config CORSConfig) MiddlewareFunc
CORS creates a CORS middleware with the given configuration.
func NewRateLimitGroup ¶ added in v0.8.0
func NewRateLimitGroup(limiters ...MiddlewareFunc) MiddlewareFunc
NewRateLimitGroup creates a group of rate limiters that all must pass. Useful for having multiple limits (e.g., 10/second AND 100/minute).
func RateLimit ¶ added in v0.8.0
func RateLimit(requests int, window time.Duration, opts ...RateLimitOption) MiddlewareFunc
RateLimit creates a global rate limiter middleware. It limits all requests to the specified number within the given time window.
func RateLimitByIP ¶ added in v0.8.0
func RateLimitByIP(requests int, window time.Duration, opts ...RateLimitOption) MiddlewareFunc
RateLimitByIP creates a per-IP rate limiter middleware. It extracts the client IP from RemoteAddr by default. If TrustedProxies is configured (via WithTrustedProxies), it will trust X-Forwarded-For and X-Real-IP headers only when the direct connection comes from a trusted proxy.
func RateLimitByKey ¶ added in v0.8.0
func RateLimitByKey(requests int, window time.Duration, keyFunc func(*Context) string, opts ...RateLimitOption) MiddlewareFunc
RateLimitByKey creates a per-key rate limiter middleware. Each unique key (returned by keyFunc) has its own rate limit.
func RateLimitByKeyWithCleanupControl ¶ added in v0.8.0
func RateLimitByKeyWithCleanupControl(requests int, window time.Duration, keyFunc func(*Context) string, opts ...RateLimitOption) (*rateLimiterWithCleanup, MiddlewareFunc)
RateLimitByKeyWithCleanupControl creates a per-key rate limiter with cleanup control for testing.
func RateLimitWithStore ¶ added in v0.8.0
func RateLimitWithStore(store RateLimitStore, keyFunc func(*Context) string, opts ...RateLimitOption) MiddlewareFunc
RateLimitWithStore creates a rate limiter middleware using a custom store.
func SecurityHeaders ¶ added in v0.9.2
func SecurityHeaders() MiddlewareFunc
SecurityHeaders returns a middleware that sets common security response headers. These headers help protect against common web vulnerabilities like MIME sniffing, clickjacking, and information leakage.
func Throttle ¶ added in v0.8.0
func Throttle(requests int, window time.Duration, opts ...RateLimitOption) MiddlewareFunc
Throttle is an alias for RateLimitByIP for convenience.
func ThrottleByKey ¶ added in v0.8.0
func ThrottleByKey(requests int, window time.Duration, keyFunc func(*Context) string, opts ...RateLimitOption) MiddlewareFunc
ThrottleByKey is an alias for RateLimitByKey for convenience.
type Node ¶ added in v0.2.0
type Node struct {
// contains filtered or unexported fields
}
Node represents a node in the radix tree
type RateLimitConfig ¶ added in v0.8.0
type RateLimitConfig struct {
Burst int
Skip func(*Context) bool
OnLimitReached func(*Context)
Message string
CleanupInterval time.Duration
// TrustedProxies is a list of trusted proxy IPs/CIDRs.
// Only when the direct connection comes from a trusted proxy will
// X-Forwarded-For / X-Real-IP headers be used for IP extraction.
// If empty, only RemoteAddr is used (headers are not trusted).
TrustedProxies []string
}
RateLimitConfig holds configuration for rate limiting middleware.
func (*RateLimitConfig) String ¶ added in v0.8.0
func (cfg *RateLimitConfig) String() string
String returns a description of the rate limit configuration.
type RateLimitOption ¶ added in v0.8.0
type RateLimitOption func(*RateLimitConfig)
RateLimitOption is a functional option for configuring rate limiters.
func WithBurst ¶ added in v0.8.0
func WithBurst(burst int) RateLimitOption
WithBurst sets the burst size (number of requests allowed above the limit).
func WithCleanupInterval ¶ added in v0.8.0
func WithCleanupInterval(interval time.Duration) RateLimitOption
WithCleanupInterval sets the interval for cleaning up stale limiters.
func WithMessage ¶ added in v0.8.0
func WithMessage(message string) RateLimitOption
WithMessage sets a custom error message for rate limit responses.
func WithOnLimitReached ¶ added in v0.8.0
func WithOnLimitReached(callback func(*Context)) RateLimitOption
WithOnLimitReached sets a callback invoked when the rate limit is exceeded.
func WithSkip ¶ added in v0.8.0
func WithSkip(skip func(*Context) bool) RateLimitOption
WithSkip sets a function to determine if a request should skip rate limiting.
func WithTrustedProxies ¶ added in v0.9.2
func WithTrustedProxies(proxies []string) RateLimitOption
WithTrustedProxies sets the list of trusted proxy IPs/CIDRs. When set, X-Forwarded-For and X-Real-IP headers are only trusted when the direct connection IP is in this list.
type RateLimitStore ¶ added in v0.8.0
type RateLimitStore interface {
// Allow checks if the request is allowed and records it.
// Returns true if allowed, along with remaining requests and reset time.
Allow(key string) (allowed bool, remaining int, resetTime time.Time)
}
RateLimitStore is an interface for custom rate limit storage backends.
type RequestFailed ¶ added in v0.4.0
type RequestFailed struct {
Context context.Context
RequestID string
Method string
Path string
Error error
Stack string // Stack trace if panic recovered
Recovered bool // true if recovered from panic
TraceID string // APM trace ID
SpanID string // APM span ID
}
RequestFailed is dispatched when an HTTP request fails with an error or panic
func (*RequestFailed) Name ¶ added in v0.4.0
func (e *RequestFailed) Name() string
Name returns the event name
type RequestHandled ¶ added in v0.4.0
type RequestHandled struct {
Context context.Context
RequestID string
Method string
Path string
Route string // Route pattern that was matched
StatusCode int
BytesWritten int64
Duration time.Duration
TraceID string // APM trace ID
SpanID string // APM span ID
}
RequestHandled is dispatched when an HTTP request completes successfully
func (*RequestHandled) Name ¶ added in v0.4.0
func (e *RequestHandled) Name() string
Name returns the event name
type RequestRouted ¶ added in v0.4.0
type RequestRouted struct {
Context context.Context
RequestID string
Route string // Route pattern e.g. "/users/{id}"
RouteName string // Named route if any
Params map[string]string // Route parameters
Matched bool // false for 404
}
RequestRouted is dispatched after route matching completes
func (*RequestRouted) Name ¶ added in v0.4.0
func (e *RequestRouted) Name() string
Name returns the event name
type RequestStarted ¶ added in v0.4.0
type RequestStarted struct {
Context context.Context
Method string
Path string
RemoteAddr string
UserAgent string
RequestID string
StartedAt time.Time
TraceID string // APM trace ID
SpanID string // APM span ID
}
RequestStarted is dispatched when an HTTP request begins processing
func (*RequestStarted) Name ¶ added in v0.4.0
func (e *RequestStarted) Name() string
Name returns the event name
type ResourceConfig ¶ added in v0.2.0
ResourceConfig maps HTTP verbs to controller methods
func DefaultResourceConfig ¶ added in v0.2.0
func DefaultResourceConfig() []ResourceConfig
DefaultResourceConfig returns the default REST resource configuration
type ResourceController ¶ added in v0.2.0
type ResourceController interface{}
ResourceController defines the interface for a resource controller Controllers can implement any subset of these methods
type ResourceRoute ¶
type ResourceRoute interface {
Only(methods ...string) ResourceRoute
Except(methods ...string) ResourceRoute
}
ResourceRoute represents a resource with configurable methods
type RouteConfig ¶
type RouteConfig interface {
Name(name string) RouteConfig
Use(middlewares ...MiddlewareFunc) RouteConfig
}
RouteConfig represents a single route that can be configured
type RouteDefinition ¶ added in v0.2.0
type RouteDefinition struct {
Method string
Path string
Handler HandlerFunc
Middlewares []MiddlewareFunc
Name string
}
RouteDefinition represents a route before it's committed to the tree
type RouteNotFoundError ¶
type RouteNotFoundError struct {
Name string
}
RouteNotFoundError is returned when a named route doesn't exist
func (*RouteNotFoundError) Error ¶
func (e *RouteNotFoundError) Error() string
type Router ¶
type Router interface {
// HTTP Methods - accepts Context-based handlers
Get(path string, handler HandlerFunc) RouteConfig
Post(path string, handler HandlerFunc) RouteConfig
Put(path string, handler HandlerFunc) RouteConfig
Delete(path string, handler HandlerFunc) RouteConfig
Patch(path string, handler HandlerFunc) RouteConfig
Options(path string, handler HandlerFunc) RouteConfig
Head(path string, handler HandlerFunc) RouteConfig
// Route Management
// Group creates a route group with optional closure for inline route definitions.
// Example: r.Group("/api", func(api Router) { api.Get("/users", handler) })
Group(prefix string, fn ...func(Router)) Router
Prefix(prefix string)
Resource(path string, controller interface{}) ResourceRoute
// Middleware - Context-based
Use(middlewares ...MiddlewareFunc) Router
// Serving
ServeHTTP(w http.ResponseWriter, r *http.Request)
Handle() http.Handler
}
Router defines the interface for HTTP routing
type Segment ¶ added in v0.2.0
type Segment struct {
Type SegmentType
Value string // segment value: "users" for static, "id" for param
Pattern *regexp.Regexp // compiled regex for SegmentRegex
RawPattern string // original pattern string for URL generation
}
Segment represents a parsed path segment
func ParseSegments ¶ added in v0.2.0
ParseSegments parses a path pattern into segments Supports: /static, /{param}, /{param:regex}, /{param:.*}
type SegmentType ¶ added in v0.2.0
type SegmentType int
SegmentType represents the type of path segment
const ( SegmentStatic SegmentType = iota // /users SegmentParam // /{id} SegmentRegex // /{id:[0-9]+} SegmentWildcard // /{path:.*} )
func (SegmentType) String ¶ added in v0.2.0
func (st SegmentType) String() string
String returns the string representation of the segment type
type Tree ¶ added in v0.2.0
type Tree struct {
// contains filtered or unexported fields
}
Tree is a radix tree for route matching
func (*Tree) AllowedMethods ¶ added in v0.2.0
AllowedMethods returns all HTTP methods registered for a path
func (*Tree) Insert ¶ added in v0.2.0
func (t *Tree) Insert(method, path string, handler HandlerFunc) error
Insert adds a route to the tree
func (*Tree) InsertWithName ¶ added in v0.2.0
func (t *Tree) InsertWithName(method, path string, handler HandlerFunc, name string) error
InsertWithName adds a named route to the tree
func (*Tree) Match ¶ added in v0.2.0
func (t *Tree) Match(method, path string) *MatchResult
Match finds a route for the given method and path
type VelocityRouter ¶
type VelocityRouter = VelocityRouterV2
VelocityRouter is an alias for backward compatibility
type VelocityRouterV2 ¶ added in v0.2.0
type VelocityRouterV2 struct {
// contains filtered or unexported fields
}
VelocityRouterV2 is the tree-based router implementation This replaces gorilla/mux with a custom radix tree
func NewV2 ¶ added in v0.2.0
func NewV2() *VelocityRouterV2
NewV2 creates a new tree-based router instance
func (*VelocityRouterV2) Any ¶ added in v0.2.0
func (r *VelocityRouterV2) Any(path string, handler HandlerFunc) RouteConfig
Any registers a route that matches any HTTP method
func (*VelocityRouterV2) Delete ¶ added in v0.2.0
func (r *VelocityRouterV2) Delete(path string, handler HandlerFunc) RouteConfig
Delete registers a DELETE route
func (*VelocityRouterV2) Get ¶ added in v0.2.0
func (r *VelocityRouterV2) Get(path string, handler HandlerFunc) RouteConfig
Get registers a GET route
func (*VelocityRouterV2) Group ¶ added in v0.2.0
func (r *VelocityRouterV2) Group(prefix string, fn ...func(Router)) Router
Group creates a new router group with a prefix
func (*VelocityRouterV2) Handle ¶ added in v0.2.0
func (r *VelocityRouterV2) Handle() http.Handler
Handle returns the underlying http.Handler
func (*VelocityRouterV2) Head ¶ added in v0.2.0
func (r *VelocityRouterV2) Head(path string, handler HandlerFunc) RouteConfig
Head registers a HEAD route
func (*VelocityRouterV2) Match ¶ added in v0.2.0
func (r *VelocityRouterV2) Match(methods []string, path string, handler HandlerFunc) RouteConfig
Match registers a route for specific HTTP methods
func (*VelocityRouterV2) Options ¶ added in v0.2.0
func (r *VelocityRouterV2) Options(path string, handler HandlerFunc) RouteConfig
Options registers an OPTIONS route
func (*VelocityRouterV2) Patch ¶ added in v0.2.0
func (r *VelocityRouterV2) Patch(path string, handler HandlerFunc) RouteConfig
Patch registers a PATCH route
func (*VelocityRouterV2) Post ¶ added in v0.2.0
func (r *VelocityRouterV2) Post(path string, handler HandlerFunc) RouteConfig
Post registers a POST route
func (*VelocityRouterV2) Prefix ¶ added in v0.2.0
func (r *VelocityRouterV2) Prefix(prefix string)
Prefix sets a prefix for all routes
func (*VelocityRouterV2) Put ¶ added in v0.2.0
func (r *VelocityRouterV2) Put(path string, handler HandlerFunc) RouteConfig
Put registers a PUT route
func (*VelocityRouterV2) Resource ¶ added in v0.2.0
func (r *VelocityRouterV2) Resource(path string, controller interface{}) ResourceRoute
Resource creates RESTful routes for a controller
func (*VelocityRouterV2) RouteURL ¶ added in v0.2.0
RouteURL generates a URL for a named route with the given parameters
func (*VelocityRouterV2) ServeHTTP ¶ added in v0.2.0
func (r *VelocityRouterV2) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP implements http.Handler interface
func (*VelocityRouterV2) SetInstanceEventDispatcher ¶ added in v0.9.11
func (r *VelocityRouterV2) SetInstanceEventDispatcher(fn func(event interface{}) error)
SetInstanceEventDispatcher sets the event dispatcher on this router instance.
func (*VelocityRouterV2) SetServices ¶ added in v0.9.11
func (r *VelocityRouterV2) SetServices(s *app.Services)
SetServices sets the service container that will be injected into every Context.
func (*VelocityRouterV2) Static ¶ added in v0.2.0
func (r *VelocityRouterV2) Static(directory string)
Static serves static files from the specified directory. Note: The underlying http.Dir follows symlinks by default. If this is a concern, ensure the directory does not contain symlinks pointing outside the intended root, or use a custom http.FileSystem that rejects symlinks.
func (*VelocityRouterV2) Use ¶ added in v0.2.0
func (r *VelocityRouterV2) Use(middlewares ...MiddlewareFunc) Router
Use adds middleware to the router