router

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2026 License: MIT Imports: 16 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"
)

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 LoadRoutes

func LoadRoutes()

LoadRoutes applies all registered routes to the global router

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 Register

func Register(fn RegistrationFunc)

Register adds a route registration function to be called during initialization

func RegisterWithPrefix

func RegisterWithPrefix(prefix string, fn RegistrationFunc)

RegisterWithPrefix adds a route registration function with a prefix

func ResetGlobalRouter added in v0.2.0

func ResetGlobalRouter()

ResetGlobalRouter resets the global router (for testing)

func Route

func Route(name string, params map[string]string) (string, error)

Route generates a URL for a named route

func SetEventDispatcher added in v0.4.0

func SetEventDispatcher(fn func(event interface{}) error)

SetEventDispatcher sets the function used to dispatch events. This is called by the events package to wire up event dispatching.

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

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

Cookie returns a cookie by name

func (*Context) Error

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

Error sends a JSON error response

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

func (*Context) Header

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

Header returns a request header value

func (*Context) IP

func (c *Context) IP() string

IP returns the client IP address

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

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

QueryDefault returns a query parameter or default value if not set

func (*Context) Redirect

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

Redirect redirects to a URL with the given status code

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

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

Status sends a response with just a status code

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

type Node added in v0.2.0

type Node struct {
	// contains filtered or unexported fields
}

Node represents a node in the radix tree

type RegistrationFunc

type RegistrationFunc func(Router)

RegistrationFunc is a function that registers routes

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
}

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
}

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
}

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 Get

func Get() *VelocityRouterV2

Get returns the global router instance, creating it if necessary

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

func (r *VelocityRouterV2) Static(directory string)

Static serves static files from the specified directory

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