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) }