-
Notifications
You must be signed in to change notification settings - Fork 0
/
gin_operator.go
246 lines (214 loc) · 5.69 KB
/
gin_operator.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package ginx
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/shrewx/ginx/internal/binding"
"github.com/shrewx/ginx/internal/errors"
"github.com/shrewx/ginx/internal/middleware"
"github.com/shrewx/ginx/pkg/logx"
"github.com/shrewx/ginx/pkg/statuserror"
"github.com/shrewx/ginx/pkg/trace"
"net/http"
"reflect"
"strings"
)
type GinGroup struct {
EmptyOperator
basePath string
}
func (g *GinGroup) BasePath() string {
return g.basePath
}
func Group(path string) *GinGroup {
return &GinGroup{
basePath: path,
}
}
type GinRouter struct {
bathPath string
handleOperator HandleOperator
middlewareOperators []TypeOperator
children map[*GinRouter]bool
}
func (g *GinRouter) Output(ctx *gin.Context) (interface{}, error) {
return g.handleOperator.Output(ctx)
}
func (g *GinRouter) Path() string {
if g.handleOperator != nil {
return g.handleOperator.Path()
}
return ""
}
func (g *GinRouter) BasePath() string { return g.bathPath }
func (g *GinRouter) Method() string {
if g.handleOperator != nil {
return g.handleOperator.Method()
}
return ""
}
func NewRouter(operators ...Operator) *GinRouter {
var (
r = &GinRouter{}
middlewareOperators []TypeOperator
)
r.children = make(map[*GinRouter]bool, 0)
for i, operator := range operators {
switch operator.(type) {
case GroupOperator:
if i != 0 {
panic("you should define path in first param")
}
r.bathPath = operator.(GroupOperator).BasePath()
case HandleOperator:
r.handleOperator = operator.(HandleOperator)
case TypeOperator:
middlewareOperators = append(middlewareOperators, operator.(TypeOperator))
}
}
r.middlewareOperators = middlewareOperators
return r
}
func (g *GinRouter) Register(r Operator) {
switch r.(type) {
case TypeOperator:
g.middlewareOperators = append(g.middlewareOperators, r.(TypeOperator))
case RouterOperator:
g.children[r.(*GinRouter)] = true
default:
child := NewRouter(r)
g.children[child] = true
}
}
func initGinEngine(r *GinRouter, agent *trace.Agent) *gin.Engine {
root := gin.New()
// health
root.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, "health")
})
// internal middleware
root.Use(gin.Recovery())
root.Use(middleware.CORS())
root.Use(middleware.Telemetry(agent))
loadGinRouters(root, r)
return root
}
func loadGinRouters(ir gin.IRouter, r *GinRouter) {
if r.children != nil && len(r.children) != 0 {
var middleware []gin.HandlerFunc
for _, op := range r.middlewareOperators {
middleware = append(middleware, ginMiddlewareWrapper(op))
}
newIRouter := ir.Group(r.bathPath, middleware...)
for child := range r.children {
loadGinRouters(newIRouter, child)
}
}
if op := r.handleOperator; r.handleOperator != nil {
switch strings.ToUpper(op.Method()) {
case "GET":
ir.GET(op.Path(), ginHandleFuncWrapper(op))
case "POST":
ir.POST(op.Path(), ginHandleFuncWrapper(op))
case "PUT":
ir.PUT(op.Path(), ginHandleFuncWrapper(op))
case "DELETE":
ir.DELETE(op.Path(), ginHandleFuncWrapper(op))
case "HEAD":
ir.HEAD(op.Path(), ginHandleFuncWrapper(op))
case "PATCH":
ir.PATCH(op.Path(), ginHandleFuncWrapper(op))
case "OPTIONS":
ir.OPTIONS(op.Path(), ginHandleFuncWrapper(op))
default:
panic(fmt.Sprintf("method %s is invalid", op.Method()))
}
}
}
func ginHandleFuncWrapper(op Operator) gin.HandlerFunc {
return func(ctx *gin.Context) {
op = reflect.New(reflect.ValueOf(op).Elem().Type()).Interface().(Operator)
// set operation name
ctx.Set(OperationName, reflect.TypeOf(op).Elem().Name())
// set lang to ctx so that client can know the lang
if ctx.GetHeader(LangHeader) == "" {
ctx.Header(LangHeader, I18nZH)
}
if err := binding.Validate(ctx, op); err != nil {
logx.ErrorWithoutSkip(err)
ginErrorWrapper(errors.BadRequest, ctx)
return
}
result, err := op.Output(ctx)
if err != nil {
ginErrorWrapper(err, ctx)
return
}
// for gin HandlerFunc
if handle, ok := result.(gin.HandlerFunc); ok {
handle(ctx)
}
if !ctx.IsAborted() && !ctx.Writer.Written() && ctx.Writer.Status() == http.StatusOK {
code := http.StatusOK
if ctx.Request.Method == http.MethodPost {
code = http.StatusCreated
}
switch response := result.(type) {
case MineDescriber:
if attachment, ok := response.(*Attachment); ok {
attachment.Header(ctx)
}
ctx.Data(code, response.ContentType(), response.Bytes())
default:
ctx.JSON(code, response)
}
}
return
}
}
func ginMiddlewareWrapper(op Operator) gin.HandlerFunc {
return func(ctx *gin.Context) {
op = reflect.New(reflect.ValueOf(op).Elem().Type()).Interface().(Operator)
ctx.Set(OperationName, reflect.TypeOf(op).Elem().Name())
if err := binding.Validate(ctx, op); err != nil {
logx.ErrorWithoutSkip(err)
ginErrorWrapper(err, ctx)
return
}
result, err := op.Output(ctx)
if err != nil {
ginErrorWrapper(err, ctx)
return
}
// for gin HandlerFunc
if handle, ok := result.(gin.HandlerFunc); ok {
handle(ctx)
}
}
}
func ginErrorWrapper(err error, ctx *gin.Context) {
switch e := err.(type) {
case *statuserror.StatusErr:
ctx.AbortWithStatusJSON(e.StatusCode(), e.I18n(GetLang(ctx)))
case statuserror.CommonError:
ctx.AbortWithStatusJSON(statuserror.StatusCodeFromCode(e.Code()), e.I18n(GetLang(ctx)))
default:
ctx.AbortWithStatusJSON(http.StatusInternalServerError, &statuserror.StatusErr{
Key: errors.InternalServerError.Key(),
ErrorCode: http.StatusBadGateway,
Message: e.Error(),
})
}
}
func GetLang(ctx *gin.Context) string {
lang := ginx.i18n
if ctx.GetHeader(LangHeader) != "" {
switch ctx.GetHeader(LangHeader) {
case I18nEN:
lang = I18nEN
case I18nZH:
lang = I18nZH
default:
}
}
return lang
}