/
context.go
107 lines (88 loc) · 2.21 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
package gee
import (
"bytes"
"io"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"google.golang.org/protobuf/proto"
"github.com/goapt/gee/binding"
"github.com/goapt/gee/render"
)
type Context struct {
*gin.Context
httpStatus int
Response *Response
}
func (c *Context) getHttpStatus(status int) int {
if c.httpStatus == 0 {
return status
}
return c.httpStatus
}
func (c *Context) ShouldBindUri(obj any) error {
if _, ok := obj.(proto.Message); ok {
m := make(map[string][]string)
for _, v := range c.Params {
m[v.Key] = []string{v.Value}
}
return binding.Uri.BindUri(m, obj)
} else {
return c.Context.ShouldBindUri(obj)
}
}
func (c *Context) ShouldBindQuery(obj any) error {
if _, ok := obj.(proto.Message); ok {
return c.ShouldBindWith(obj, binding.Query)
} else {
return c.Context.ShouldBindQuery(obj)
}
}
func (c *Context) ShouldBindJSON(obj any) error {
return c.ShouldBindWith(obj, binding.JSON)
}
func (c *Context) ShouldBindBodyJSON(obj any) error {
return c.ShouldBindBodyWith(obj, binding.JSON)
}
// GetBody read body data and restore request body data
func (c *Context) GetBody() ([]byte, error) {
body, err := c.Context.GetRawData()
if err != nil {
return nil, err
}
c.Request.Body = io.NopCloser(bytes.NewReader(body))
return body, nil
}
func (c *Context) BindJSON(obj any) error {
return c.MustBindWith(obj, binding.JSON)
}
func (c *Context) Status(status int) {
c.httpStatus = status
}
func (c *Context) JSON(data any) error {
c.Context.Render(c.getHttpStatus(200), &render.JSON{Data: data})
return nil
}
func (c *Context) XML(data any) error {
c.Context.XML(c.getHttpStatus(200), data)
return nil
}
func (c *Context) YAML(data any) error {
c.Context.YAML(c.getHttpStatus(200), data)
return nil
}
func (c *Context) Redirect(location string) error {
c.Context.Redirect(c.getHttpStatus(302), location)
return nil
}
func (c *Context) String(format string, values ...any) error {
c.Context.String(c.getHttpStatus(200), format, values...)
return nil
}
func (c *Context) RequestId() string {
requestId := c.Request.Header.Get("X-Request-ID")
if requestId == "" {
requestId = uuid.New().String()
c.Request.Header.Set("X-Request-ID", requestId)
}
return requestId
}