joist/internal/routing/router.go
2025-09-06 23:53:58 -04:00

63 lines
1.3 KiB
Go

package routing
import (
"context"
"net/http"
"regexp"
"strings"
"time"
"github.com/go-chi/chi/v5"
)
type RouteCacher interface {
Add(string, string) error
AddRouteInfo(RouteInfo) error
GetPath(string) (string, error)
GetRouteInfo(string) (RouteInfo, error)
All() (map[string]string, error)
}
type Router struct {
*chi.Mux
cache RouteCacher
cacheTTL time.Duration
}
func (ro *Router) WithRouteInfo(ri RouteInfo, h HandlerFn) http.HandlerFunc {
ro.cache.AddRouteInfo(ri)
return func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), routeInfoKey{}, ri)
h.ServeHTTP(w, r.WithContext(ctx))
}
}
// TODO: move to base handler when it's implemented
func GetRouteInfo(r *http.Request) (RouteInfo, bool) {
info, ok := r.Context().Value(routeInfoKey{}).(RouteInfo)
return info, ok
}
func convertRouteToRouteName(route string) (string, error) {
name := "app"
if route == "/" {
return name + ".home", nil
}
route = strings.ReplaceAll(route, "/", ".")
route = strings.ReplaceAll(route, "-", "_")
paramRegex := regexp.MustCompile(`\.{[^}]*}`)
params := paramRegex.FindAllString(route, -1)
route = paramRegex.ReplaceAllString(route, "")
if len(params) > 0 {
route += ".params"
}
name += strings.TrimRight(route, ".")
return name, nil
}