From 64b06db74da3bb77c7bd703bf9124fed83c47d7f Mon Sep 17 00:00:00 2001 From: tjpcc Date: Mon, 9 Oct 2023 08:59:01 -0600 Subject: router/pathtree: support a required path segment prefix before :wildcards --- router.go | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) (limited to 'router.go') diff --git a/router.go b/router.go index d45a7de..7cf3142 100644 --- a/router.go +++ b/router.go @@ -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{} -- cgit v1.2.3