|
77 | 77 | package httprouter
|
78 | 78 |
|
79 | 79 | import (
|
| 80 | + "context" |
80 | 81 | "net/http"
|
81 | 82 | )
|
82 | 83 |
|
@@ -107,6 +108,18 @@ func (ps Params) ByName(name string) string {
|
107 | 108 | return ""
|
108 | 109 | }
|
109 | 110 |
|
| 111 | +type paramsKey struct{} |
| 112 | + |
| 113 | +// ParamsKey is the request context key under which URL params are stored. |
| 114 | +var ParamsKey = paramsKey{} |
| 115 | + |
| 116 | +// ParamsFromContext pulls the URL parameters from a request context, |
| 117 | +// or returns nil if none are present. |
| 118 | +func ParamsFromContext(ctx context.Context) Params { |
| 119 | + p, _ := ctx.Value(ParamsKey).(Params) |
| 120 | + return p |
| 121 | +} |
| 122 | + |
110 | 123 | // Router is a http.Handler which can be used to dispatch requests to different
|
111 | 124 | // handler functions via configurable routes
|
112 | 125 | type Router struct {
|
@@ -236,6 +249,20 @@ func (r *Router) Handle(method, path string, handle Handle) {
|
236 | 249 | root.addRoute(path, handle)
|
237 | 250 | }
|
238 | 251 |
|
| 252 | +// Handler is an adapter which allows the usage of an http.Handler as a |
| 253 | +// request handle. |
| 254 | +// The Params are available in the request context under ParamsKey. |
| 255 | +func (r *Router) Handler(method, path string, handler http.Handler) { |
| 256 | + r.Handle(method, path, |
| 257 | + func(w http.ResponseWriter, req *http.Request, p Params) { |
| 258 | + ctx := req.Context() |
| 259 | + ctx = context.WithValue(ctx, ParamsKey, p) |
| 260 | + req = req.WithContext(ctx) |
| 261 | + handler.ServeHTTP(w, req) |
| 262 | + }, |
| 263 | + ) |
| 264 | +} |
| 265 | + |
239 | 266 | // HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a
|
240 | 267 | // request handle.
|
241 | 268 | func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) {
|
|
0 commit comments