diff options
| author | Stefan Majewsky <majewsky@gmx.net> | 2026-10-05 22:21:26 +0200 |
|---|---|---|
| committer | Stefan Majewsky <majewsky@gmx.net> | 2026-10-05 22:21:26 +0200 |
| commit | 43a403b45d9644e634c2c560d16331305d83a4b0 (patch) | |
| tree | 8ec3825579b388c205edfebed76b04906ae5368f | |
| parent | 6e5880aca9744d5e21434708f550f383400966e4 (diff) | |
| download | go-gg-43a403b45d9644e634c2c560d16331305d83a4b0.tar.gz | |
pathrouter: remove type Context from public interface
| -rw-r--r-- | CHANGELOG.md | 10 | ||||
| -rw-r--r-- | benchmark/pathrouter/pathrouter_test.go | 4 | ||||
| -rw-r--r-- | pathrouter/catchallvariable.go | 7 | ||||
| -rw-r--r-- | pathrouter/choice.go | 3 | ||||
| -rw-r--r-- | pathrouter/context.go | 54 | ||||
| -rw-r--r-- | pathrouter/element.go | 8 | ||||
| -rw-r--r-- | pathrouter/handler.go | 16 | ||||
| -rw-r--r-- | pathrouter/here.go | 4 | ||||
| -rw-r--r-- | pathrouter/matcher.go | 11 | ||||
| -rw-r--r-- | pathrouter/pathrouter_test.go | 6 | ||||
| -rw-r--r-- | pathrouter/variable.go | 12 |
11 files changed, 96 insertions, 39 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index d0536a2..c576b6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,16 @@ SPDX-FileCopyrightText: 2026 Stefan Majewsky <majewsky@gmx.net> SPDX-License-Identifier: Apache-2.0 --> +# v1.18.0 (TBD) + +Changes: + +- pathrouter: Remove `type Context` argument from `HandlerFunc` signature. + When first using pathrouter in a real-world application, the extra argument proved cumbersome, + so I settled on clever shenanigans within the library in order to make application code more readable. + I really hate that I'm breaking compatiblity yet again, but in the end, user experience matters most. + My takeaway is that new packages should go through a period of declared instability until the first major users are done. + # v1.17.0 (2026-10-02) Changes: diff --git a/benchmark/pathrouter/pathrouter_test.go b/benchmark/pathrouter/pathrouter_test.go index 361cc2f..7eefc43 100644 --- a/benchmark/pathrouter/pathrouter_test.go +++ b/benchmark/pathrouter/pathrouter_test.go @@ -62,9 +62,9 @@ func buildMuxRouterForDistributionAPI() http.Handler { } func buildPathrouterForDistributionAPI() http.Handler { - handle := func(endpointName string) pr.HandlerFunc { + handle := func(endpointName string) http.HandlerFunc { msg := endpointName + " is forbidden" - return func(w http.ResponseWriter, r *http.Request, vars map[string]string) { + return func(w http.ResponseWriter, r *http.Request) { http.Error(w, msg, http.StatusForbidden) } } diff --git a/pathrouter/catchallvariable.go b/pathrouter/catchallvariable.go index d1d3e2c..29947ab 100644 --- a/pathrouter/catchallvariable.go +++ b/pathrouter/catchallvariable.go @@ -4,16 +4,17 @@ package pathrouter import ( + "net/http" "strings" . "go.xyrillian.de/gg/option" ) // CatchAllVariable is a [Matcher] that accepts subpaths with an arbitrary number of path elements. -// The value of any amount of leading path elements will be collected into the [Context], +// The value of any amount of leading path elements will be collected +// (to be retrieved inside the request handler using [VariableValue]), // such that the remainder is accepted by the next matcher. // At least one element must be collected. -// The full sequence of collected path elements can be retrieved with [Context.Variable]. // // CatchAllVariable() may appear at any point within the routing tree, // but it may not contain another CatchAllVariable() anywhere within it. @@ -33,7 +34,7 @@ func catchAllVariable(name string, matcher realMatcher) Matcher { panic("matcher within CatchAllVariable() may not accept unlimited path lengths") } - accept := func(path []string, rc Context) HandlerFunc { + accept := func(path []string, rc routingContext) http.HandlerFunc { for length := innerMinLength; length <= innerMaxLength; length++ { if length > len(path) { break diff --git a/pathrouter/choice.go b/pathrouter/choice.go index d107785..ee64151 100644 --- a/pathrouter/choice.go +++ b/pathrouter/choice.go @@ -4,6 +4,7 @@ package pathrouter import ( + "net/http" "slices" . "go.xyrillian.de/gg/option" @@ -48,7 +49,7 @@ func choice(matchers []realMatcher) Matcher { return realMatcher{ minLength: slices.Min(minLengths), maxLength: maxLength, - accept: func(path []string, rc Context) HandlerFunc { + accept: func(path []string, rc routingContext) http.HandlerFunc { for _, m := range matchers { hf := m.accept(path, rc) if hf != nil { diff --git a/pathrouter/context.go b/pathrouter/context.go index d47e302..7408960 100644 --- a/pathrouter/context.go +++ b/pathrouter/context.go @@ -3,21 +3,61 @@ package pathrouter -// Context contains information about an HTTP request that has been processed by matchers from this package. -// It appears as an argument in [HandlerFunc]. -type Context struct { +import ( + "context" + "maps" + "net/http" +) + +type routingContextKeyType struct{} + +var routingContextKey = any(routingContextKeyType{}) + +// routingContext contains information about an HTTP request that has been processed by matchers from this package. +// It is stored in `r.Body` of the HTTP request by wrapping the original response body's behavior. +type routingContext struct { vars map[string]string } -func newContext() Context { - return Context{ +func injectContext(r *http.Request) (*http.Request, routingContext) { + // NOTE: Using context.WithValue() and thus extending the chain within r.Context by another element + // incurs a performance penalty whenever `r.Context` is used, but it's the option that sucks the least. + // We initially had `type HandlerFunc = func(http.ResponseWriter, *http.Request, pathrouter.Context)` + // to avoid this performance penalty, but having another thing that's called "Context" is confusing. + // The final API implementation accepts a slight performance decrease to prioritize developer ergonomics. + // + // The only other option that does not add an extra argument to the HandlerFunc signature is to stash + // `type routingContext` within `r.Body`, but that would incur the performance penalty on every use of + // `r.Body` instead of `r.Context()`, which is usually much worse. + + rc := routingContext{ vars: make(map[string]string), } + ctx := context.WithValue(r.Context(), routingContextKey, rc) + return r.WithContext(ctx), rc } -// Variable returns the path element(s) collected by a [Variable] or [CatchAllVariable] matcher with the given name, +// VariableValue returns the path element(s) collected by a [Variable] or [CatchAllVariable] matcher of the same name, // with any URL escaping removed. // If no matcher with this name appeared in the path leading up to the handler, the empty string is returned. -func (rc Context) Variable(name string) string { +// +// Panics if r is not a request that was routed by a [Matcher] from this package. +func VariableValue(r *http.Request, name string) string { + rc, ok := r.Context().Value(routingContextKey).(routingContext) + if !ok { + panic("request was not routed by gg/pathrouter") + } return rc.vars[name] } + +// VariableValues returns all path element(s) collected by [Variable] or [CatchAllVariable] matchers, keyed on the name of the matcher. +// The result is the set of all possible values that [VariableValue] can return. +// +// Panics if r is not a request that was routed by a [Matcher] from this package. +func VariableValues(r *http.Request) map[string]string { + rc, ok := r.Context().Value(routingContextKey).(routingContext) + if !ok { + panic("request was not routed by gg/pathrouter") + } + return maps.Clone(rc.vars) +} diff --git a/pathrouter/element.go b/pathrouter/element.go index 395fb40..6426c04 100644 --- a/pathrouter/element.go +++ b/pathrouter/element.go @@ -3,7 +3,11 @@ package pathrouter -import "go.xyrillian.de/gg/options" +import ( + "net/http" + + "go.xyrillian.de/gg/options" +) // Element is a [Matcher] that accepts subpaths with at least one path element. // The first path element must be equal to the given value, @@ -24,7 +28,7 @@ func element(value string, matcher realMatcher) Matcher { return realMatcher{ minLength: matcher.minLength + 1, maxLength: options.Map(matcher.maxLength, increment), - accept: func(path []string, rc Context) HandlerFunc { + accept: func(path []string, rc routingContext) http.HandlerFunc { if len(path) == 0 || path[0] != value { return nil } diff --git a/pathrouter/handler.go b/pathrouter/handler.go index 1ecabdd..ad14845 100644 --- a/pathrouter/handler.go +++ b/pathrouter/handler.go @@ -12,16 +12,10 @@ import ( . "go.xyrillian.de/gg/option" ) -// HandlerFunc is like [http.HandlerFunc], but also receives variable values that were extracted from the URL path. -// -// Package pathrouter passes variables explicitly like this, instead of via [context.Context.WithValue], -// because doing so imposes a performance penalty for every usage of the respective context. -type HandlerFunc = func(w http.ResponseWriter, r *http.Request, rc Context) - // ByMethod is a set of request handlers matching the same request path, keyed on request method. // It is commonly constructed as a literal using the respective constants from the net/http package, such as [http.MethodGet]. // This type appears in the signature of func [Handlers], see documentation over there for details. -type ByMethod map[string]HandlerFunc +type ByMethod map[string]http.HandlerFunc // Handlers is a [Matcher] that accepts empty subpaths only. // It appears at the leaf nodes of a [Matcher] tree, which correspond to specific endpoint paths, @@ -41,7 +35,7 @@ type ByMethod map[string]HandlerFunc // // If there is a handler for [http.MethodGet], but none for [http.MethodHead], the GET handler will be called for HEAD as well. // To have a GET handler, but no HEAD handler, set the handler for [http.MethodHead] to nil. -// Any other use of a nil [HandlerFunc] is invalid and will cause a panic. +// Any other use of a nil [http.HandlerFunc] is invalid and will cause a panic. func Handlers(m ByMethod) Matcher { // reuse GET handler for HEAD if not overridden if handler, exists := m[http.MethodGet]; exists { @@ -62,10 +56,10 @@ func Handlers(m ByMethod) Matcher { // precomputations for accept() allowHeader := m.buildAllowHeader() - serve := func(w http.ResponseWriter, r *http.Request, rc Context) { + serve := func(w http.ResponseWriter, r *http.Request) { handler, ok := m[r.Method] if ok { - handler(w, r, rc) + handler(w, r) return } @@ -80,7 +74,7 @@ func Handlers(m ByMethod) Matcher { return realMatcher{ minLength: 0, maxLength: Some(0), - accept: func(path []string, rc Context) HandlerFunc { + accept: func(path []string, rc routingContext) http.HandlerFunc { if len(path) != 0 { return nil } diff --git a/pathrouter/here.go b/pathrouter/here.go index bf21016..e0d4eee 100644 --- a/pathrouter/here.go +++ b/pathrouter/here.go @@ -4,6 +4,8 @@ package pathrouter import ( + "net/http" + . "go.xyrillian.de/gg/option" ) @@ -43,7 +45,7 @@ func here(matcher realMatcher) Matcher { return realMatcher{ minLength: 0, maxLength: Some(1), - accept: func(path []string, rc Context) HandlerFunc { + accept: func(path []string, rc routingContext) http.HandlerFunc { if len(path) == 0 || (len(path) == 1 && path[0] == "") { return matcher.accept(nil, rc) } diff --git a/pathrouter/matcher.go b/pathrouter/matcher.go index 45ba818..0ddd7f6 100644 --- a/pathrouter/matcher.go +++ b/pathrouter/matcher.go @@ -49,10 +49,10 @@ // // Path matching is performed on the escaped form of the URL path, as returned by [url.URL.EscapedPath], // so any slashes that were encoded as %2F in the URL path will be considered part of a path element instead of a boundary. +// After matching, [VariableValue] calls return unescaped values. // // For instance, using the example above, the URL path "/v1/objects/42/23" would not match and generate a 404 response, -// but the URL path "/v1/objects/42%2F23" would match and invoke (e.g. with method GET) the GetObject handler with rc.Variable("id") = "42/23". -// Like in this example, [HandlerFunc] will receive a [Context] in which [Context.Variable] calls returns unescaped values. +// but the URL path "/v1/objects/42%2F23" would match and invoke (e.g. with method GET) the GetObject handler with pathrouter.VariableValue(r, "id") = "42/23". // // # Implicit normalizations // @@ -97,7 +97,7 @@ type Matcher interface { } type realMatcher struct { - accept func(path []string, rc Context) HandlerFunc + accept func(path []string, rc routingContext) http.HandlerFunc // The smallest len(path) that accept() can accept. minLength int @@ -115,12 +115,13 @@ func (m realMatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) { // TryServeHTTP implements the [Matcher] interface. func (m realMatcher) TryServeHTTP(w http.ResponseWriter, r *http.Request) bool { path := extractPath(r.URL) - rc := newContext() + var rc routingContext + r, rc = injectContext(r) handlerFunc := m.accept(path, rc) if handlerFunc == nil { return false } else { - handlerFunc(w, r, rc) + handlerFunc(w, r) return true } } diff --git a/pathrouter/pathrouter_test.go b/pathrouter/pathrouter_test.go index 96083ed..08a7c69 100644 --- a/pathrouter/pathrouter_test.go +++ b/pathrouter/pathrouter_test.go @@ -19,10 +19,10 @@ import ( func TestRouting(t *testing.T) { // helper methods varRx := regexp.MustCompile(`\$\w+`) - h := func(status int, msgBase string) pr.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request, rc pr.Context) { + h := func(status int, msgBase string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { msg := varRx.ReplaceAllStringFunc(msgBase, func(match string) string { - return rc.Variable(strings.TrimPrefix(match, "$")) + return pr.VariableValue(r, strings.TrimPrefix(match, "$")) }) if r.Method == http.MethodHead { w.WriteHeader(status) diff --git a/pathrouter/variable.go b/pathrouter/variable.go index 0cb44aa..78bf394 100644 --- a/pathrouter/variable.go +++ b/pathrouter/variable.go @@ -3,12 +3,16 @@ package pathrouter -import "go.xyrillian.de/gg/options" +import ( + "net/http" + + "go.xyrillian.de/gg/options" +) // Variable is a [Matcher] that accepts subpaths with at least one path element. -// The value of the first path element will be collected into the [Context], +// The value of the first path element will be collected +// (to be retrieved inside the request handler using [VariableValue]), // and the remaining subpath will have to be accepted by the next matcher. -// The collected path element can be retrieved with [Context.Variable]. func Variable(name string, matcher Matcher) Matcher { return variable(name, matcher.downcast()) } @@ -17,7 +21,7 @@ func variable(name string, matcher realMatcher) Matcher { return realMatcher{ minLength: matcher.minLength + 1, maxLength: options.Map(matcher.maxLength, increment), - accept: func(path []string, rc Context) HandlerFunc { + accept: func(path []string, rc routingContext) http.HandlerFunc { if len(path) == 0 || path[0] == "" { return nil } |
