Improved code quality
This commit is contained in:
parent
4c4775c071
commit
ad033d4315
10 changed files with 131 additions and 120 deletions
61
README.md
61
README.md
|
@ -2,6 +2,12 @@
|
|||
|
||||
HTTP router based on radix trees.
|
||||
|
||||
## Features
|
||||
|
||||
- Efficient lookup
|
||||
- Generic data structure
|
||||
- Zero dependencies (excluding tests)
|
||||
|
||||
## Installation
|
||||
|
||||
```shell
|
||||
|
@ -10,45 +16,52 @@ go get git.akyoto.dev/go/router
|
|||
|
||||
## Usage
|
||||
|
||||
### Static
|
||||
|
||||
We can save any type of data inside the router. Here is an example storing strings for static routes:
|
||||
|
||||
```go
|
||||
router := router.New[string]()
|
||||
|
||||
router.Add("GET", "/hello", "Hello")
|
||||
router.Add("GET", "/world", "World")
|
||||
```
|
||||
// Static routes
|
||||
router.Add("GET", "/hello", "...")
|
||||
router.Add("GET", "/world", "...")
|
||||
|
||||
### Parameters
|
||||
|
||||
The router supports parameters:
|
||||
|
||||
```go
|
||||
// Parameter routes
|
||||
router.Add("GET", "/users/:id", "...")
|
||||
router.Add("GET", "/users/:id/comments", "...")
|
||||
|
||||
// Wildcard routes
|
||||
router.Add("GET", "/images/*path", "...")
|
||||
|
||||
// Simple lookup
|
||||
data, params := router.Lookup("GET", "/users/42")
|
||||
fmt.Println(data, params)
|
||||
|
||||
// Efficient lookup
|
||||
data := router.LookupNoAlloc("GET", "/users/42", func(key string, value string) {
|
||||
fmt.Println(key, value)
|
||||
})
|
||||
```
|
||||
|
||||
### Wildcards
|
||||
## Tests
|
||||
|
||||
The router can also fall back to a catch-all route which is useful for file servers:
|
||||
|
||||
```go
|
||||
router.Add("GET", "/images/*path", "...")
|
||||
```
|
||||
PASS: TestStatic
|
||||
PASS: TestParameter
|
||||
PASS: TestWildcard
|
||||
PASS: TestMethods
|
||||
PASS: TestGitHub
|
||||
coverage: 76.9% of statements
|
||||
```
|
||||
|
||||
## Benchmarks
|
||||
|
||||
Requesting every single route in [github.txt](testdata/github.txt) (≈200 requests) in each iteration:
|
||||
|
||||
```
|
||||
BenchmarkLookup-12 33210 36134 ns/op 19488 B/op 337 allocs/op
|
||||
BenchmarkLookupNoAlloc-12 103437 11331 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkLookup-12 6965749 171.2 ns/op 96 B/op 2 allocs/op
|
||||
BenchmarkLookupNoAlloc-12 24243546 48.5 ns/op 0 B/op 0 allocs/op
|
||||
```
|
||||
|
||||
## Embedding
|
||||
## License
|
||||
|
||||
If you'd like to embed this router into your own framework, please use `LookupNoAlloc` because it's much faster than `Lookup`.
|
||||
Please see the [license documentation](https://akyoto.dev/license).
|
||||
|
||||
To build an http server you would of course store request handlers (functions), not strings.
|
||||
## Copyright
|
||||
|
||||
© 2023 Eduard Urbach
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue