2023-07-09 10:21:32 +00:00
|
|
|
# router
|
|
|
|
|
2023-07-09 17:46:17 +02:00
|
|
|
HTTP router based on radix trees.
|
|
|
|
|
2023-07-10 14:48:28 +02:00
|
|
|
## Usage
|
2023-07-09 21:24:24 +02:00
|
|
|
|
2023-07-10 14:48:28 +02:00
|
|
|
### Static
|
|
|
|
|
|
|
|
We can save any type of data inside the router. Here is an example storing strings for static routes:
|
2023-07-09 21:24:24 +02:00
|
|
|
|
|
|
|
```go
|
|
|
|
router := router.New[string]()
|
|
|
|
|
|
|
|
router.Add("GET", "/hello", "Hello")
|
|
|
|
router.Add("GET", "/world", "World")
|
|
|
|
```
|
|
|
|
|
2023-07-10 14:48:28 +02:00
|
|
|
### Parameters
|
|
|
|
|
|
|
|
The router supports parameters:
|
|
|
|
|
|
|
|
```go
|
|
|
|
router.Add("GET", "/users/:id", "...")
|
|
|
|
router.Add("GET", "/users/:id/comments", "...")
|
|
|
|
```
|
|
|
|
|
|
|
|
### Wildcards
|
|
|
|
|
|
|
|
The router can also fall back to a catch-all route which is useful for file servers:
|
|
|
|
|
|
|
|
```go
|
|
|
|
router.Add("GET", "/images/*path", "...")
|
|
|
|
```
|
|
|
|
|
2023-07-09 17:46:17 +02:00
|
|
|
## Benchmarks
|
|
|
|
|
2023-07-10 14:48:28 +02:00
|
|
|
Requesting every single route in [github.txt](testdata/github.txt) (≈200 requests) in each iteration:
|
2023-07-09 17:46:17 +02:00
|
|
|
|
|
|
|
```
|
2023-07-10 12:02:34 +02:00
|
|
|
BenchmarkLookup-12 33210 36134 ns/op 19488 B/op 337 allocs/op
|
|
|
|
BenchmarkLookupNoAlloc-12 103437 11331 ns/op 0 B/op 0 allocs/op
|
2023-07-10 14:48:28 +02:00
|
|
|
```
|
|
|
|
|
|
|
|
## Embedding
|
|
|
|
|
|
|
|
If you'd like to embed this router into your own framework, please use `LookupNoAlloc` because it's much faster than `Lookup`.
|
|
|
|
|
|
|
|
To build an http server you would of course store request handlers (functions), not strings.
|