-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
executable file
·58 lines (50 loc) · 1.34 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package scaffold
import (
"net/http"
"golang.org/x/net/context"
)
type paramContext struct {
context.Context
params map[string]Param
}
func newParamContext(ctx context.Context, r *http.Request, vars map[int]string) *paramContext {
params := make(map[string]Param)
for i, p := range vars {
k, v := paramName(p), ""
ctx, v, _ = URLPart(ctx, r, i)
params[k] = Param(v)
}
return ¶mContext{
Context: ctx,
params: params,
}
}
func (p *paramContext) Value(key interface{}) interface{} {
if p.params != nil {
if k, ok := key.(string); ok {
if param, ok := p.params[k]; ok {
return param
}
}
}
return p.Context.Value(key)
}
func wrapMiddleware(vars map[int]string, middleware Middleware) Middleware {
return Middleware(func(next Handler) Handler {
return HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
p := newParamContext(ctx, r, vars)
teardown := HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
p.params = nil
next.CtxServeHTTP(ctx, w, r)
})
middleware(teardown).CtxServeHTTP(p, w, r)
})
})
}
func wrapHandler(vars map[int]string, handler Handler) Handler {
return HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
p := newParamContext(ctx, r, vars)
handler.CtxServeHTTP(p, w, r)
p.params = nil
})
}