-
Notifications
You must be signed in to change notification settings - Fork 27
/
context.go
766 lines (677 loc) · 18 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
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
package baa
import (
"bufio"
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"html/template"
"io"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
)
var (
// ErrJSONPayloadEmpty is returned when the JSON payload is empty.
ErrJSONPayloadEmpty = errors.New("JSON payload is empty")
// ErrXMLPayloadEmpty is returned when the XML payload is empty.
ErrXMLPayloadEmpty = errors.New("XML payload is empty")
)
const (
// defaultMaxMemory Maximum amount of memory to use when parsing a multipart form.
// Set this to whatever value you prefer; default is 32 MB.
defaultMaxMemory = 32 << 20 // 32 MB
// CharsetUTF8 ...
CharsetUTF8 = "charset=utf-8"
// MediaTypes
ApplicationJSON = "application/json"
ApplicationJSONCharsetUTF8 = ApplicationJSON + "; " + CharsetUTF8
ApplicationJavaScript = "application/javascript"
ApplicationJavaScriptCharsetUTF8 = ApplicationJavaScript + "; " + CharsetUTF8
ApplicationXML = "application/xml"
ApplicationXMLCharsetUTF8 = ApplicationXML + "; " + CharsetUTF8
ApplicationForm = "application/x-www-form-urlencoded"
ApplicationProtobuf = "application/protobuf"
TextHTML = "text/html"
TextHTMLCharsetUTF8 = TextHTML + "; " + CharsetUTF8
TextPlain = "text/plain"
TextPlainCharsetUTF8 = TextPlain + "; " + CharsetUTF8
MultipartForm = "multipart/form-data"
)
// Context provlider a HTTP context for baa
// context contains reqest, response, header, cookie and some content type.
type Context struct {
Req *http.Request
Resp *Response
baa *Baa
store map[string]interface{}
storeMutex sync.RWMutex // store rw lock
routeName string // route name
pNames []string // route params names
pValues []string // route params values
handlers []HandlerFunc // middleware handler and route match handler
hi int // handlers execute position
}
// NewContext create a http context
func NewContext(w http.ResponseWriter, r *http.Request, b *Baa) *Context {
c := new(Context)
c.Resp = NewResponse(w, b)
c.baa = b
c.pNames = make([]string, 0, 16)
c.pValues = make([]string, 0, 16)
c.handlers = make([]HandlerFunc, len(b.middleware), len(b.middleware)+3)
copy(c.handlers, b.middleware)
c.Reset(w, r)
return c
}
// RouteName return context matched route name
func (c *Context) RouteName() string {
return c.routeName
}
// Reset ...
func (c *Context) Reset(w http.ResponseWriter, r *http.Request) {
c.Resp.reset(w)
c.Req = r
c.hi = 0
c.handlers = c.handlers[:len(c.baa.middleware)]
c.routeName = ""
c.pNames = c.pNames[:0]
c.pValues = c.pValues[:0]
c.storeMutex.Lock()
c.store = nil
c.storeMutex.Unlock()
}
// Set store data in context
func (c *Context) Set(key string, v interface{}) {
c.storeMutex.Lock()
if c.store == nil {
c.store = make(map[string]interface{})
}
c.store[key] = v
c.storeMutex.Unlock()
}
// Get returns data from context
func (c *Context) Get(key string) interface{} {
c.storeMutex.RLock()
defer c.storeMutex.RUnlock()
if c.store == nil {
return nil
}
return c.store[key]
}
// Gets returns data map from content store
func (c *Context) Gets() map[string]interface{} {
c.storeMutex.RLock()
vals := make(map[string]interface{})
for k, v := range c.store {
vals[k] = v
}
c.storeMutex.RUnlock()
return vals
}
// SetParam read route param value from uri
func (c *Context) SetParam(name, value string) {
c.pNames = append(c.pNames, name)
c.pValues = append(c.pValues, value)
}
// Param get route param from context
func (c *Context) Param(name string) string {
for i := len(c.pNames) - 1; i >= 0; i-- {
if c.pNames[i] == name {
return c.pValues[i]
}
}
return ""
}
// Params returns route params from context
func (c *Context) Params() map[string]string {
m := make(map[string]string)
for i := 0; i < len(c.pNames); i++ {
m[c.pNames[i]] = c.pValues[i]
}
return m
}
// ParamInt get route param from context and format to int
func (c *Context) ParamInt(name string) int {
v, _ := strconv.Atoi(c.Param(name))
return v
}
// ParamInt32 get route param from context and format to int32
func (c *Context) ParamInt32(name string) int32 {
return int32(c.ParamInt64(name))
}
// ParamInt64 get route param from context and format to int64
func (c *Context) ParamInt64(name string) int64 {
v, _ := strconv.ParseInt(c.Param(name), 10, 64)
return v
}
// ParamFloat get route param from context and format to float64
func (c *Context) ParamFloat(name string) float64 {
v, _ := strconv.ParseFloat(c.Param(name), 64)
return v
}
// ParamBool get route param from context and format to bool
func (c *Context) ParamBool(name string) bool {
v, _ := strconv.ParseBool(c.Param(name))
return v
}
// Query get a param from http.Request.Form
func (c *Context) Query(name string) string {
c.ParseForm(0)
return c.Req.Form.Get(name)
}
// QueryTrim querys and trims spaces form parameter.
func (c *Context) QueryTrim(name string) string {
c.ParseForm(0)
return strings.TrimSpace(c.Req.Form.Get(name))
}
// QueryStrings get a group param from http.Request.Form and format to string slice
func (c *Context) QueryStrings(name string) []string {
c.ParseForm(0)
if v, ok := c.Req.Form[name]; ok {
return v
}
return []string{}
}
// QueryEscape returns escapred query result.
func (c *Context) QueryEscape(name string) string {
c.ParseForm(0)
return template.HTMLEscapeString(c.Req.Form.Get(name))
}
// QueryInt get a param from http.Request.Form and format to int
func (c *Context) QueryInt(name string) int {
c.ParseForm(0)
v, _ := strconv.Atoi(c.Req.Form.Get(name))
return v
}
// QueryInt32 get a param from http.Request.Form and format to int32
func (c *Context) QueryInt32(name string) int32 {
return int32(c.QueryInt64(name))
}
// QueryInt64 get a param from http.Request.Form and format to int64
func (c *Context) QueryInt64(name string) int64 {
c.ParseForm(0)
v, _ := strconv.ParseInt(c.Req.Form.Get(name), 10, 64)
return v
}
// QueryFloat get a param from http.Request.Form and format to float64
func (c *Context) QueryFloat(name string) float64 {
c.ParseForm(0)
v, _ := strconv.ParseFloat(c.Req.Form.Get(name), 64)
return v
}
// QueryBool get a param from http.Request.Form and format to bool
func (c *Context) QueryBool(name string) bool {
c.ParseForm(0)
v, _ := strconv.ParseBool(c.Req.Form.Get(name))
return v
}
// Querys return http.Request.URL queryString data
func (c *Context) Querys() map[string]interface{} {
params := make(map[string]interface{})
var newValues url.Values
if c.Req.URL != nil {
newValues, _ = url.ParseQuery(c.Req.URL.RawQuery)
}
for k, v := range newValues {
if len(v) > 1 {
params[k] = v
} else {
params[k] = v[0]
}
}
return params
}
// Posts return http.Request form data
func (c *Context) Posts() map[string]interface{} {
if err := c.ParseForm(0); err != nil {
return nil
}
params := make(map[string]interface{})
data := c.Req.PostForm
if len(data) == 0 && len(c.Req.Form) > 0 {
data = c.Req.Form
}
for k, v := range data {
if len(v) > 1 {
params[k] = v
} else {
params[k] = v[0]
}
}
return params
}
// QueryJSON decode json from http.Request.Body
func (c *Context) QueryJSON(v interface{}) error {
content, err := c.Body().Bytes()
if err != nil {
return err
}
if len(content) == 0 {
return ErrJSONPayloadEmpty
}
return json.Unmarshal(content, v)
}
// QueryXML decode xml from http.Request.Body
func (c *Context) QueryXML(v interface{}) error {
content, err := c.Body().Bytes()
if err != nil {
return err
}
if len(content) == 0 {
return ErrXMLPayloadEmpty
}
return xml.Unmarshal(content, v)
}
// GetFile returns information about user upload file by given form field name.
func (c *Context) GetFile(name string) (multipart.File, *multipart.FileHeader, error) {
if err := c.ParseForm(0); err != nil {
return nil, nil, err
}
return c.Req.FormFile(name)
}
// SaveToFile reads a file from request by field name and saves to given path.
func (c *Context) SaveToFile(name, savePath string) error {
fr, _, err := c.GetFile(name)
if err != nil {
return err
}
defer fr.Close()
fw, err := os.OpenFile(savePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return err
}
defer fw.Close()
_, err = io.Copy(fw, fr)
return err
}
// Body get raw request body and return RequestBody
func (c *Context) Body() *RequestBody {
return NewRequestBody(c.Req.Body)
}
// SetCookie sets given cookie value to response header.
// full params example:
// SetCookie(<name>, <value>, <max age>, <path>, <domain>, <secure>, <http only>)
func (c *Context) SetCookie(name string, value string, others ...interface{}) {
cookie := http.Cookie{}
cookie.Name = name
cookie.Value = url.QueryEscape(value)
if len(others) > 0 {
switch v := others[0].(type) {
case int:
cookie.MaxAge = v
case int64:
cookie.MaxAge = int(v)
case int32:
cookie.MaxAge = int(v)
}
}
cookie.Path = "/"
if len(others) > 1 {
if v, ok := others[1].(string); ok && len(v) > 0 {
cookie.Path = v
}
}
if len(others) > 2 {
if v, ok := others[2].(string); ok && len(v) > 0 {
cookie.Domain = v
}
}
if len(others) > 3 {
switch v := others[3].(type) {
case bool:
cookie.Secure = v
default:
if others[3] != nil {
cookie.Secure = true
}
}
}
if len(others) > 4 {
if v, ok := others[4].(bool); ok && v {
cookie.HttpOnly = true
}
}
c.Resp.Header().Add("Set-Cookie", cookie.String())
}
// GetCookie returns given cookie value from request header.
func (c *Context) GetCookie(name string) string {
cookie, err := c.Req.Cookie(name)
if err != nil {
return ""
}
v, _ := url.QueryUnescape(cookie.Value)
return v
}
// GetCookieInt returns cookie result in int type.
func (c *Context) GetCookieInt(name string) int {
v, _ := strconv.Atoi(c.GetCookie(name))
return v
}
// GetCookieInt32 returns cookie result in int32 type.
func (c *Context) GetCookieInt32(name string) int32 {
return int32(c.GetCookieInt64(name))
}
// GetCookieInt64 returns cookie result in int64 type.
func (c *Context) GetCookieInt64(name string) int64 {
v, _ := strconv.ParseInt(c.GetCookie(name), 10, 64)
return v
}
// GetCookieFloat64 returns cookie result in float64 type.
func (c *Context) GetCookieFloat64(name string) float64 {
v, _ := strconv.ParseFloat(c.GetCookie(name), 64)
return v
}
// GetCookieBool returns cookie result in float64 type.
func (c *Context) GetCookieBool(name string) bool {
v, _ := strconv.ParseBool(c.GetCookie(name))
return v
}
// String write text by string
func (c *Context) String(code int, s string) {
c.Resp.Header().Set("Content-Type", TextPlainCharsetUTF8)
c.Resp.WriteHeader(code)
c.Resp.Write([]byte(s))
}
// Text write text by []byte
func (c *Context) Text(code int, s []byte) {
c.Resp.Header().Set("Content-Type", TextHTMLCharsetUTF8)
c.Resp.WriteHeader(code)
c.Resp.Write(s)
}
// JSON write data by json format
func (c *Context) JSON(code int, v interface{}) {
var re []byte
var err error
if c.baa.debug {
re, err = json.MarshalIndent(v, "", " ")
} else {
re, err = json.Marshal(v)
}
if err != nil {
c.Error(err)
return
}
c.Resp.Header().Set("Content-Type", ApplicationJSONCharsetUTF8)
c.Resp.WriteHeader(code)
c.Resp.Write(re)
}
// JSONString return string by Marshal interface
func (c *Context) JSONString(v interface{}) (string, error) {
var re []byte
var err error
if c.baa.debug {
re, err = json.MarshalIndent(v, "", " ")
} else {
re, err = json.Marshal(v)
}
if err != nil {
return "", err
}
return string(re), nil
}
// JSONP write data by jsonp format
func (c *Context) JSONP(code int, callback string, v interface{}) {
re, err := json.Marshal(v)
if err != nil {
c.Error(err)
return
}
c.Resp.Header().Set("Content-Type", ApplicationJavaScriptCharsetUTF8)
c.Resp.WriteHeader(code)
c.Resp.Write([]byte(callback + "("))
c.Resp.Write(re)
c.Resp.Write([]byte(");"))
}
// XML sends an XML response with status code.
func (c *Context) XML(code int, v interface{}) {
var re []byte
var err error
if c.baa.debug {
re, err = xml.MarshalIndent(v, "", " ")
} else {
re, err = xml.Marshal(v)
}
if err != nil {
c.Error(err)
return
}
c.Resp.Header().Set("Content-Type", ApplicationXMLCharsetUTF8)
c.Resp.WriteHeader(code)
c.Resp.Write([]byte(xml.Header))
c.Resp.Write(re)
}
// HTML write render data by html template engine use context.store
// it is a alias of c.Render
func (c *Context) HTML(code int, tpl string) {
c.Render(code, tpl)
}
// Render write render data by html template engine use context.store
func (c *Context) Render(code int, tpl string) {
re, err := c.Fetch(tpl)
if err != nil {
c.Error(err)
return
}
c.Resp.Header().Set("Content-Type", TextHTMLCharsetUTF8)
c.Resp.WriteHeader(code)
c.Resp.Write(re)
}
// Fetch render data by html template engine use context.store and returns data
func (c *Context) Fetch(tpl string) ([]byte, error) {
buf := new(bytes.Buffer)
if err := c.baa.Render().Render(buf, tpl, c.Gets()); err != nil {
return nil, err
}
// clear go template generated black lines
nbuf := new(bytes.Buffer)
r := bufio.NewReader(buf)
for {
line, _, err := r.ReadLine()
if err != nil {
break
}
clearLine := strings.TrimSpace(string(line))
if len(clearLine) == 0 {
continue
}
nbuf.Write(line)
nbuf.WriteRune('\n')
}
return nbuf.Bytes(), nil
}
// Redirect redirects the request using http.Redirect with status code.
func (c *Context) Redirect(code int, url string) error {
if code < http.StatusMultipleChoices || code > http.StatusTemporaryRedirect {
return fmt.Errorf("invalid redirect status code")
}
http.Redirect(c.Resp, c.Req, url, code)
return nil
}
// RemoteAddr returns more real IP address.
func (c *Context) RemoteAddr() string {
var addr string
key := "__ctx_remoteAddr"
if addr, ok := c.Get(key).(string); ok {
return addr
}
for _, k := range []string{"X-Forwarded-For", "Ali-Cdn-Real-Ip", "X-Real-IP"} {
if addr = c.Req.Header.Get(k); addr != "" {
if strings.Contains(addr, ",") {
addrs := strings.Split(addr, ",")
addr = addrs[0]
}
break
}
}
if addr == "" {
addr = c.Req.RemoteAddr
addr, _, _ = net.SplitHostPort(addr)
}
c.Set(key, addr)
return addr
}
// Referer returns http request Referer
func (c *Context) Referer() string {
return c.Req.Header.Get("Referer")
}
// UserAgent returns http request UserAgent
func (c *Context) UserAgent() string {
return c.Req.Header.Get("User-Agent")
}
// URL returns http request full url
func (c *Context) URL(hasQuery bool) string {
scheme := c.Req.URL.Scheme
host := c.Req.URL.Host
if scheme == "" {
if c.Req.TLS != nil {
scheme = "https"
} else {
scheme = "http"
}
}
if host == "" {
host = c.Req.Host
}
if len(host) > 0 {
if host[0] == ':' {
//
} else if host[0] == '/' {
scheme += ":"
} else {
scheme += "://"
}
} else {
scheme = ""
}
if hasQuery {
url := c.Req.RequestURI
if url == "" {
url = c.Req.URL.Path
if len(c.Req.URL.RawQuery) > 0 {
url += "?" + c.Req.URL.RawQuery
}
}
return scheme + host + url
}
return scheme + host + c.Req.URL.Path
}
// IsMobile returns if it is a mobile phone device request
func (c *Context) IsMobile() bool {
userAgent := c.UserAgent()
for _, v := range []string{"iPhone", "iPod", "Android"} {
if strings.Contains(userAgent, v) {
return true
}
}
return false
}
// IsAJAX returns if it is a ajax request
func (c *Context) IsAJAX() bool {
return c.Req.Header.Get("X-Requested-With") == "XMLHttpRequest"
}
// ParseForm parses a request body as multipart/form-data or
// parses the raw query from the URL and updates r.Form.
func (c *Context) ParseForm(maxSize int64) error {
if c.Req.Form != nil {
return nil
}
contentType := c.Req.Header.Get("Content-Type")
if (c.Req.Method == "POST" || c.Req.Method == "PUT") &&
len(contentType) > 0 && strings.Contains(contentType, MultipartForm) {
if maxSize == 0 {
maxSize = defaultMaxMemory
}
return c.Req.ParseMultipartForm(maxSize)
}
return c.Req.ParseForm()
}
// Next execute next handler
// handle middleware first, last execute route handler
// if something wrote to http, break chain and return
func (c *Context) Next() {
if c.hi >= len(c.handlers) {
return
}
if c.Resp.Wrote() {
if c.baa.Debug() {
c.baa.Logger().Println("Warning: content has been written, handle chain break.")
}
return
}
i := c.hi
c.hi++
if c.handlers[i] != nil {
c.handlers[i](c)
} else {
c.Next()
}
}
// Break break the handles chain and Immediate return
func (c *Context) Break() {
c.hi = len(c.handlers)
}
// Error invokes the registered HTTP error handler.
func (c *Context) Error(err error) {
c.baa.Error(err, c)
}
// NotFound invokes the registered HTTP NotFound handler.
func (c *Context) NotFound() {
c.baa.NotFound(c)
}
// Baa get app instance
func (c *Context) Baa() *Baa {
return c.baa
}
// DI get registered dependency injection service
func (c *Context) DI(name string) interface{} {
return c.baa.GetDI(name)
}
/**
implement for context.Context
*/
// Deadline returns that there is no deadline (ok==false) when c.Req has no Context.
func (c *Context) Deadline() (deadline time.Time, ok bool) {
if c.Req == nil || c.Req.Context() == nil {
return
}
return c.Req.Context().Deadline()
}
// Done returns nil (chan which will wait forever) when c.Req has no Context.
func (c *Context) Done() <-chan struct{} {
if c.Req == nil || c.Req.Context() == nil {
return nil
}
return c.Req.Context().Done()
}
// Err returns nil when c.Req has no Context.
func (c *Context) Err() error {
if c.Req == nil || c.Req.Context() == nil {
return nil
}
return c.Req.Context().Err()
}
// Value returns the value associated with this context for key, or nil
// if no value is associated with key. Successive calls to Value with
// the same key returns the same result.
func (c *Context) Value(key interface{}) interface{} {
if key == 0 {
return c.Req
}
if keyAsString, ok := key.(string); ok {
if val := c.Get(keyAsString); val != nil {
return val
}
}
if c.Req == nil || c.Req.Context() == nil {
return nil
}
return c.Req.Context().Value(key)
}