diff options
| author | tjpcc <tjp@ctrl-c.club> | 2023-09-28 08:08:48 -0600 |
|---|---|---|
| committer | tjpcc <tjp@ctrl-c.club> | 2023-10-09 08:47:37 -0600 |
| commit | 6e1c25af361dde4c063eccbf769e966df4b65f23 (patch) | |
| tree | d28044cf2db246555deda8db395f2f0a7e786590 /userpath.go | |
| parent | b4f45f7c654e87bda6d5e7effb6ac5b5feb29ce0 (diff) | |
config file refactor
Diffstat (limited to 'userpath.go')
| -rw-r--r-- | userpath.go | 61 |
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) +} |
