-
Notifications
You must be signed in to change notification settings - Fork 1
/
echotool.go
139 lines (115 loc) · 2.47 KB
/
echotool.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package echotool
import (
"sync"
"time"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/songzhaoliang/echotool/metric"
"github.com/songzhaoliang/echotool/pprof"
"github.com/songzhaoliang/echotool/swagger"
)
type HandlerFunc func(echo.Context, *Context)
type HandlerFuncsChain []HandlerFunc
type Engine struct {
middlewares HandlerFuncsChain
finisher HandlerFunc
aborter HandlerFunc
contextPool sync.Pool
}
type Option func(*Engine)
func WithFinisher(finisher HandlerFunc) Option {
return func(e *Engine) {
if finisher != nil {
e.finisher = finisher
}
}
}
func WithAborter(aborter HandlerFunc) Option {
return func(e *Engine) {
if aborter != nil {
e.aborter = aborter
}
}
}
func NewEngine(opts ...Option) *Engine {
e := &Engine{
finisher: GetCommonFinisher(),
aborter: GetCommonAborter(),
}
for _, opt := range opts {
opt(e)
}
return e
}
func NewDefaultEcho() *echo.Echo {
r := echo.New()
r.Use(middleware.Recover())
r.Use(SetRequestID(GetUUID))
pprof.Register(r)
metric.Register(r)
swagger.Register(r)
return r
}
func NewDefaultEngine(opts ...Option) *Engine {
e := NewEngine(opts...)
e.Use(AddTraceID(GetRequestID))
e.Use(PrintRequest())
return e
}
func (e *Engine) Use(middlewares ...HandlerFunc) *Engine {
e.middlewares = append(e.middlewares, middlewares...)
return e
}
func (e *Engine) EchoHandler(handlers ...HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if len(handlers) == 0 {
return nil
}
ec := e.acquireContext()
defer e.releaseContext(ec)
defer func() {
if r := recover(); r != nil {
if err, ok := r.(*EchotoolError); ok {
ec.Abort(err.GetCode(), err.GetError())
ReleaseEchotoolError(err)
e.aborter(c, ec)
} else {
panic(r)
}
}
}()
ec.handlerName = GetHandlerName(handlers[0])
ec.handlers = append(ec.handlers, e.middlewares...)
ec.handlers = append(ec.handlers, handlers...)
for _, handler := range ec.handlers {
handler(c, ec)
if !ec.IsOK() {
break
}
}
if ec.IsOK() {
e.finisher(c, ec)
} else {
e.aborter(c, ec)
}
return nil
}
}
func (e *Engine) acquireContext() (ec *Context) {
if v := e.contextPool.Get(); v != nil {
ec = v.(*Context)
} else {
ec = &Context{}
}
ec.engine = e
ec.ok = true
ec.customValues = make(map[string]string)
ec.startTime = time.Now()
return
}
func (e *Engine) releaseContext(ec *Context) {
if ec != nil {
ec.reset()
e.contextPool.Put(ec)
}
}