No Description

Bozhin Zafirov a946535ce4 Router module, initial import. 2 hours ago
.gitignore a946535ce4 Router module, initial import. 2 hours ago
README.md a946535ce4 Router module, initial import. 2 hours ago
constructor.go a946535ce4 Router module, initial import. 2 hours ago
errors.go a946535ce4 Router module, initial import. 2 hours ago
go.mod a946535ce4 Router module, initial import. 2 hours ago
route.go a946535ce4 Router module, initial import. 2 hours ago

README.md

router

A golang library for HTTP routing. Once initialized, router is immutable and thread-safe.

Usage:

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".