-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcontext.go
70 lines (58 loc) · 1.15 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
59
60
61
62
63
64
65
66
67
68
69
70
package bon
import (
"context"
"net/http"
)
var contextKey = &struct {
name string
}{
name: "BON",
}
type (
Context struct {
params params
}
params struct {
keys []string
values []string
}
)
func (m *Mux) NewContext() *Context {
return &Context{
params: params{
keys: make([]string, 0, m.maxParam),
values: make([]string, 0, m.maxParam),
},
}
}
// allocate
func (ctx *Context) WithContext(r *http.Request) *http.Request {
return r.WithContext(
context.WithValue(r.Context(), contextKey, ctx),
)
}
func (ctx *Context) reset() *Context {
ctx.params.keys = ctx.params.keys[:0]
ctx.params.values = ctx.params.values[:0]
return ctx
}
func (ctx *Context) PutParam(key, value string) {
ctx.params.keys = append(ctx.params.keys, key)
ctx.params.values = append(ctx.params.values, value)
}
func (ctx *Context) GetParam(key string) string {
for i, v := range ctx.params.keys {
if v == key {
return ctx.params.values[i]
}
}
return ""
}
func URLParam(r *http.Request, key string) string {
if ctx := r.Context().Value(contextKey); ctx != nil {
if ctx, ok := ctx.(*Context); ok {
return ctx.GetParam(key)
}
}
return ""
}