mux

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2026 License: MIT Imports: 7 Imported by: 0

README

mux

Lightweight, dependency-free HTTP router

Quick example:

package main

import (
  "net/http"
  "github.com/GreedyKomodoDragon/mux"
)

func main() {
  r := mux.New()
  r.Get("/users/{id}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    id := mux.Param(r, "id")
    w.Write([]byte(id))
  }))
  http.ListenAndServe(":8080", r)
}

Features:

  • Named params: {name}
  • Explicit wildcard: {*path} (must be last segment)
  • Subrouter groups: Group(prefix, func(sub *Router) { ... })
  • Per-router middleware with Use(...)
  • Prefix middleware with UsePrefix(prefix, ...)
  • Convenience methods: Get/Post/Put/Patch/Delete
  • Trailing slash behaviour mirrors net/http/ServeMux (redirects to add/remove trailing slash when a nearby route exists)

How it works:

  • Route registration compiles a pattern into typed path segments (static, param, wildcard) and inserts it into an internal trie.
  • Request matching walks the trie by path segment with precedence: static -> param -> wildcard.
  • Handlers are pre-wrapped at registration time (not per request), so serving stays fast.
  • URL params are stored on request context only when needed, and read with Param(r, name) / Params(r).
  • Internal trie details are documented in mux/TRIE.md.

Pattern rules:

  • {name} captures one segment.
  • {*name} captures the remaining path and must be the final segment.
  • Duplicate param names inside one route pattern are invalid and panic at registration.
  • Empty segments (for example /a//b) are invalid and panic at registration.

Middleware model:

  • UsePrefix(prefix, ...) applies middleware to matching routes by path prefix.
  • Prefix matching is segment-aware: /v2 matches /v2/users, not /v21/users.
  • Literal prefix segments only match static route segments (not param segments).
  • Wildcard route segments ({*name}) can satisfy deeper prefix matches.
  • Middleware execution order is: UsePrefix(...) -> Use(...) -> handler.
  • UsePrefix(...) rewraps existing matching routes immediately and also affects future matching routes.
  • Use(...) is registration-time only; adding it later does not rewrap existing routes.

Groups:

  • Group(prefix, fn) creates a subrouter with inherited Use(...) middleware and combined prefix.
  • Routes registered in a group are inserted into the root router trie with the group prefix applied.
  • UsePrefix(...) called inside a group is interpreted relative to that group prefix.

HTTP behavior:

  • If path matches but method does not, router returns 405 and sets Allow.
  • Not found routes use the configured NotFound handler (default http.NotFound).
  • Trailing slash redirect semantics follow net/http/ServeMux behavior.

Notes:

  • Register routes at startup; the router is optimized for serving and does not expect frequent runtime registration.
  • Duplicate registrations (same method+pattern) are allowed; the last registration wins.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MuxRoutePattern

func MuxRoutePattern(r *http.Request) string

MuxRoutePattern returns the matched route pattern from the request's context.

func Param

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

Param returns the named URL parameter from the request's context.

func Params

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

Params returns a copy of all URL parameters present on the request.

Types

type Router

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

Router is a lightweight HTTP router with named params, explicit wildcard, subrouter groups, and per-router middleware. It's intentionally small and dependency-free so it can be published later as a standalone module.

func New

func New() *Router

New returns a new Router.

func (*Router) Delete

func (r *Router) Delete(pattern string, h http.Handler) error

func (*Router) Get

func (r *Router) Get(pattern string, h http.Handler) error

Convenience methods.

func (*Router) Group

func (r *Router) Group(prefix string, fn func(sub *Router))

Group creates a subrouter with the provided prefix. The subrouter inherits middleware from the parent. Registration inside fn will register routes on the parent router but with the group's prefix applied.

func (*Router) Handle

func (r *Router) Handle(method, pattern string, h http.Handler) error

Handle registers a handler for the given method and pattern. Pattern syntax: segments separated by '/'. Named param: {name}. Wildcard: {*name} (must be last).

func (*Router) HandleFunc

func (r *Router) HandleFunc(method, pattern string, hf func(http.ResponseWriter, *http.Request)) error

HandleFunc convenience wrapper.

func (*Router) HandleFuncMethods

func (r *Router) HandleFuncMethods(methods []string, pattern string, hf func(http.ResponseWriter, *http.Request)) error

HandleFuncMethods convenience wrapper for HandleMethods.

func (*Router) HandleMethods

func (r *Router) HandleMethods(methods []string, pattern string, h http.Handler) error

HandleMethods registers the same handler for multiple HTTP methods.

func (*Router) MethodNotAllowed

func (r *Router) MethodNotAllowed(h http.Handler)

MethodNotAllowed sets a custom 405 handler.

func (*Router) NotFound

func (r *Router) NotFound(h http.Handler)

NotFound sets a custom NotFound handler.

func (*Router) Patch

func (r *Router) Patch(pattern string, h http.Handler) error

func (*Router) Post

func (r *Router) Post(pattern string, h http.Handler) error

func (*Router) Put

func (r *Router) Put(pattern string, h http.Handler) error

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements http.Handler.

func (*Router) Use

func (r *Router) Use(mw ...func(http.Handler) http.Handler)

Use appends middleware to this router. Middleware will be applied in the order they are provided when wrapping handlers at registration time.

func (*Router) UsePrefix

func (r *Router) UsePrefix(prefix string, mw ...func(http.Handler) http.Handler)

UsePrefix registers middleware that applies to all routes whose registered pattern matches the provided prefix by path segments. The prefix is normalized and matched in a segment-aware manner. UsePrefix applies the middleware to existing routes immediately and to future registrations.

Jump to

Keyboard shortcuts

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