httprouter

A lightweight, high-performance HTTP request router for Go built on a compact radix tree.

Library
Go
vv1.3.0
17,130stars
BSD 3-Clause License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
48/100Fair
Development Activity0
Maintenance20
Community72
Maturity60
Momentum40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
77/100Good
Architecture82
Code Quality78
Innovation68
Learning Curve80

httprouter is a minimal, high-performance HTTP request multiplexer for Go’s net/http package. In contrast to the standard library’s http.ServeMux, it matches requests against explicit, named path patterns rather than longest-prefix rules, so every route is either an exact match or a clean miss, with no ambiguous overlap between patterns.

The router is built around a compact radix (prefix) trie, with one tree maintained per HTTP method. Child nodes are reordered by priority (the number of registered handles beneath them) so the most-used branches are checked first, keeping lookups fast even with a large number of registered routes and minimizing allocations during matching and dispatch.

Beyond raw routing, it ships pragmatic conveniences: automatic trailing-slash redirects, case-insensitive path auto-correction, automatic 405 Method Not Allowed and OPTIONS handling, panic recovery hooks, and adapters for standard http.Handler/http.HandlerFunc so it can be dropped into existing middleware chains. It has become a foundational building block for several other Go web frameworks and API toolkits.

What You Get

  • A Router type that implements http.Handler, so it drops straight into http.ListenAndServe or any existing middleware chain
  • Named path parameters (:name) and catch-all parameters (*name) resolved via the tree and handed to handlers as a Params slice
  • Automatic redirects for missing/extra trailing slashes and case-insensitive path correction (RedirectTrailingSlash, RedirectFixedPath)
  • Built-in 405 Method Not Allowed and automatic OPTIONS response handling, including a configurable Allow header
  • A PanicHandler hook so a handler panic can be turned into a clean error response instead of crashing the process
  • ServeFiles helper for serving static files from a filesystem root off a catch-all route

Common Use Cases

  • Routing layer for a lightweight REST API written directly against net/http, without pulling in a full web framework
  • Foundational router underneath a larger framework or internal toolkit that wants radix-tree performance with its own middleware/handler conventions layered on top
  • Services that care about per-request allocation counts and want routing overhead close to zero, e.g. high-throughput internal APIs or proxies
  • Static file serving alongside API routes via ServeFiles, combined with http.FileServer
  • Multi-domain or multi-tenant servers that build one Router per host and dispatch via a http.Handler switch

Under The Hood

Architecture The router (router.go) is a thin http.Handler wrapper around a map[string]*node — one radix-tree root per HTTP method — with a sync.Pool of Params slices to avoid per-request allocations. ServeHTTP looks up the tree for the request method, walks it via node.getValue (tree.go), and on a miss falls through to trailing-slash redirection, case-insensitive path fixing (findCaseInsensitivePath), 405/OPTIONS handling, and finally a configurable NotFound handler. Route registration (addRoute/insertChild) incrementally splits and merges trie edges, panicking synchronously on conflicting wildcards so a broken route table fails fast at startup rather than misrouting at request time. path.go contributes a small, allocation-conscious CleanPath used only in the path-correction fallback. The design deliberately keeps the hot path (getValue) free of anything not needed for matching — no logging, no middleware chain, no reflection — leaving orchestration entirely to the caller.

Tech Stack The module (go.mod) declares go 1.7 and has zero external dependencies — everything is built on the standard library’s net/http, context, strings, sync, and unicode/utf8. There is no build tooling beyond the Go toolchain itself; CI (.travis.yml) runs go test, go vet, and a gofmt -s diff check across a wide matrix of Go versions (1.7 through a floating master), reflecting the project’s design goal of staying compatible with old and new Go alike.

Code Quality Tests are extensive relative to the codebase size: router_test.go, tree_test.go, and path_test.go together contain roughly 30 Test* functions and a benchmark, covering route registration conflicts, wildcard edge cases, trailing-slash/case-insensitive redirection, and CleanPath behavior against the standard library’s path.Clean for parity. Error handling is panic-based and intentional — invalid route registrations (conflicting wildcards, empty method, malformed catch-all) panic immediately at setup time with descriptive messages, rather than being silently accepted. Naming is short and consistent with idiomatic Go conventions (n, ps, tsr are used throughout the low-level tree code), and go vet/gofmt -s are enforced in CI, though there is no linter beyond that.

What Makes It Unique The standout technical choice is the priority-reordering radix tree: child nodes are kept sorted by how many handles are registered beneath them, so the router’s own structure adapts to the shape of the registered routes to keep the most-traveled branches near the front of each scan. Combined with explicit-only matching (no implicit longest-prefix fallback like http.ServeMux), a pooled Params slice, and a hot path with effectively zero allocations for parameter-free routes, the result is a router whose performance characteristics are unusually well understood and benchmarked (the author’s own go-http-routing-benchmark project), which is a large part of why it became the routing engine embedded inside several later Go web frameworks.

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers

Search