-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
83 lines (72 loc) · 2.07 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
71
72
73
74
75
76
77
78
79
80
81
82
83
package httputil
import (
"container/list"
"context"
"net/http"
"reflect"
)
type httpContextKey string
const (
httpContextName httpContextKey = "_httpcontext_"
)
// Context 上下文
type httpContext struct {
element *list.Element
head *list.List
w http.ResponseWriter
r *http.Request
}
// WithHTTPContext 新建一个Context
func WithHTTPContext(parent context.Context) context.Context {
return context.WithValue(parent, httpContextName, &httpContext{
head: list.New(),
})
}
// Use 设置一个中间件
func Use(ctx context.Context, f http.HandlerFunc) context.Context {
httpCtx := ctx.Value(httpContextName).(*httpContext)
httpCtx.head.PushBack(f)
return ctx
}
// HandleFunc 包装http.HandlerFunc
func HandleFunc(ctx context.Context, handlers ...http.HandlerFunc) http.HandlerFunc {
httpCtx := ctx.Value(httpContextName).(*httpContext)
// 生成静态上下文
staticHead := list.New()
staticHead.PushBackList(httpCtx.head)
for _, f := range handlers {
staticHead.PushBack(f)
}
// 已一个nil表示结尾
staticHead.PushBack(nil)
return func(w http.ResponseWriter, r *http.Request) {
rawContext := r.Context()
// 生成动态上下文
dynamic := &httpContext{
head: staticHead,
element: staticHead.Front(),
w: w,
}
if rawContext != nil {
dynamic.r = r.WithContext(context.WithValue(rawContext, httpContextName, dynamic))
} else {
dynamic.r = r.WithContext(context.WithValue(context.Background(), httpContextName, dynamic))
}
Next(dynamic.r.Context())
}
}
// Next 调用下一个中间件
func Next(ctx context.Context) {
httpCtx := ctx.Value(httpContextName).(*httpContext)
if !reflect.ValueOf(httpCtx.element.Value).IsNil() {
handler := (httpCtx.element.Value).(http.HandlerFunc)
httpCtx.element = httpCtx.element.Next()
handler(httpCtx.w, httpCtx.r)
}
}
// WithValue 添加数据
func WithValue(ctx context.Context, key, val interface{}) context.Context {
httpCtx := ctx.Value(httpContextName).(*httpContext)
httpCtx.r = httpCtx.r.WithContext(context.WithValue(ctx, key, val))
return httpCtx.r.Context()
}