|
|
2 hours ago | |
|---|---|---|
| .gitignore | 2 hours ago | |
| README.md | 2 hours ago | |
| constructor.go | 2 hours ago | |
| errors.go | 2 hours ago | |
| go.mod | 2 hours ago | |
| route.go | 2 hours ago |
A golang library for HTTP routing. Once initialized, router is immutable and thread-safe.
First, import the router:
import "go.deck17.com/router"
Then make a router instance:
urlRouter, err := router.NewRouter(
map[string]string{
"page.index": "/",
"page.about": "/about",
"page.edit": "/object/{name}/edit",
},
)
To initialize endpoints with http library:
pattern := func(key string) string {
path, err := urlRouter.Pattern(key)
if err != nil {
panic(err)
}
return path
}
http.HandlerFunc(pattern("page.index"), handleIndex)
http.HandlerFunc(pattern("page.edit"), handleEdit)
To use the handler inside Go code:
route := func(key string, args ...any) string {
path, err := urlRouter.Route(key, args...)
if err != nil {
panic(err)
}
return path
}
http.Redirect(w, route("page.edit", "object-1"), http.StatusSeeOther)
It is also possible to use the router inside templates. For this to work, it is necessary to implement a custom template function either similar to "route" or just as a wrapper to "route".