router

package
v0.9.12 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2026 License: MIT Imports: 31 Imported by: 0

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

View Source
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"
)
View Source
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
	StatusUnauthorized                 = http.StatusUnauthorized
	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
	StatusUnavailableForLegalReasons   = http.StatusUnavailableForLegalReasons

	// 5xx Server Errors
	StatusInternalServerError           = http.StatusInternalServerError
	StatusNotImplemented                = http.StatusNotImplemented
	StatusBadGateway                    = http.StatusBadGateway
	StatusServiceUnavailable            = http.StatusServiceUnavailable
	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.

View Source
const DefaultMaxBodySize int64 = 10 * 1024 * 1024

DefaultMaxBodySize is the default maximum request body size (10MB).

Variables

This section is empty.

Functions

func BuildPath added in v0.2.0

func BuildPath(segments []Segment, params map[string]string) (string, error)

BuildPath builds a URL path from segments and parameter values

func CurrentRoute

func CurrentRoute(r *http.Request) string

CurrentRoute returns the current route name if it exists

func GetParams added in v0.2.0

func GetParams(r *http.Request) map[string]string

GetParams retrieves route parameters from the request context

func GetRequestID added in v0.4.0

func GetRequestID(r *http.Request) string

GetRequestID extracts the request ID from the request context

func GetRouteName added in v0.2.0

func GetRouteName(r *http.Request) string

GetRouteName retrieves the current route name from the request context

func GetRoutePattern added in v0.4.0

func GetRoutePattern(r *http.Request) string

GetRoutePattern extracts the matched route pattern from the request context

func Param

func Param(r *http.Request, name string) string

Param extracts a route parameter from the request

func Params

func Params(r *http.Request) map[string]string

Params returns all route parameters from the request

func SetParams added in v0.2.0

func SetParams(r *http.Request, params map[string]string) *http.Request

SetParams stores route parameters in the request context Returns a new request with the parameters stored

func SetRouteName added in v0.2.0

func SetRouteName(r *http.Request, name string) *http.Request

SetRouteName stores the current route name in the request context

func Wrap

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

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

func (*Context) Auth added in v0.9.11

func (c *Context) Auth() any

Auth returns the auth manager (*auth.Manager). Requires type assertion.

func (*Context) BadRequest

func (c *Context) BadRequest(message ...string) error

BadRequest sends a 400 error response

func (*Context) Bind

func (c *Context) Bind(v interface{}) error

Bind parses the request body as JSON into the given struct

func (*Context) CSRF added in v0.9.11

func (c *Context) CSRF() any

CSRF returns the CSRF protection instance (*csrf.CSRF). Requires type assertion.

func (*Context) Cache added in v0.9.11

func (c *Context) Cache() *cache.Manager

Cache returns the cache manager.

func (*Context) Cookie

func (c *Context) Cookie(name string) (*http.Cookie, error)

Cookie returns a cookie by name

func (*Context) Crypto added in v0.9.11

func (c *Context) Crypto() crypto.Encryptor

Crypto returns the encryptor.

func (*Context) DB added in v0.9.11

func (c *Context) DB() *orm.Manager

DB returns the ORM manager.

func (*Context) Error

func (c *Context) Error(status int, message string) error

Error sends a JSON error response

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) Forbidden

func (c *Context) Forbidden(message ...string) error

Forbidden sends a 403 error response

func (*Context) Get

func (c *Context) Get(key string) interface{}

Get retrieves a value from the context

func (*Context) GetString

func (c *Context) GetString(key string) string

GetString retrieves a string value from the context

func (*Context) HTML

func (c *Context) HTML(status int, html string) error

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) Header

func (c *Context) Header(name string) string

Header returns a request header value

func (*Context) HeaderInt64 added in v0.8.0

func (c *Context) HeaderInt64(name string, defaultValue ...int64) int64

HeaderInt64 returns a header value as int64, with optional default

func (*Context) IP

func (c *Context) IP() string

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) IsAjax

func (c *Context) IsAjax() bool

IsAjax returns true if the request is an AJAX request

func (*Context) JSON

func (c *Context) JSON(status int, data interface{}) error

JSON sends a JSON response with the given status code

func (*Context) Log added in v0.9.11

func (c *Context) Log() log.Logger

Log returns the logger.

func (*Context) Mail added in v0.9.11

func (c *Context) Mail() mail.Mailer

Mail returns the mailer.

func (*Context) Method

func (c *Context) Method() string

Method returns the HTTP method

func (*Context) NoContent

func (c *Context) NoContent() error

NoContent sends a 204 No Content response

func (*Context) NotFound

func (c *Context) NotFound(message ...string) error

NotFound sends a 404 error response

func (*Context) Param

func (c *Context) Param(name string) string

Param returns a route parameter by name

func (*Context) ParamInt added in v0.8.0

func (c *Context) ParamInt(name string) (int, error)

ParamInt returns a route parameter as int

func (*Context) ParamInt64 added in v0.8.0

func (c *Context) ParamInt64(name string) (int64, error)

ParamInt64 returns a route parameter as int64

func (*Context) Path

func (c *Context) Path() string

Path returns the request path

func (*Context) Query

func (c *Context) Query(name string) string

Query returns a query parameter by name

func (*Context) QueryBool added in v0.8.0

func (c *Context) QueryBool(name string) bool

QueryBool returns a query parameter as bool (handles "true", "1", "yes")

func (*Context) QueryDefault

func (c *Context) QueryDefault(name, defaultValue string) string

QueryDefault returns a query parameter or default value if not set

func (*Context) QueryFloat64 added in v0.8.0

func (c *Context) QueryFloat64(name string, defaultValue ...float64) float64

QueryFloat64 returns a query parameter as float64, with optional default

func (*Context) QueryInt added in v0.8.0

func (c *Context) QueryInt(name string, defaultValue ...int) int

QueryInt returns a query parameter as int, with optional default

func (*Context) QueryInt64 added in v0.8.0

func (c *Context) QueryInt64(name string, defaultValue ...int64) int64

QueryInt64 returns a query parameter as int64, with optional default

func (*Context) Queue added in v0.9.11

func (c *Context) Queue() queue.Driver

Queue returns the queue driver.

func (*Context) Redirect

func (c *Context) Redirect(status int, rawURL string) error

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) Scheduler added in v0.9.11

func (c *Context) Scheduler() *scheduler.Scheduler

Scheduler returns the task scheduler.

func (*Context) Services added in v0.9.11

func (c *Context) Services() *app.Services

Services returns the service container.

func (*Context) Set

func (c *Context) Set(key string, value interface{})

Set stores a value in the context

func (*Context) SetCookie

func (c *Context) SetCookie(cookie *http.Cookie)

SetCookie sets a cookie on the response

func (*Context) SetHeader

func (c *Context) SetHeader(name, value string)

SetHeader sets a response header

func (*Context) SetServices added in v0.9.11

func (c *Context) SetServices(s *app.Services)

SetServices sets the service container on this context.

func (*Context) Status

func (c *Context) Status(status int) error

Status sends a response with just a status code

func (*Context) Storage added in v0.9.11

func (c *Context) Storage() *storage.Manager

Storage returns the storage manager.

func (*Context) String

func (c *Context) String(status int, text string) error

String sends a plain text response

func (*Context) Unauthorized

func (c *Context) Unauthorized(message ...string) error

Unauthorized sends a 401 error response

func (*Context) Validator added in v0.9.11

func (c *Context) Validator() validation.Validator

Validator returns the validator.

func (*Context) View added in v0.9.11

func (c *Context) View() any

View returns the view engine (*view.Engine). Requires type assertion.

func (*Context) WantsJSON

func (c *Context) WantsJSON() bool

WantsJSON returns true if the client expects a JSON response

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

Error represents an HTTP error response

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

type HandlerFunc func(c *Context) error

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

type ResourceConfig struct {
	HttpMethod string
	Action     string
	PathSuffix string
	HasParam   bool
}

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

func ParseSegments(path string) ([]Segment, error)

ParseSegments parses a path pattern into segments Supports: /static, /{param}, /{param:regex}, /{param:.*}

func (*Segment) Match added in v0.2.0

func (s *Segment) Match(value string) bool

Match checks if the given value matches this segment

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 NewTree added in v0.2.0

func NewTree() *Tree

NewTree creates a new routing tree

func (*Tree) AllowedMethods added in v0.2.0

func (t *Tree) AllowedMethods(path string) []string

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 New

func New() *VelocityRouterV2

New creates a new router instance

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

func (r *VelocityRouterV2) RouteURL(name string, params map[string]string) (string, error)

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

Jump to

Keyboard shortcuts

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