-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
98 lines (82 loc) · 1.98 KB
/
context.go
File metadata and controls
98 lines (82 loc) · 1.98 KB
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
package web
import (
"encoding/json"
"errors"
"net/http"
"net/url"
"strconv"
)
type Context struct {
Resp http.ResponseWriter
Req *http.Request
// 缓存的响应部分
// 这部分数据会在最后刷新
RespStatusCode int
RespData []byte
PathParams map[string]string
// 缓存查询数据
cacheQueryValues url.Values
MatchedRoute string
UserValues map[string]any
}
func (ctx *Context) BindJSON(val any) error {
if ctx.Req.Body == nil {
return errors.New("thin-web: body 为 nil")
}
decoder := json.NewDecoder(ctx.Req.Body)
decoder.DisallowUnknownFields()
return decoder.Decode(val)
}
func (ctx *Context) FormValue(key string) StringValue {
if err := ctx.Req.ParseForm(); err != nil {
return StringValue{err: err}
}
return StringValue{val: ctx.Req.FormValue(key)}
}
func (ctx *Context) QueryValue(key string) StringValue {
if ctx.cacheQueryValues == nil {
ctx.cacheQueryValues = ctx.Req.URL.Query()
}
// get 方法会判空不方便排错
//v := ctx.cacheQueryValues.Get(key)
v, ok := ctx.cacheQueryValues[key]
if !ok {
return StringValue{err: errors.New("thin-web: 找不到这个 key")}
}
return StringValue{val: v[0]}
}
func (ctx *Context) PathValue(key string) StringValue {
v, ok := ctx.PathParams[key]
if !ok {
return StringValue{err: errors.New("thin-web: 找不到这个 key")}
}
return StringValue{val: v}
}
func (ctx *Context) SetCookie(cookie *http.Cookie) {
http.SetCookie(ctx.Resp, cookie)
}
func (ctx *Context) RespJSON(status int, val any) error {
bs, err := json.Marshal(val)
if err != nil {
return err
}
ctx.Resp.WriteHeader(status)
_, err = ctx.Resp.Write(bs)
return err
}
func (ctx *Context) RespJSONOK(val any) error {
return ctx.RespJSON(http.StatusOK, val)
}
type StringValue struct {
val string
err error
}
func (str StringValue) String() (string, error) {
return str.val, str.err
}
func (str StringValue) ToInt64() (int64, error) {
if str.err != nil {
return 0, str.err
}
return strconv.ParseInt(str.val, 10, 64)
}