/
context.go
132 lines (95 loc) · 2 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
package web
import (
"encoding/json"
"errors"
"net/http"
"net/url"
"reflect"
"strconv"
)
type StringValue struct {
data string
err error
}
func (s StringValue) AsInt64() (int64, error) {
if s.err != nil {
return 0, s.err
}
return strconv.ParseInt(s.data, 10, 64)
}
type Context struct {
Req *http.Request
Resp http.ResponseWriter
PathParams map[string]string
QueryData url.Values
RespStatus int
RespData []byte
MatchedRoute string
T TemplateEngine
UserValues map[string]any
}
func (c *Context) Render(tplName string, data any) error {
ctx := c.Req.Context()
var err error
c.RespData, err = c.T.Render(ctx, tplName, data)
if err != nil {
c.RespStatus = http.StatusInternalServerError
return err
}
c.RespStatus = http.StatusOK
return nil
}
// BindJSON 将body的json数据绑定到传入参数类型上
func (c *Context) BindJSON(data any) error {
typ := reflect.TypeOf(data)
if typ.Kind() != reflect.Pointer {
return errors.New("传入类型必须为指针类型")
}
decoder := json.NewDecoder(c.Req.Body)
return decoder.Decode(data)
}
func (c *Context) GetForm(key string) StringValue {
err := c.Req.ParseForm()
if err != nil {
return StringValue{"", err}
}
data, ok := c.Req.Form[key]
if !ok {
return StringValue{"", errors.New("key不存在")}
}
return StringValue{
data: data[0],
err: nil,
}
}
func (c *Context) GetQuery(key string) StringValue {
if c.QueryData == nil {
c.QueryData = c.Req.URL.Query()
}
data, ok := c.QueryData[key]
if !ok {
return StringValue{
data: "",
err: errors.New("key不存在"),
}
}
return StringValue{
data: data[0],
err: nil,
}
}
func (c *Context) WriteJSONOK(resp any) error {
return c.WriteJSON(http.StatusOK, resp)
}
func (c *Context) WriteJSON(status int, resp any) error {
data, err := json.Marshal(resp)
if err != nil {
return err
}
c.RespStatus = status
c.RespData = data
return nil
}
func (c *Context) SetCookie(cookie *http.Cookie) {
http.SetCookie(c.Resp, cookie)
}