2.3 KiB
2.3 KiB
Router
A high-performance router for Go with support for path parameters and wildcards. Sports an incredibly simple API over the top of a prefix tree data structure. Minimal allocations and, dare we say, 🔥blazingly fast🔥.
Features
- Zero dependencies
- Fast path matching with radix tree structure
- Support for path parameters (
[id]
) and wildcards (*path
) - Up to 15x faster than
http.ServeMux
for dynamic routes - Zero allocations for static routes
Installation
go get git.sharkk.net/Go/Router
Usage
type Handler func(params []string)
router := router.New()
// Static routes
router.Get("/", func(params []string) {
fmt.Println("Root handler")
})
router.Get("/users/all", func(params []string) {
fmt.Println("All users")
})
// Parameter routes
router.Get("/users/[id]", func(params []string) {
userID := params[0]
fmt.Printf("User ID: %s\n", userID)
})
// Nested parameters
router.Get("/users/[id]/posts/[postId]", func(params []string) {
userID := params[0]
postID := params[1]
fmt.Printf("User %s, Post %s\n", userID, postID)
})
// Wildcard routes
router.Get("/files/*path", func(params []string) {
filePath := params[0]
fmt.Printf("File path: %s\n", filePath)
})
// Lookup routes
if handler, params, ok := router.Lookup("GET", "/users/123"); ok {
handler(params)
}
Benchmarks
Benchmark results comparing our router to the standard http.ServeMux
on AMD Ryzen 9 7950X:
cpu: AMD Ryzen 9 7950X 16-Core Processor
BenchmarkComparison/root_path
Router: 2.098 ns/op 0 B/op 0 allocs/op
ServeMux: 32.010 ns/op 0 B/op 0 allocs/op
BenchmarkComparison/static_path
Router: 16.050 ns/op 0 B/op 0 allocs/op
ServeMux: 67.980 ns/op 0 B/op 0 allocs/op
BenchmarkComparison/dynamic_path
Router: 39.170 ns/op 16 B/op 1 allocs/op
ServeMux: 174.000 ns/op 48 B/op 3 allocs/op
BenchmarkComparison/not_found
Router: 10.580 ns/op 0 B/op 0 allocs/op
ServeMux: 178.100 ns/op 56 B/op 3 allocs/op
Key Performance Points:
- Root path lookups are 15x faster
- Static paths are 4x faster with zero allocations
- Dynamic paths are 4.4x faster with fewer allocations
- Not found paths are 16.8x faster with zero allocations
License
Licensed under MIT. Take a look!