@@ -122,6 +122,25 @@ func ParamsFromContext(ctx context.Context) Params {
122
122
return p
123
123
}
124
124
125
+ type matchKey struct {}
126
+
127
+ // MatchedRoutePathKey is the request context key under which the handler path
128
+ // match is stored.
129
+ var MatchedRoutePathKey = matchKey {}
130
+
131
+ // MatchedRoutePathFromContext retrieves the matched route path from the context.
132
+ func MatchedRoutePathFromContext (ctx context.Context ) string {
133
+ p , _ := ctx .Value (MatchedRoutePathKey ).(string )
134
+ return p
135
+ }
136
+
137
+ func saveMatchedRoutePathToContext (path string , handle Handle ) Handle {
138
+ return func (w http.ResponseWriter , req * http.Request , ps Params ) {
139
+ req = req .WithContext (context .WithValue (req .Context (), MatchedRoutePathKey , path ))
140
+ handle (w , req , ps )
141
+ }
142
+ }
143
+
125
144
// Router is a http.Handler which can be used to dispatch requests to different
126
145
// handler functions via configurable routes
127
146
type Router struct {
@@ -130,6 +149,10 @@ type Router struct {
130
149
paramsPool sync.Pool
131
150
maxParams uint16
132
151
152
+ // SaveMatchedRoutePathToContext when enabled adds the matched route path
153
+ // onto the http.Request context before invoking the handler
154
+ SaveMatchedRoutePathToContext bool
155
+
133
156
// Enables automatic redirection if the current route can't be matched but a
134
157
// handler for the path with (without) the trailing slash exists.
135
158
// For example if /foo/ is requested but a route only exists for /foo, the
@@ -268,6 +291,10 @@ func (r *Router) Handle(method, path string, handle Handle) {
268
291
panic ("handle must not be nil" )
269
292
}
270
293
294
+ if r .SaveMatchedRoutePathToContext {
295
+ handle = saveMatchedRoutePathToContext (path , handle )
296
+ }
297
+
271
298
if r .trees == nil {
272
299
r .trees = make (map [string ]* node )
273
300
}
0 commit comments