This repository was archived by the owner on Jan 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
328 lines (286 loc) · 6.69 KB
/
context.go
File metadata and controls
328 lines (286 loc) · 6.69 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
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
package mint
import (
"compress/gzip"
"context"
"encoding/json"
"net"
"net/http"
"net/url"
"strings"
)
//constant
const (
emptyString = ""
PayloadKey = "PayLoad"
contentType = "Content-Type"
contentEncoding = "Content-Encoding"
)
var (
newLine = []byte{'\n'}
jsonContentType = []string{"application/json; charset=utf-8"}
gzipContentEncoding = []string{"gzip"}
)
//Context provides context for whole request/response cycle
//It helps to pass variable from one middlware to another
type Context struct {
HandlerContext *HandlerContext
Req *http.Request
Res http.ResponseWriter
params map[string]string
index int
status int
size int
errors []error
query url.Values
}
func (app *Mint) newContext() *Context {
return new(Context)
}
//Reset resets the value the context
func (c *Context) Reset() {
c.HandlerContext = nil
c.Req = nil
c.Res = nil
c.status = 0
c.size = 0
c.errors = c.errors[0:0]
c.index = 0
c.params = nil
c.query = nil
}
func newContextPool(app *Mint) func() interface{} {
return func() interface{} {
return app.newContext()
}
}
//GetHeader returns request header
//shortcut for c.Rewq
func (c *Context) GetHeader(key string) string {
return c.Req.Header.Get(key)
}
//Status set http status code'
func (c *Context) Status(status int) {
c.status = status
c.Res.WriteHeader(status)
}
func (c *Context) writeContentType(values []string) {
c.SetHeader(contentType, values)
}
//SetHeader #
func (c *Context) SetHeader(key string, value []string) {
header := c.Res.Header()
if val := header[key]; len(val) == 0 {
header[key] = value
}
}
//AddHeader add header to the response
func (c *Context) AddHeader(key string, value string) {
c.Res.Header().Add(key, value)
}
func bodyAllowedForStatus(status int) bool {
switch {
case status >= 100 && status <= 199:
return false
case status == http.StatusNoContent:
return false
case status == http.StatusNotModified:
return false
}
return true
}
//CJSON writes compressed json response
func (c *Context) compressedJSON(code int, response interface{}) {
// create header
c.SetHeader(contentEncoding, gzipContentEncoding)
// Gzip data
c.Status(code)
gz := c.HandlerContext.Mint.gzipWriterPool.Get().(*gzip.Writer)
bytes := c.HandlerContext.Mint.bufferPool.Get()
gz.Reset(c.Res)
err := json.NewEncoder(bytes).Encode(response)
if err != nil {
c.Error(err)
}
size, err := gz.Write(bytes.Bytes())
c.HandlerContext.Mint.bufferPool.Put(bytes)
if err != nil {
c.Errors(err)
}
c.setSize(size)
size, err = gz.Write(newLine)
c.setSize(size)
if err != nil {
c.Errors(err)
}
gz.Close()
c.HandlerContext.Mint.gzipWriterPool.Put(gz)
}
//JSON #
func (c *Context) JSON(code int, response interface{}) {
c.SetHeader(contentType, jsonContentType)
if bodyAllowedForStatus(code) {
if c.HandlerContext.compressed {
c.compressedJSON(code, response)
} else {
c.uncompressedJSON(code, response)
}
} else {
c.Status(code)
}
}
//JSON writes json response
func (c *Context) uncompressedJSON(code int, response interface{}) {
c.Status(code)
bytes := c.HandlerContext.Mint.bufferPool.Get()
err := json.NewEncoder(bytes).Encode(response)
if err != nil {
c.Error(err)
}
size, err := c.Res.Write(bytes.Bytes())
c.HandlerContext.Mint.bufferPool.Put(bytes)
if err != nil {
c.Errors(err)
}
c.setSize(size)
size, err = c.Res.Write(newLine)
c.setSize(size)
if err != nil {
c.Errors(err)
}
}
func (c *Context) setSize(size int) {
c.size += size
}
//Errors records error to be displayed later
func (c *Context) Errors(err ...error) {
for _, er := range err {
c.Error(er)
}
}
func (c *Context) Error(err error) {
if err != nil {
c.errors = append(c.errors, err)
}
}
//ClientIP returns ip address of the user using request info
func (c *Context) ClientIP() string {
clientIP := c.GetHeader("X-Forwarded-For")
clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
if clientIP == emptyString {
clientIP = strings.TrimSpace(c.GetHeader("X-Real-Ip"))
}
if clientIP != emptyString {
return clientIP
}
if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Req.RemoteAddr)); err == nil {
return ip
}
return emptyString
}
//Next runs the next handler
func (c *Context) Next() {
if c.index >= c.HandlerContext.count {
return
}
handle := c.HandlerContext.handlers[c.index]
c.index++
handle(c)
}
//QueryArray #
func (c *Context) QueryArray(key string) ([]string, bool) {
if c.query == nil {
c.query = c.Req.URL.Query()
}
if values, ok := c.query[key]; ok && len(values) > 0 {
return values, true
}
return []string{}, false
}
//Query #
func (c *Context) Query(key string) (string, bool) {
queryArray, ok := c.QueryArray(key)
if ok {
return queryArray[0], ok
}
return "", ok
}
//DefaultQuery #
func (c *Context) DefaultQuery(key string, defaultv string) string {
value, ok := c.Query(key)
if ok {
return value
}
return defaultv
}
//QueryValues #
func (c *Context) QueryValues() url.Values {
return c.query
}
//Get #
func (c *Context) Get(key interface{}) interface{} {
return c.Req.Context().Value(key)
}
//DefaultGet #
func (c *Context) DefaultGet(key interface{}, defaultv interface{}) interface{} {
value := c.Get(key)
if value == nil {
return defaultv
}
return value
}
//GetString gets string value using key in context
func (c *Context) GetString(key interface{}) string {
return c.Get(key).(string)
}
//GetInt64 gets values associated with key as int64
func (c *Context) GetInt64(key interface{}) int64 {
return c.Get(key).(int64)
}
//GetFloat64 gets values associated with key as float64
func (c *Context) GetFloat64(key interface{}) float64 {
return c.Get(key).(float64)
}
//GetComplex128 gets values associated with key as complex128
func (c *Context) GetComplex128(key interface{}) complex128 {
return c.Get(key).(complex128)
}
//Set #
func (c *Context) Set(key, val interface{}) {
if val == nil {
return
}
c.Req = c.Req.WithContext(context.WithValue(c.Req.Context(), key, val))
}
//Param #
func (c *Context) Param(key string) (string, bool) {
value, ok := c.params[key]
if ok {
return value, ok
}
return "", ok
}
//DefaultParam #
func (c *Context) DefaultParam(key string, defaultv string) string {
value, ok := c.params[key]
if ok {
return value
}
return defaultv
}
//ParamMap #
func (c *Context) ParamMap() map[string]string {
return c.params
}
//MintParam #
func (c *Context) MintParam(key string) (interface{}, bool) {
value, ok := c.HandlerContext.Mint.Get(key)
return value, ok
}
//SetMintParam #
func (c *Context) SetMintParam(key string, value interface{}) {
c.HandlerContext.Mint.Set(key, value)
}
// URI gets request uri
func (c *Context) URI() string {
return c.Req.RequestURI
}