--wip-- [skip ci]
This commit is contained in:
1 parent
72bc974aa6
commit
bca93f6c6c
12 files changed
+256
-54
No files matched your search
@@ -2,8 +2,10 @@ package templer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -25,12 +27,38 @@ func Middleware(next http.Handler) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// Path returns the current path without a leading slash
|
||||
// Path returns the current path with 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, "/")
|
||||
return path
|
||||
}
|
||||
|
||||
func RelativePath(ctx context.Context, relPath string) (path string, err error) {
|
||||
baseStr := Path(ctx)
|
||||
|
||||
if baseStr != "" && !strings.HasSuffix(baseStr, "/") {
|
||||
baseStr += "/"
|
||||
}
|
||||
|
||||
base, err := url.Parse(baseStr)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("could not parse base path: %w", err)
|
||||
return
|
||||
}
|
||||
rel, err := url.Parse(relPath)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("could not parse relative path: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Resolve the relative path against the base
|
||||
path = base.ResolveReference(rel).Path
|
||||
if strings.HasSuffix(path, "/") {
|
||||
path = path[:len(path)-1]
|
||||
}
|
||||
return
|
||||
}
|
||||
Reference in new issue
Block a user