-
Notifications
You must be signed in to change notification settings - Fork 35
/
context.go
755 lines (616 loc) · 20 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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
package quark
import (
"bytes"
"errors"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"reflect"
"strings"
"github.com/derekstavis/go-qs"
"github.com/gobeam/stringy"
"github.com/golang-jwt/jwt/v4"
"github.com/gorilla/sessions"
"github.com/labstack/echo/v4"
"github.com/mitchellh/mapstructure"
"github.com/quarkcloudio/quark-go/v3/utils/tag"
)
// Context is the most important part of gin. It allows us to pass variables between middleware,
// manage the flow, validate the JSON of a request and render a JSON response for example.
type Context struct {
Engine *Engine // 引擎实例
EchoContext echo.Context // Echo框架上下文
Request *http.Request // Request
Writer http.ResponseWriter // ResponseWriter
Template interface{} // 资源模板实例
fullPath string // 路由
Params map[string]string // URL param
Querys map[string]interface{} // URL querys
}
type ParamValue struct {
Key int
Value string
}
// ContentType returns the Content-Type header of the request.
func (p *Context) ContentType() string {
return p.Request.Header.Get("Content-Type")
}
// IsTLS returns true if HTTP connection is TLS otherwise false.
func (p *Context) IsTLS() bool {
return p.EchoContext.IsTLS()
}
// IsWebSocket returns true if HTTP connection is WebSocket otherwise false.
func (p *Context) IsWebSocket() bool {
return p.EchoContext.IsWebSocket()
}
// Scheme returns the HTTP protocol scheme, `http` or `https`.
func (p *Context) Scheme() string {
return p.EchoContext.Scheme()
}
// RealIP returns the client's network address based on `X-Forwarded-For`
// or `X-Real-IP` request header.
// The behavior can be configured using `Echo#IPExtractor`.
func (p *Context) RealIP() string {
return p.EchoContext.RealIP()
}
// QueryParam returns the query param for the provided name.
func (p *Context) QueryParam(name string) string {
return p.EchoContext.QueryParam(name)
}
// QueryParams returns the query parameters as `url.Values`.
func (p *Context) QueryParams() url.Values {
return p.EchoContext.QueryParams()
}
// QueryString returns the URL query string.
func (p *Context) QueryString() string {
return p.EchoContext.QueryString()
}
// FormValue returns the form field value for the provided name.
func (p *Context) FormValue(name string) string {
return p.EchoContext.FormValue(name)
}
// FormParams returns the form parameters as `url.Values`.
func (p *Context) FormParams() (url.Values, error) {
return p.EchoContext.FormParams()
}
// FormFile returns the multipart form file for the provided name.
func (p *Context) FormFile(name string) (*multipart.FileHeader, error) {
return p.EchoContext.FormFile(name)
}
// MultipartForm returns the multipart form.
func (p *Context) MultipartForm() (*multipart.Form, error) {
return p.EchoContext.MultipartForm()
}
// Cookie returns the named cookie provided in the request.
func (p *Context) Cookie(name string) (*http.Cookie, error) {
return p.EchoContext.Cookie(name)
}
// SetCookie adds a `Set-Cookie` header in HTTP response.
func (p *Context) SetCookie(cookie *http.Cookie) {
p.EchoContext.SetCookie(cookie)
}
// Cookies returns the HTTP cookies sent with the request.
func (p *Context) Cookies() []*http.Cookie {
return p.EchoContext.Cookies()
}
// Session returns the named session provided in the request.
func (p *Context) Session(name string) (*sessions.Session, error) {
return p.Engine.cookieStore.Get(p.Request, name)
}
// SetSession adds a `session` in HTTP response.
func (p *Context) SetSession(name string, values map[interface{}]interface{}) error {
sess, err := p.Engine.cookieStore.Get(p.Request, name)
if err != nil {
return err
}
sess.Values = values
return sess.Save(p.Request, p.Writer)
}
// SetSessionWithOptions adds a `session` with options in HTTP response.
func (p *Context) SetSessionWithOptions(name string, options *sessions.Options, values map[interface{}]interface{}) error {
sess, err := p.Engine.cookieStore.Get(p.Request, name)
if err != nil {
return err
}
sess.Options = options
sess.Values = values
return sess.Save(p.Request, p.Writer)
}
// Get retrieves data from the context.
func (p *Context) Get(key string) interface{} {
return p.EchoContext.Get(key)
}
// Set saves data in the context.
func (p *Context) Set(key string, val interface{}) {
p.EchoContext.Set(key, val)
}
// Bind binds the request body into provided type `i`. The default binder
// does it based on Content-Type header.
func (p *Context) Bind(i interface{}) error {
if err := p.EchoContext.Bind(i); err != nil {
return err
}
// Set tag defaults
// type Example struct {
// Page int `default:"1"`
// Size int `default:"10"`
// IsBool bool `default:"true"`
// Keyword string `default:"hello world"`
// Number float64 `default:"1.23"`
// Status [3]int `default:"1,2"`
// TimeRange []string `default:"12:30,13:30"`
// Data map[string]interface{} `default:"age:18,name:zero"`
// }
// {Page:1 Size:10 Keyword:hello world Number:1.23 Status:[1 2 0] TimeRange:[12:30 13:30] Data:map[age:18 name:zero]}
tag.SetDefaults(reflect.ValueOf(i).Elem())
return nil
}
// Validate validates provided `i`. It is usually called after `Context#Bind()`.
// Validator must be registered using `Echo#Validator`.
func (p *Context) Validate(i interface{}) error {
return p.EchoContext.Validate(i)
}
// Render renders a template with data and sends a text/html response with status
// code. Renderer must be registered using `Echo.Renderer`.
func (p *Context) Render(code int, name string, data interface{}) error {
return p.EchoContext.Render(code, name, data)
}
// HTML sends an HTTP response with status code.
func (p *Context) HTML(code int, html string) error {
return p.EchoContext.HTML(code, html)
}
// HTMLBlob sends an HTTP blob response with status code.
func (p *Context) HTMLBlob(code int, b []byte) error {
return p.EchoContext.HTMLBlob(code, b)
}
// String sends a string response with status code.
func (p *Context) String(code int, s string) error {
return p.EchoContext.String(code, s)
}
// JSON sends a JSON response with status code.
func (p *Context) JSON(code int, i interface{}) error {
return p.EchoContext.JSON(code, i)
}
// JSONPretty sends a pretty-print JSON with status code.
func (p *Context) JSONPretty(code int, i interface{}, indent string) error {
return p.EchoContext.JSONPretty(code, i, indent)
}
// JSONBlob sends a JSON blob response with status code.
func (p *Context) JSONBlob(code int, b []byte) error {
return p.EchoContext.JSONBlob(code, b)
}
// JSONP sends a JSONP response with status code. It uses `callback` to construct
// the JSONP payload.
func (p *Context) JSONP(code int, callback string, i interface{}) error {
return p.EchoContext.JSONP(code, callback, i)
}
// JSONPBlob sends a JSONP blob response with status code. It uses `callback`
// to construct the JSONP payload.
func (p *Context) JSONPBlob(code int, callback string, b []byte) error {
return p.EchoContext.JSONPBlob(code, callback, b)
}
// XML sends an XML response with status code.
func (p *Context) XML(code int, i interface{}) error {
return p.EchoContext.XML(code, i)
}
// XMLPretty sends a pretty-print XML with status code.
func (p *Context) XMLPretty(code int, i interface{}, indent string) error {
return p.EchoContext.XMLPretty(code, i, indent)
}
// XMLBlob sends an XML blob response with status code.
func (p *Context) XMLBlob(code int, b []byte) error {
return p.EchoContext.XMLBlob(code, b)
}
// Blob sends a blob response with status code and content type.
func (p *Context) Blob(code int, contentType string, b []byte) error {
return p.EchoContext.Blob(code, contentType, b)
}
// Stream sends a streaming response with status code and content type.
func (p *Context) Stream(code int, contentType string, r io.Reader) error {
return p.EchoContext.Stream(code, contentType, r)
}
// File sends a response with the content of the file.
func (p *Context) File(file string) error {
return p.EchoContext.File(file)
}
// File upload
func (p *Context) SaveFile(file *multipart.FileHeader, path string) error {
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()
// Destination
dst, err := os.Create(path)
if err != nil {
return err
}
defer dst.Close()
// Copy
if _, err = io.Copy(dst, src); err != nil {
return err
}
return err
}
// Attachment sends a response as attachment, prompting client to save the
// file.
func (p *Context) Attachment(file string, name string) error {
return p.EchoContext.Attachment(file, name)
}
// Inline sends a response as inline, opening the file in the browser.
func (p *Context) Inline(file string, name string) error {
return p.EchoContext.Inline(file, name)
}
// NoContent sends a response with no body and a status code.
func (p *Context) NoContent(code int) error {
return p.EchoContext.NoContent(code)
}
// Redirect redirects the request to a provided URL with status code.
func (p *Context) Redirect(code int, url string) error {
return p.EchoContext.Redirect(code, url)
}
// Error invokes the registered global HTTP error handler. Generally used by middleware.
// A side-effect of calling global error handler is that now Response has been committed (sent to the client) and
// middlewares up in chain can not change Response status code or Response body anymore.
//
// Avoid using this method in handlers as no middleware will be able to effectively handle errors after that.
func (p *Context) Error(err error) {
p.EchoContext.Error(err)
}
// 设置SetFullPath
func (p *Context) SetFullPath(fullPath string) *Context {
p.fullPath = fullPath
return p
}
// FullPath returns a matched route full path. For not found routes
// returns an empty string.
//
// router.GET("/user/:id", func(c *gin.Context) {
// c.FullPath() == "/user/:id" // true
// })
func (p *Context) FullPath() string {
return p.fullPath
}
// Method return request method.
//
// Returned value is valid until returning from RequestHandler.
func (p *Context) Method() string {
return p.Request.Method
}
// Host returns requested host.
//
// The host is valid until returning from RequestHandler.
func (p *Context) Host() string {
return p.Request.Host
}
// Path returns requested path.
//
// The path is valid until returning from RequestHandler.
func (p *Context) Path() string {
return p.Request.URL.Path
}
// OriginalURL returns url query data
func (p *Context) OriginalURL() string {
return p.Request.URL.RawQuery
}
// IP tries to parse the headers in [X-Real-Ip, X-Forwarded-For]. It calls RemoteIP() under the hood
func (p *Context) ClientIP() string {
return p.EchoContext.RealIP()
}
// BodyParser binds the request body to a struct.
// It supports decoding the following content types based on the Content-Type header:
// application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data
// If none of the content types above are matched, it will return a ErrUnprocessableEntity error
func (p *Context) BodyParser(i interface{}) error {
if err := p.EchoContext.Bind(i); err != nil {
return err
}
// Set tag defaults
// type Example struct {
// Page int `default:"1"`
// Size int `default:"10"`
// IsBool bool `default:"true"`
// Keyword string `default:"hello world"`
// Number float64 `default:"1.23"`
// Status [3]int `default:"1,2"`
// TimeRange []string `default:"12:30,13:30"`
// Data map[string]interface{} `default:"age:18,name:zero"`
// }
// {Page:1 Size:10 Keyword:hello world Number:1.23 Status:[1 2 0] TimeRange:[12:30 13:30] Data:map[age:18 name:zero]}
tag.SetDefaults(reflect.ValueOf(i).Elem())
return nil
}
// 获取请求头数据
func (p *Context) Header(key string) string {
if len(p.Request.Header[key]) > 0 {
return p.Request.Header[key][0]
}
return ""
}
// Method return request method.
//
// Returned value is valid until returning from RequestHandler.
func (p *Context) Write(data []byte) {
p.Writer.Write(data)
}
// Body returns body data
func (p *Context) Body() []byte {
body, err := io.ReadAll(p.Request.Body)
if err != nil {
return nil
}
// 重新赋值
p.Request.Body = io.NopCloser(bytes.NewBuffer(body))
return body
}
// Param returns the value of the URL param.
// It is a shortcut for c.Params.ByName(key)
func (p *Context) parseParams() {
params := map[string]string{}
fullPaths := strings.Split(p.FullPath(), "/")
paramValues := []*ParamValue{}
for k, v := range fullPaths {
if strings.Contains(v, ":") {
v = stringy.New(v).ReplaceFirst(":", "")
mapValue := &ParamValue{
Key: k,
Value: v,
}
paramValues = append(paramValues, mapValue)
}
}
paths := strings.Split(p.Path(), "/")
for _, v := range paramValues {
params[v.Value] = paths[v.Key]
}
p.SetParams(params)
}
// 设置Params
func (p *Context) SetParams(params map[string]string) *Context {
p.Params = params
return p
}
// Param returns the value of the URL param.
// It is a shortcut for c.Params.ByName(key)
//
// router.GET("/user/:id", func(c *hertz.RequestContext) {
// // a GET request to /user/john
// id := c.Param("id") // id == "john"
// })
func (p *Context) Param(key string) string {
if p.Params == nil {
p.parseParams()
}
return p.Params[key]
}
// Query returns the value of the URL Querys.
func (p *Context) parseQuerys() {
querys, err := qs.Unmarshal(p.Request.URL.RawQuery)
if err == nil {
p.Querys = querys
}
}
// Query returns the value of the URL query.
func (p *Context) Query(params ...interface{}) interface{} {
if p.Querys == nil {
p.parseQuerys()
}
if len(params) == 2 {
if p.Querys[params[0].(string)] == nil {
return params[1]
}
}
return p.Querys[params[0].(string)]
}
// AllQuerys returns all query arguments from RequestURI.
func (p *Context) AllQuerys() map[string]interface{} {
if p.Querys == nil {
p.parseQuerys()
}
return p.Querys
}
// ResourceName returns the value of the URL Resource param.
// If request path is "/api/admin/login/index" and route is "/api/admin/login/:resource"
//
// resourceName := p.ResourceName() // resourceName = "index"
func (p *Context) ResourceName() string {
return p.Param("resource")
}
// 替换路由中的资源参数
//
// url := p.RouteToEngineUrl("/api/admin/login/:resource/captchaId") // url = "/api/admin/login/index/captchaId"
func (p *Context) RouterPathToUrl(routerPath string) string {
name := p.ResourceName()
return strings.ReplaceAll(routerPath, ":resource", name)
}
// 获取Header中的token
func (p *Context) Token() string {
authorization := p.Header("Authorization")
authorizations := strings.Split(authorization, " ")
if len(authorizations) == 2 {
return authorizations[1]
}
queryToken := p.Query("token", "")
if queryToken.(string) != "" {
return queryToken.(string)
}
return ""
}
// 生成JWT认证的token
func (p *Context) JwtToken(claims interface{}) (tokenString string, err error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims.(jwt.Claims))
return token.SignedString([]byte(p.Engine.GetConfig().AppKey))
}
// 获取当前JWT认证的用户信息
func (p *Context) JwtAuthUser(claims interface{}) (err error) {
authUser, err := p.JwtAuthUserMap()
if err != nil {
return err
}
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Result: claims,
TagName: "json",
})
if err != nil {
return err
}
return decoder.Decode(authUser)
}
// 获取当前JWT认证的用户信息,返回的数据为map格式
func (p *Context) JwtAuthUserMap() (result jwt.MapClaims, err error) {
token, err := jwt.Parse(p.Token(), func(token *jwt.Token) (interface{}, error) {
return []byte(p.Engine.config.AppKey), nil
})
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, errors.New("token is malformed")
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
return nil, errors.New("token is expired")
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, errors.New("token is not valid yet")
} else {
return nil, err
}
}
}
if !token.Valid {
return nil, errors.New("token is invalid")
}
return token.Claims.(jwt.MapClaims), nil
}
// 根据路由判断是否为当前加载实例
func (p *Context) isCurrentTemplate(provider interface{}) bool {
providerName := reflect.TypeOf(provider).String()
getNames := strings.Split(providerName, ".")
structName := getNames[len(getNames)-1]
ResourceName := p.ResourceName()
return strings.EqualFold(strings.ToLower(structName), strings.ToLower(ResourceName))
}
// 解析UseHandler方法
func (p *Context) useHandlerParser() error {
var err error
for _, Handler := range p.Engine.UseHandlers() {
err = Handler(p)
if err == nil {
return nil
}
if err.Error() != p.Next().Error() {
return err
}
}
return err
}
// 初始化模板实例
func (p *Context) InitTemplate(ctx *Context) error {
var (
err error
templateInstance interface{}
)
// 获取模板实例
templateInstance, err = p.getTemplate(ctx)
if err != nil {
return err
}
// 设置模板实例
p.setTemplate(templateInstance)
return nil
}
// 获取当前模板实例
func (p *Context) getTemplate(ctx *Context) (interface{}, error) {
var templateInstance interface{}
for _, provider := range p.Engine.providers {
// 模版参数初始化
provider.(interface {
TemplateInit(ctx *Context) interface{}
}).TemplateInit(ctx)
// 实例初始化
provider.(interface {
Init(ctx *Context) interface{}
}).Init(ctx)
// 初始化路由
provider.(interface {
RouteInit() interface{}
}).RouteInit()
// 加载自定义路由
provider.(interface {
Route() interface{}
}).Route()
// 获取模板定义的路由
templateInstanceRoutes := provider.(interface {
GetRouteMapping() []*RouteMapping
}).GetRouteMapping()
for _, v := range templateInstanceRoutes {
if v.Path == p.FullPath() {
if p.isCurrentTemplate(provider) {
// 设置实例
templateInstance = provider
}
}
}
}
if templateInstance == nil {
return nil, errors.New("unable to find resource instance")
}
return templateInstance, nil
}
// 设置当前模板实例
func (p *Context) setTemplate(templateInstance interface{}) {
// 设置实例
p.Template = templateInstance
}
// 判断当前页面是否为列表页面 todo
func (p *Context) IsIndex() bool {
uri := strings.Split(p.Path(), "/")
return (uri[len(uri)-1] == "index")
}
// 判断当前页面是否为创建页面
func (p *Context) IsCreating() bool {
uri := strings.Split(p.Path(), "/")
return (uri[len(uri)-1] == "create") || (uri[len(uri)-1] == "store")
}
// 判断当前页面是否为编辑页面
func (p *Context) IsEditing() bool {
uri := strings.Split(p.Path(), "/")
return (uri[len(uri)-1] == "edit") || (uri[len(uri)-1] == "save")
}
// 判断当前页面是否为详情页面
func (p *Context) IsDetail() bool {
uri := strings.Split(p.Path(), "/")
return (uri[len(uri)-1] == "detail")
}
// 判断当前页面是否为导出页面
func (p *Context) IsExport() bool {
uri := strings.Split(p.Path(), "/")
return (uri[len(uri)-1] == "export")
}
// 判断当前页面是否为导入页面
func (p *Context) IsImport() bool {
uri := strings.Split(p.Path(), "/")
return (uri[len(uri)-1] == "import")
}
// 输出成功状态的JSON数据,JSONOk("成功") | JSONOk("成功", map[string]interface{}{"title":"标题"})
func (p *Context) JSONOk(message ...interface{}) error {
var (
content = ""
data interface{}
)
if len(message) == 1 {
content = message[0].(string)
}
if len(message) == 2 {
content = message[0].(string)
data = message[1]
}
return p.JSON(200, Success(content, data))
}
// 输出失败状态的JSON数据,JSONError("错误")
func (p *Context) JSONError(message string) error {
return p.JSON(200, Error(message))
}
// 执行下一个Use方法,TODO
func (p *Context) Next() error {
return errors.New("NextUseHandler")
}