Skip to content

Commit 0162dec

Browse files
committed
router: move context params stuff to router.go
1 parent 4c7fa62 commit 0162dec

File tree

2 files changed

+27
-32
lines changed

2 files changed

+27
-32
lines changed

params.go

Lines changed: 0 additions & 32 deletions
This file was deleted.

router.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@
7777
package httprouter
7878

7979
import (
80+
"context"
8081
"net/http"
8182
)
8283

@@ -107,6 +108,18 @@ func (ps Params) ByName(name string) string {
107108
return ""
108109
}
109110

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+
110123
// Router is a http.Handler which can be used to dispatch requests to different
111124
// handler functions via configurable routes
112125
type Router struct {
@@ -236,6 +249,20 @@ func (r *Router) Handle(method, path string, handle Handle) {
236249
root.addRoute(path, handle)
237250
}
238251

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+
239266
// HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a
240267
// request handle.
241268
func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) {

0 commit comments

Comments
 (0)