| 1 | package handlers |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net/http" |
| 6 | ) |
| 7 | |
| 8 | type ContextHandler interface { |
| 9 | ServeHTTPContext(context.Context, http.ResponseWriter, *http.Request) |
| 10 | } |
| 11 | |
| 12 | type ContextHandlerFunc func(context.Context, http.ResponseWriter, *http.Request) |
| 13 | |
| 14 | func (f ContextHandlerFunc) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, req *http.Request) { |
| 15 | f(ctx, w, req) |
| 16 | } |
| 17 | |
| 18 | type ContextAdapter struct { |
| 19 | Ctx context.Context |
| 20 | Handler ContextHandler |
| 21 | } |
| 22 | |
| 23 | func (ca *ContextAdapter) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
| 24 | ca.Handler.ServeHTTPContext(ca.Ctx, w, req) |
| 25 | } |
| 26 | |
| 27 | type key int |
| 28 | |
| 29 | const ( |
| 30 | stateKey key = iota |
| 31 | ) |
| 32 | |
| 33 | func With(h ContextHandler, st *State) ContextHandler { |
| 34 | return ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, req *http.Request) { |
| 35 | ctx = context.WithValue(ctx, stateKey, st) |
| 36 | h.ServeHTTPContext(ctx, w, req) |
| 37 | }) |
| 38 | } |