feat: translation middleware
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
package templer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
pathKey ctxKey = iota
|
||||
)
|
||||
|
||||
func Middleware(next http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
ctx = context.WithValue(ctx, pathKey, r.URL.Path)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
// Path returns the current path without a leading slash
|
||||
func Path(ctx context.Context) string {
|
||||
path, ok := ctx.Value(pathKey).(string)
|
||||
if !ok {
|
||||
slog.Error("could not extract request path from context")
|
||||
return ""
|
||||
}
|
||||
return strings.TrimPrefix(path, "/")
|
||||
}
|
||||
Reference in New Issue
Block a user