summaryrefslogtreecommitdiff
path: root/userpath.go
diff options
context:
space:
mode:
Diffstat (limited to 'userpath.go')
-rw-r--r--userpath.go61
1 files changed, 61 insertions, 0 deletions
diff --git a/userpath.go b/userpath.go
new file mode 100644
index 0000000..9c9793f
--- /dev/null
+++ b/userpath.go
@@ -0,0 +1,61 @@
+package main
+
+import (
+ "context"
+ "os/user"
+ "path"
+ "path/filepath"
+ "strings"
+
+ sr "tildegit.org/tjp/sliderule"
+)
+
+func usernameFromRouter(ctx context.Context) (string, bool) {
+ username, ok := sr.RouteParams(ctx)["username"]
+ return username, ok
+}
+
+func userFsRoute(ctx context.Context, route RouteDirective) (RouteDirective, bool) {
+ username, ok := usernameFromRouter(ctx)
+ if !ok {
+ return route, false
+ }
+
+ u, err := user.Lookup(username)
+ if err != nil {
+ return route, false
+ }
+
+ route.URLPath = strings.ReplaceAll(route.URLPath, "~", "~"+u.Username)
+ if strings.HasPrefix(route.FsPath, "~/") {
+ route.FsPath = filepath.Join(u.HomeDir, route.FsPath[2:])
+ } else {
+ route.FsPath = strings.ReplaceAll(route.FsPath, "/~/", "/"+u.Username+"/")
+ }
+ return route, true
+}
+
+func buildAndAddRoute(router *sr.Router, route RouteDirective, handlerf func(RouteDirective) sr.Handler) {
+ var (
+ urlpath string
+ handler sr.Handler
+ )
+
+ if strings.IndexByte(route.FsPath, '~') < 0 {
+ urlpath = route.URLPath
+ handler = handlerf(route)
+ } else {
+ urlpath = strings.Replace(route.URLPath, "~", "~:username", 1)
+ handler = sr.HandlerFunc(func(ctx context.Context, request *sr.Request) *sr.Response {
+ route, ok := userFsRoute(ctx, route)
+ if !ok {
+ return nil
+ }
+
+ return handlerf(route).Handle(ctx, request)
+ })
+ }
+
+ router.Route(urlpath, handler)
+ router.Route(path.Join(urlpath, "*"), handler)
+}