forked from glennliao/apijson-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhook.go
More file actions
executable file
·84 lines (64 loc) · 1.6 KB
/
hook.go
File metadata and controls
executable file
·84 lines (64 loc) · 1.6 KB
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
84
package action
import (
"context"
"net/http"
)
type HookReq struct {
Node *Node
Method string
ctx context.Context
hooks []*Hook
nextIdx int
isInTransaction bool
handler finishHandler
}
func (r *HookReq) IsPost() bool {
return r.Method == http.MethodPost
}
func (r *HookReq) IsPut() bool {
return r.Method == http.MethodPut
}
func (r *HookReq) IsDelete() bool {
return r.Method == http.MethodDelete
}
func (r *HookReq) Next() error {
for {
var h *Hook
for r.nextIdx+1 < len(r.hooks) && h == nil {
r.nextIdx++
_h := r.hooks[r.nextIdx]
if r.isInTransaction {
if _h.HandlerInTransaction == nil {
continue
}
h = _h
} else {
if _h.Handler == nil {
continue
}
h = _h
}
}
if h != nil {
if r.nextIdx < len(r.hooks) {
if r.isInTransaction {
return h.HandlerInTransaction(r.ctx, r)
}
return h.Handler(r.ctx, r)
}
}
return r.handler(r.ctx, r.Node, r.Method)
}
}
type Hook struct {
For []string
// 事务外 , 可执行参数校验,io等耗时操作
Handler func(ctx context.Context, req *HookReq) error
// 事务内,尽量少执行耗时操作 (无论request配置中是否开启事务, 都会先执行handler 然后 在范围内执行HandlerInTransaction)
HandlerInTransaction func(ctx context.Context, req *HookReq) error
}
type finishHandler func(ctx context.Context, n *Node, method string) error
func getHooksByAccessName(hooksMap map[string][]*Hook, accessName string) []*Hook {
hooks := append(hooksMap["*"], hooksMap[accessName]...)
return hooks
}