Documentation
¶
Overview ¶
Package match provides a minimal, high-performance generic path router.
A Router maps slash-separated route patterns to caller-provided values, then returns the matched value and any captured parameters. It is intentionally narrower than an HTTP framework: it does not know about methods, middleware, redirects, request objects, URL decoding, or path cleaning. That makes it useful anywhere a path-like string needs to resolve to typed application data, such as HTTP handler lookup, command dispatch, API route tables, asset paths, virtual filesystems, or nested routers.
The zero value of Router is ready to use. The stored value can be any Go type, and after routes are registered a Router may be shared by multiple goroutines for matching.
Quick Start ¶
var router match.Router[string]
router.Insert("/posts/{year}/{slug}", "post")
router.Insert("/static/{*path}", "asset")
value, params, ok := router.Match("/posts/2026/route-grammar")
_ = value // "post"
_ = params.Get("year") // "2026"
_ = params.Get("slug") // "route-grammar"
_ = ok // true
Path Semantics ¶
Routes and paths are plain strings with / as the segment separator. match does not normalize either side before matching: absolute and relative paths are distinct, empty segments are significant, trailing slashes are significant, escaped URL bytes are not decoded, and . or .. segments are not cleaned. If you are matching net/http requests, apply whatever URL or path normalization your application wants before calling Match.
The github.com/ryanfowler/match/dns sub-package provides a DNS hostname matcher with the same generic value and Params model for dot-separated, case-insensitive hostname labels.
Route Grammar ¶
Routes are slash-separated patterns made from literal text, named parameters, and catch-all parameters. A route does not have to start with /.
Literal text matches itself. A named parameter is written as {name} and captures one non-empty path segment. A parameter may have literal text before or after it in the same segment, such as /files/{name}.json or /user_{id}. Each path segment may contain at most one parameter.
A catch-all parameter is written as {*name}. It captures the non-empty remainder of the path, including any slashes, and must appear at the end of the route. A catch-all may have a literal prefix in its final segment, such as /static/prefix-{*path}; the captured value starts after that prefix.
Literal braces are escaped by doubling them: {{ matches a literal { and }} matches a literal }. Escaped braces may also appear inside parameter names.
Parameter names must be non-empty. Names cannot contain /, and * is only valid as the first character of a catch-all parameter. Parameters and catch-all parameters capture non-empty text.
API Overview ¶
Insert registers trusted route definitions and panics on invalid, duplicate, or ambiguous routes. TryInsert registers routes from configuration, plugins, or other input that should produce a regular error.
Match looks up an exact path. MatchInto is the same operation using a caller-provided *Params value as reusable storage. MatchPrefix and MatchPrefixInto return the best whole-segment route prefix plus the remaining path, which is useful for mounts and nested dispatch. Rest is / when a prefix match consumes the full path. Clone returns an independent copy of a Router's routing state for cases where a route table needs to be extended without mutating the original.
Matching Behavior and Conflicts ¶
When more than one route could match, match chooses the most specific route: exact literal segments beat parameter segments, parameter segments with more literal text are tried first, and catch-all routes are considered last. Prefix matching uses the same route grammar, but chooses the route that consumes the most path.
TryInsert returns an error for invalid, duplicate, or ambiguous routes. Invalid route syntax is reported with sentinel errors such as ErrInvalidParam, ErrInvalidParamSegment, and ErrInvalidCatchAll. Duplicate and ambiguous routes return *ConflictError. For example, /x/{id}/bar conflicts with /x/{name}/bar because both match the same set of paths. Insert panics on the same errors returned by TryInsert.
Params ¶
Matching returns parameters in route order. Params is an opaque value type; use Len and At to iterate without allocation, Get or TryGet to look up named parameters, Seq for range-over-function iteration, Merge to concatenate parameter sets, and AppendTo or All when a []Param snapshot is needed.
Internals ¶
Routes are parsed once during insertion. The parser turns a route string into tokens, splits those tokens into segment patterns, records capture names in route order, and builds a normalized route shape used to detect duplicates even when parameter names differ.
The matcher is a segment trie. Each node can have static edges, parameter edges, catch-all edges, and an optional route value. Static edges are tried first. Parameter edges are sorted by specificity, with more literal text before less literal text, so /user-{id} is preferred over /{id} for "/user-42". Catch-all edges are checked after static and parameter edges. Nodes with many static children add a small lookup map while preserving compact storage for small route tables.
TryInsert also maintains a conflict index. Dynamic routes are grouped by segment count and first definitely-static segment, with separate tracking for catch-all routes. This catches ambiguous definitions before they can make match results depend on insertion order.
Parameters are collected after the winning route is selected, using the canonical route entry's capture names. Params stores up to four captures inline and grows to a slice only when needed. MatchInto and MatchPrefixInto reset and reuse a caller-provided *Params value, which avoids heap allocation for common hot-path routing loops.
Callers that insert routes while other goroutines use the router must synchronize access.
Index ¶
- Variables
- type ConflictError
- type Param
- type Params
- func (p Params) All() []Param
- func (p *Params) Append(key, val string)
- func (p Params) AppendTo(dst []Param) []Param
- func (p Params) At(i int) Param
- func (p Params) Get(key string) string
- func (p *Params) Grow(capacity int)
- func (p Params) Len() int
- func (p *Params) Reset()
- func (p Params) Seq() iter.Seq2[string, string]
- func (p Params) TryGet(key string) (string, bool)
- type PrefixMatch
- type Router
- func (r *Router[T]) Clone() Router[T]
- func (r *Router[T]) Insert(route string, value T)
- func (r *Router[T]) Match(path string) (T, Params, bool)
- func (r *Router[T]) MatchInto(path string, params *Params) (T, bool)
- func (r *Router[T]) MatchPrefix(path string) (PrefixMatch[T], bool)
- func (r *Router[T]) MatchPrefixInto(path string, params *Params) (PrefixMatch[T], bool)
- func (r *Router[T]) TryInsert(route string, value T) error
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidParamSegment reports a route segment that contains more than // one parameter. ErrInvalidParamSegment = errors.New("only one parameter is allowed per path segment") // ErrInvalidParam reports malformed parameter syntax or an invalid // parameter name. ErrInvalidParam = errors.New("parameters must be registered with a valid name") // ErrInvalidCatchAll reports a catch-all parameter that is not the final // token in its route. ErrInvalidCatchAll = errors.New("catch-all parameters are only allowed at the end of a route") )
Functions ¶
This section is empty.
Types ¶
type ConflictError ¶
type ConflictError struct {
// Route is the route that failed to insert.
Route string
// With is the previously registered route that conflicts with Route.
With string
}
ConflictError reports a route that cannot be inserted because it overlaps an already registered route.
func (*ConflictError) Error ¶
func (e *ConflictError) Error() string
Error returns a human-readable description of the route conflict.
type Param ¶
type Param struct {
// Key is the parameter name from the matched route.
Key string
// Val is the substring captured from the matched path.
Val string
}
Param is one captured route parameter.
type Params ¶
type Params struct {
// contains filtered or unexported fields
}
Params stores captured route parameters in route order.
Params is an opaque value type. Use Len and At to inspect captures without allocation, Get or TryGet to look up a named capture, and AppendTo or All when a []Param snapshot is needed. Up to four captures are stored inline.
func Merge ¶
Merge returns a Params value containing a followed by b.
Parameter keys are not deduplicated; when the same key appears in both inputs, the returned Params contains both captures in order.
func NewParams ¶
NewParams returns an empty Params value with room for capacity parameters.
It is most useful with Router.MatchInto when callers want to reuse storage across matches. Capacity values of four or less use the inline storage built into Params.
func (Params) AppendTo ¶
AppendTo appends the captured parameters to dst and returns the extended slice.
func (Params) At ¶
At returns the parameter at index i.
It panics if i is outside the range [0, Len()).
func (*Params) Grow ¶ added in v0.3.0
Grow ensures p has enough reusable storage for capacity parameters.
Capacity values of four or less use the inline storage built into Params.
func (*Params) Reset ¶ added in v0.3.0
func (p *Params) Reset()
Reset clears p while preserving reusable heap storage.
type PrefixMatch ¶
PrefixMatch contains the result of a successful prefix match.
Rest is the remaining path after the matched prefix. It is always "/" when the match consumes the full path.
type Router ¶
type Router[T any] struct { // contains filtered or unexported fields }
Router maps path patterns to caller-provided values.
The zero value is ready to use. After routes are registered, a Router may be used by multiple goroutines for matching. Callers that insert routes while other goroutines use the router must synchronize access.
func (*Router[T]) Clone ¶ added in v0.2.0
Clone returns a Router containing a deep copy of r's routing state.
Future inserts into the returned Router do not mutate r. Stored values are copied by assignment.
func (*Router[T]) Insert ¶
Insert registers route with value.
It panics with the same errors returned by TryInsert when route is invalid or conflicts with an existing route.
func (*Router[T]) Match ¶
Match returns the value and parameters for path.
The boolean result is false when no registered route matches; in that case the value is the zero value of T and the returned Params is empty.
func (*Router[T]) MatchInto ¶
MatchInto returns the value for path using params as parameter storage.
Params is reset before matching and must be non-nil. Use NewParams to create a reusable Params buffer large enough for the expected number of captures.
func (*Router[T]) MatchPrefix ¶
func (r *Router[T]) MatchPrefix(path string) (PrefixMatch[T], bool)
MatchPrefix returns the value, parameters, and remaining path for the best registered route that matches the front of path.
The boolean result is false when no registered route matches a whole-segment prefix of path. When multiple routes match, the route that consumes the most path wins. A route registered as "/" matches the root prefix of any absolute path.
func (*Router[T]) MatchPrefixInto ¶
func (r *Router[T]) MatchPrefixInto(path string, params *Params) (PrefixMatch[T], bool)
MatchPrefixInto is like MatchPrefix, but uses params as parameter storage.
Params is reset before matching and must be non-nil. Use NewParams to create a reusable Params buffer large enough for the expected number of captures.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package dns provides a minimal, high-performance generic matcher for DNS hostnames.
|
Package dns provides a minimal, high-performance generic matcher for DNS hostnames. |
|
internal
|
|