Skip to content

Commit a64d89a

Browse files
committed
httphelper: add more helpers for Handler w/ context
Add an httphelper.Handler type that is analogous to the http.Handler type, except that it also takes a context. Also fix WrapHandler so that it calls ServeHTTP on the HandlerFunc. Signed-off-by: Blake Gentry <blakesgentry@gmail.com>
1 parent 02778c9 commit a64d89a

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

pkg/httphelper/httphelper.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,27 @@ var CORSAllowAllHandler = cors.Allow(&cors.Options{
5050
MaxAge: time.Hour,
5151
})
5252

53+
// Handler is an extended version of http.Handler that also takes a context
54+
// argument ctx.
55+
type Handler interface {
56+
ServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request)
57+
}
58+
59+
// The HandlerFunc type is an adapter to allow the use of ordinary functions as
60+
// Handlers. If f is a function with the appropriate signature, HandlerFunc(f)
61+
// is a Handler object that calls f.
5362
type HandlerFunc func(context.Context, http.ResponseWriter, *http.Request)
5463

64+
// ServeHTTP calls f(ctx, w, r).
65+
func (f HandlerFunc) ServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request) {
66+
f(ctx, w, r)
67+
}
68+
5569
func WrapHandler(handler HandlerFunc) httprouter.Handle {
5670
return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
5771
ctx := contextFromResponseWriter(w)
5872
ctx = ctxhelper.NewContextParams(ctx, params)
59-
handler(ctx, w, req)
73+
handler.ServeHTTP(ctx, w, req)
6074
}
6175
}
6276

0 commit comments

Comments
 (0)