-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
162 lines (150 loc) · 3.92 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
package rest
import (
"context"
"encoding/json"
"fmt"
"github.com/go-playground/validator/v10"
"github.com/gozelus/zelus_rest/logger"
"github.com/pkg/errors"
"io"
"math"
"net/http"
"strings"
"sync"
"github.com/google/uuid"
)
// abortIndex 一个极大值
// 一定比 handlers 数量大,导致 next 函数执行中断
const abortIndex int8 = math.MaxInt8 / 2
type contextImp struct {
context.Context
request *http.Request
resWriter http.ResponseWriter
// Keys 用于在控制流中传递内容
keys map[string]interface{}
// 用于标志唯一请求,上下文传递
requestID string
// mu 保护 Keys map
mu sync.RWMutex
validate *validator.Validate
handlers []HandlerFunc
index int8
}
// contextImp 的构造函数
func newContext() *contextImp {
c := contextImp{}
c.validate = validator.New()
return &c
}
func (c *contextImp) init(w http.ResponseWriter, req *http.Request) {
c.Context = context.Background()
c.request = req
c.resWriter = w
c.keys = map[string]interface{}{}
c.requestID = strings.Replace(uuid.Must(uuid.NewRandom()).String(), "-", "", -1)
c.index = -1
}
func (c *contextImp) RenderJSON(r Rsp) {
_ = c.renderJSON(r.ErrorCode(), struct {
Code int `json:"error_code"`
Message string `json:"error_message"`
RequestID string `json:"request_id"`
Data interface{} `json:"data"`
}{
Code: r.ErrorCode(),
Message: r.ErrorMessage(),
RequestID: c.requestID,
Data: r.Data(),
})
}
func (c *contextImp) Headers() map[string][]string {
return c.request.Header
}
func (c *contextImp) Method() string {
return c.request.Method
}
func (c *contextImp) Path() string {
return c.request.URL.Path
}
func (c *contextImp) GetRequestID() string { return c.requestID }
func (c *contextImp) Set(key string, v interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
c.keys[key] = v
}
func (c *contextImp) Get(key string) (v interface{}, ok bool) {
c.mu.RLock()
defer c.mu.RUnlock()
v, ok = c.keys[key]
return
}
func (c *contextImp) setHandlers(hs ...HandlerFunc) {
c.handlers = hs
}
func (c *contextImp) Next() {
c.index++
for c.index < int8(len(c.handlers)) {
c.handlers[c.index](c)
c.index++
}
}
func (c *contextImp) JSONBodyBind(ptr interface{}) error {
var reader io.Reader
if c.request.ContentLength > 0 && strings.Contains(c.request.Header.Get("Content-Type"), "application/json") {
reader = c.request.Body
} else {
reader = strings.NewReader("{}")
}
err := json.NewDecoder(reader).Decode(ptr)
if err != nil {
return err
}
if err := c.validate.Struct(ptr); err != nil {
if _, ok := err.(*validator.InvalidValidationError); ok {
logger.Warnf("eer : %s ", err.Error())
return err
}
for _, err := range err.(validator.ValidationErrors) {
fmt.Printf("Namespace = %s \n", err.Namespace())
fmt.Printf("Field = %s \n", err.Field())
fmt.Printf("StructNamespace = %s \n", err.StructNamespace())
fmt.Printf("StructField = %s \n", err.StructField())
fmt.Printf("Tag = %s \n", err.Tag())
fmt.Printf("ActualTag = %s \n", err.ActualTag())
fmt.Printf("Kind = %s \n", err.Kind())
fmt.Printf("Type = %s \n", err.Type())
fmt.Printf("Value = %s \n", err.Value())
fmt.Printf("Param = %s \n", err.Param())
fmt.Println()
}
return errors.New("?")
}
return nil
}
func (c *contextImp) JSONQueryBind(ptr interface{}) error {
form := map[string]interface{}{}
for k, v := range c.request.URL.Query() {
if len(v) > 0 {
form[k] = v[0]
}
}
bytes, _ := json.Marshal(form)
return json.Unmarshal(bytes, ptr)
}
// private func
// abort 用于中断流
func (c *contextImp) abort() {
c.index = abortIndex
}
func (c *contextImp) renderJSON(code int, obj interface{}) error {
defer c.abort()
c.resWriter.WriteHeader(code)
header := c.resWriter.Header()
header["Content-Type"] = []string{"application/javascript; charset=utf-8"}
jsonBytes, err := json.Marshal(obj)
if err != nil {
return err
}
_, err = c.resWriter.Write(jsonBytes)
return err
}