diff options
author | tjpcc <tjp@ctrl-c.club> | 2023-10-09 08:59:01 -0600 |
---|---|---|
committer | tjpcc <tjp@ctrl-c.club> | 2023-10-09 08:59:01 -0600 |
commit | 64b06db74da3bb77c7bd703bf9124fed83c47d7f (patch) | |
tree | 6eea64f3de0358cb3e3d49010b2ff21a967cb63f /router.go | |
parent | 20be557b7bc3d7ada78411b7b279c9f7580d0bc7 (diff) |
router/pathtree: support a required path segment prefix before :wildcardsv1.4.0
Diffstat (limited to 'router.go')
-rw-r--r-- | router.go | 17 |
1 files changed, 10 insertions, 7 deletions
@@ -2,6 +2,7 @@ package sliderule import ( "context" + "path" "strings" "tildegit.org/tjp/sliderule/internal" @@ -10,9 +11,11 @@ import ( // Router stores a mapping of request path patterns to handlers. // // Pattern may begin with "/" and then contain slash-delimited segments. -// - Segments beginning with colon (:) are wildcards and will match any path +// - Segments containing a colon (:) are wildcards and will match any path // segment at that location. It may optionally have a word after the colon, -// which will be the parameter name the path segment is captured into. +// which will be the parameter name the path segment is captured into. It +// may also optionally have text before the colon, in which case the pattern +// will not match unless the request path segment contains that prefix. // - Segments beginning with asterisk (*) are remainder wildcards. This must // come last and will capture any remainder of the path. It may have a name // after the asterisk which will be the parameter name. @@ -50,7 +53,7 @@ func (r Router) Handle(ctx context.Context, request *Request) *Response { return nil } - return handler.Handle(context.WithValue(ctx, routeParamsKey, params), request) + return handler.Handle(context.WithValue(ctx, RouteParamsKey, params), request) } // Handler builds a Handler @@ -83,8 +86,8 @@ func (r *Router) Mount(prefix string, subrouter *Router) { prefix = strings.TrimSuffix(prefix, "/") for _, subroute := range subrouter.tree.Routes() { - r.Route(prefix+"/"+subroute.Pattern, subroute.Value) - if subroute.Pattern == "" { + r.Route(path.Join(prefix, subroute.Pattern), subroute.Value) + if subroute.Pattern == "/" { r.Route(prefix, subroute.Value) } } @@ -111,7 +114,7 @@ func (r *Router) Use(mw Middleware) { // If Router was used but no parameters were captured in the pattern, it // returns a non-nil empty map. func RouteParams(ctx context.Context) map[string]string { - if m, ok := ctx.Value(routeParamsKey).(map[string]string); ok { + if m, ok := ctx.Value(RouteParamsKey).(map[string]string); ok { return m } return nil @@ -119,4 +122,4 @@ func RouteParams(ctx context.Context) map[string]string { type routeParamsKeyType struct{} -var routeParamsKey = routeParamsKeyType{} +var RouteParamsKey = routeParamsKeyType{} |