- Go 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
Static routes no longer allocate, routes with parameters allocate once,
and sux is now faster than http.ServeMux in 11 of the 12 comparison
benchmarks.
- Match by walking the request path in place. The method's tree is
picked with a switch, and child nodes are found by scanning their
first bytes, switching to a map above 16 static children.
- Build middleware chains when routes and middleware are registered
instead of on every request.
- Carry the parameters in one allocation that holds the context, the
parameter values and the request copy, instead of pooled slices and
context.WithValue.
Bugs fixed:
- Middleware added with Use before the routes were registered ran
twice per request.
- Sibling groups could run each other's middleware through a shared
slice.
- A static segment shadowed a parameter even when the rest of the path
didn't match: with /users/admin/settings registered, /users/admin
returned 404 instead of matching /users/:id. Matching now backtracks.
- Routes with differently named parameters at the same position
(/u/:id and /u/:name/profile) all used the first route's names.
- Wildcard values were garbled on paths containing "//".
- Registering a path without a leading slash dropped its first
character: "users" registered "/sers".
Middleware functions are now called once, when the chain is built,
rather than once per request. Middleware that needs fresh state for
each request has to create it inside the handler it returns.
compare_test.go adds benchmarks against http.ServeMux. routing_test.go
adds tests for the fixes, the allocation counts and the lifetime of
parameters. BenchmarkLargeRouter registered string(rune(i)) paths and
so only measured a 404; it now registers numbers.
BenchmarkCompare (ns/op), Go 1.27.4, Intel Xeon E3-1275 v5:
v1.2.0 now ServeMux
StaticRoot 266 10.6 64.9
StaticDeep 359 53.0 179
Param1 413 179 169
Param3 530 245 441
Wildcard 426 177 484
Middleware2 366 15.9 70.5
NotFound 499 264 837
MethodNotAllowed 210 25.4 993
Large1000Static 330 40.4 147
GitHubStatic 326 41.5 143
GitHubParam 465 217 356
GitHubAll 113900 49300 90900
geomean 594 119 400
|
||
| .gitignore | ||
| benchmark_test.go | ||
| compare_test.go | ||
| go.mod | ||
| LICENSE | ||
| performance_test.go | ||
| README.md | ||
| routing_test.go | ||
| sux.go | ||
| sux_test.go | ||
sux
An allocation-conscious, middleware-capable HTTP router for Go with support for static routes, parameters (:id), wildcards (*path), route groups, and configurable 404/405 handling.
Installation
go get code.icod.de/dalu/sux
Quick start
package main
import (
"net/http"
"code.icod.de/dalu/sux"
)
func main() {
r := sux.New()
r.GET("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
})
r.GET("/users/:id", func(w http.ResponseWriter, r *http.Request) {
params := sux.ParamsFromContext(r)
w.Write([]byte("user " + params.Get("id")))
})
http.ListenAndServe(":8080", r)
}
Middleware
Middleware wraps handlers and can be applied globally or per route group. Global middleware (Use on the router) applies to all routes and runs first, followed by the middleware of the route's groups; within each, middleware runs in the order it was added.
logger := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// log request here
next.ServeHTTP(w, r)
})
}
r := sux.New()
r.Use(logger) // global
r.GET("/ping", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("pong"))
})
Route groups
Groups share a prefix and middleware.
api := r.Group("/api", func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-API-Version", "v1")
next.ServeHTTP(w, r)
})
})
api.GET("/users", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("users"))
})
Parameters and wildcards
r.GET("/posts/:postId", func(w http.ResponseWriter, r *http.Request) {
p := sux.ParamsFromContext(r)
w.Write([]byte(p.Get("postId")))
})
r.GET("/files/*path", func(w http.ResponseWriter, r *http.Request) {
p := sux.ParamsFromContext(r)
w.Write([]byte("file: " + p.Get("path")))
})
At each segment, a static segment takes precedence over a parameter, and a parameter over a wildcard. If the more specific route doesn't match the rest of the path, the next one is tried: with /users/admin/settings and /users/:id registered, /users/admin matches /users/:id.
404/405 handlers
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "custom 404", http.StatusNotFound)
})
r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "custom 405", http.StatusMethodNotAllowed)
})
// Disable cross-method probing if you prefer 404s instead of 405 checks
r.EnableMethodNotAllowedCheck(false)
Performance notes
- Static routes are served without allocating. A route with parameters costs a single allocation per request, holding the parameters and the request copy that carries them.
- Each request gets its own parameters, so they remain valid even after handlers return (important for async users of the context).
- Middleware chains are built when routes and middleware are registered, not per request.
Benchmarks
sux and http.ServeMux serving the same routes, from compare_test.go. Responses go to a no-op ResponseWriter, so the numbers measure routing, and the handlers in the parameter and wildcard benchmarks read their parameters. Allocations are shown with the bytes allocated in parentheses.
| Benchmark | sux | http.ServeMux | sux allocs | ServeMux allocs |
|---|---|---|---|---|
Static / |
10.6 ns | 64.9 ns | 0 | 0 |
Static /api/v1/users/list |
53.0 ns | 179 ns | 0 | 0 |
1 parameter /users/:id |
179 ns | 169 ns | 1 (384 B) | 1 (16 B) |
| 3 parameters | 245 ns | 441 ns | 1 (416 B) | 3 (112 B) |
Wildcard /files/*path |
177 ns | 484 ns | 1 (384 B) | 5 (96 B) |
Static / with 2 middleware |
15.9 ns | 70.5 ns | 0 | 0 |
| Not found (404) | 264 ns | 837 ns | 3 (48 B) | 12 (208 B) |
| Method not allowed (405) | 25.4 ns | 993 ns | 0 | 14 (272 B) |
| Static, among 1,000 routes | 40.4 ns | 147 ns | 0 | 0 |
| GitHub API: static route | 41.5 ns | 143 ns | 0 | 0 |
| GitHub API: route with 2 parameters | 217 ns | 356 ns | 1 (416 B) | 2 (48 B) |
| GitHub API: all 228 routes, one request each | 49.3 µs | 90.9 µs | 189 (75 KiB) | 424 (13 KiB) |
Medians of 8 runs with Go 1.27.4 on linux/amd64 and an Intel Xeon E3-1275 v5 @ 3.60GHz. The GitHub API benchmarks register the 228 routes of the GitHub v3 API.
http.ServeMux does work that sux doesn't, which shows most in the 404 and 405 rows: it cleans paths and redirects to the cleaned path, matches host patterns, falls back from HEAD to GET, and sets the Allow header on 405 responses. It's slightly faster with a single parameter because it stores path values in the request itself, while sux copies the request to carry the parameters in its context.
To run the comparison yourself (benchstat is golang.org/x/perf/cmd/benchstat):
go test -run '^$' -bench Compare -benchmem -count 8 > bench.txt
benchstat -col /router bench.txt
Testing
go test ./...
Benchmarks:
go test -bench . -benchmem