-
Notifications
You must be signed in to change notification settings - Fork 11
/
context.go
888 lines (768 loc) · 20.6 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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
package echo
import (
"bytes"
"encoding/json"
"encoding/xml"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/webx-top/echo/engine"
"github.com/webx-top/echo/logger"
"github.com/webx-top/echo/param"
"golang.org/x/net/context"
)
type (
// Context represents context for the current request. It holds request and
// response objects, path parameters, data and registered handler.
Context interface {
context.Context
Translator
Request() engine.Request
Response() engine.Response
Path() string
P(int) string
Param(string) string
// ParamNames returns path parameter names.
ParamNames() []string
SetParamNames(...string)
ParamValues() []string
SetParamValues(values ...string)
// Queries returns the query parameters as map. It is an alias for `engine.URL#Query()`.
Queries() map[string][]string
QueryValues(string) []string
Query(string) string
Form(string) string
FormValues(string) []string
// Forms returns the form parameters as map. It is an alias for `engine.Request#Form().All()`.
Forms() map[string][]string
Set(string, interface{})
Get(string) interface{}
Stored() store
Bind(interface{}) error
MustBind(interface{}) error
Render(string, interface{}, ...int) error
HTML(string, ...int) error
String(string, ...int) error
JSON(interface{}, ...int) error
JSONBlob([]byte, ...int) error
JSONP(string, interface{}, ...int) error
XML(interface{}, ...int) error
XMLBlob([]byte, ...int) error
File(string) error
Attachment(io.ReadSeeker, string) error
NoContent(...int) error
Redirect(string, ...int) error
Error(err error)
Handle(Context) error
Logger() logger.Logger
Object() *xContext
Echo() *Echo
// ServeContent sends static content from `io.Reader` and handles caching
// via `If-Modified-Since` request header. It automatically sets `Content-Type`
// and `Last-Modified` response headers.
ServeContent(io.ReadSeeker, string, time.Time) error
SetFunc(string, interface{})
GetFunc(string) interface{}
ResetFuncs(map[string]interface{})
Funcs() map[string]interface{}
Reset(engine.Request, engine.Response)
Fetch(string, interface{}) ([]byte, error)
SetRenderer(Renderer)
// Cookie
SetCookieOptions(*CookieOptions)
CookieOptions() *CookieOptions
NewCookie(string, string) *Cookie
Cookie() Cookier
GetCookie(string) string
SetCookie(string, string, ...interface{})
SetSessioner(Sessioner)
Session() Sessioner
Flash(string) interface{}
//with type action
Px(int) param.String
Paramx(string) param.String
Queryx(string) param.String
Formx(string) param.String
//string to param.String
Atop(string) param.String
SetTranslator(Translator)
Header(string) string
IsAjax() bool
Method() string
Format() string
IsPost() bool
IsGet() bool
IsPut() bool
IsDel() bool
IsHead() bool
IsPatch() bool
IsOptions() bool
IsSecure() bool
IsWebsocket() bool
IsUpload() bool
ResolveContentType() string
WithFormatExtension(bool)
ResolveFormat() string
Protocol() string
Site() string
Scheme() string
Domain() string
Host() string
Proxy() []string
Referer() string
Port() int
SetCode(int)
Code() int
NewData(...interface{}) *Data
}
xContext struct {
Translator
sessioner Sessioner
cookier Cookier
context context.Context
request engine.Request
response engine.Response
path string
pnames []string
pvalues []string
store store
handler Handler
echo *Echo
funcs map[string]interface{}
renderer Renderer
cookieOptions *CookieOptions
withFormatExtension bool
format string
code int
}
store map[string]interface{}
)
func (s store) Set(key string, value interface{}) store {
s[key] = value
return s
}
func (s store) Get(key string) interface{} {
if v, y := s[key]; y {
return v
}
return nil
}
// NewContext creates a Context object.
func NewContext(req engine.Request, res engine.Response, e *Echo) Context {
c := &xContext{
Translator: DefaultNopTranslate,
context: context.Background(),
request: req,
response: res,
echo: e,
pvalues: make([]string, *e.maxParam),
store: make(store),
handler: NotFoundHandler,
funcs: make(map[string]interface{}),
sessioner: DefaultNopSession,
}
c.cookier = NewCookier(c)
return c
}
func (c *xContext) Context() context.Context {
return c.context
}
func (c *xContext) SetContext(ctx context.Context) {
c.context = ctx
}
func (c *xContext) Deadline() (deadline time.Time, ok bool) {
return c.context.Deadline()
}
func (c *xContext) Done() <-chan struct{} {
return c.context.Done()
}
func (c *xContext) Err() error {
return c.context.Err()
}
func (c *xContext) Value(key interface{}) interface{} {
return c.context.Value(key)
}
func (c *xContext) Handle(ctx Context) error {
return c.handler.Handle(ctx)
}
// Request returns *http.Request.
func (c *xContext) Request() engine.Request {
return c.request
}
// Response returns *Response.
func (c *xContext) Response() engine.Response {
return c.response
}
// Path returns the registered path for the handler.
func (c *xContext) Path() string {
return c.path
}
// P returns path parameter by index.
func (c *xContext) P(i int) (value string) {
l := len(c.pnames)
if i < l {
value = c.pvalues[i]
}
return
}
// Param returns path parameter by name.
func (c *xContext) Param(name string) (value string) {
l := len(c.pnames)
for i, n := range c.pnames {
if n == name && i < l {
value = c.pvalues[i]
break
}
}
return
}
func (c *xContext) ParamNames() []string {
return c.pnames
}
func (c *xContext) SetParamNames(names ...string) {
c.pnames = names
}
func (c *xContext) ParamValues() []string {
return c.pvalues
}
func (c *xContext) SetParamValues(values ...string) {
c.pvalues = values
}
// Query returns query parameter by name.
func (c *xContext) Query(name string) string {
return c.request.URL().QueryValue(name)
}
func (c *xContext) QueryValues(name string) []string {
return c.request.URL().QueryValues(name)
}
func (c *xContext) Queries() map[string][]string {
return c.request.URL().Query()
}
// Form returns form parameter by name.
func (c *xContext) Form(name string) string {
return c.request.FormValue(name)
}
func (c *xContext) FormValues(name string) []string {
return c.request.Form().Gets(name)
}
func (c *xContext) Forms() map[string][]string {
return c.request.Form().All()
}
// Get retrieves data from the context.
func (c *xContext) Get(key string) interface{} {
return c.store[key]
}
// Set saves data in the context.
func (c *xContext) Set(key string, val interface{}) {
c.store[key] = val
}
func (c *xContext) Stored() store {
return c.store
}
// Bind binds the request body into specified type `i`. The default binder does
// it based on Content-Type header.
func (c *xContext) Bind(i interface{}) error {
return c.echo.binder.Bind(i, c)
}
func (c *xContext) MustBind(i interface{}) error {
return c.echo.binder.MustBind(i, c)
}
// Render renders a template with data and sends a text/html response with status
// code. Templates can be registered using `Echo.SetRenderer()`.
func (c *xContext) Render(name string, data interface{}, codes ...int) (err error) {
if len(codes) > 0 {
c.code = codes[0]
}
if c.code == 0 {
c.code = http.StatusOK
}
b, err := c.Fetch(name, data)
if err != nil {
return
}
c.response.Header().Set(HeaderContentType, MIMETextHTMLCharsetUTF8)
c.response.WriteHeader(c.code)
_, err = c.response.Write(b)
return
}
// HTML sends an HTTP response with status code.
func (c *xContext) HTML(html string, codes ...int) (err error) {
if len(codes) > 0 {
c.code = codes[0]
}
if c.code == 0 {
c.code = http.StatusOK
}
c.response.Header().Set(HeaderContentType, MIMETextHTMLCharsetUTF8)
c.response.WriteHeader(c.code)
_, err = c.response.Write([]byte(html))
return
}
// String sends a string response with status code.
func (c *xContext) String(s string, codes ...int) (err error) {
if len(codes) > 0 {
c.code = codes[0]
}
if c.code == 0 {
c.code = http.StatusOK
}
c.response.Header().Set(HeaderContentType, MIMETextPlainCharsetUTF8)
c.response.WriteHeader(c.code)
_, err = c.response.Write([]byte(s))
return
}
// JSON sends a JSON response with status code.
func (c *xContext) JSON(i interface{}, codes ...int) (err error) {
var b []byte
if c.echo.Debug() {
b, err = json.MarshalIndent(i, "", " ")
} else {
b, err = json.Marshal(i)
}
if err != nil {
return err
}
return c.JSONBlob(b, codes...)
}
// JSONBlob sends a JSON blob response with status code.
func (c *xContext) JSONBlob(b []byte, codes ...int) (err error) {
if len(codes) > 0 {
c.code = codes[0]
}
if c.code == 0 {
c.code = http.StatusOK
}
c.response.Header().Set(HeaderContentType, MIMEApplicationJSONCharsetUTF8)
c.response.WriteHeader(c.code)
_, err = c.response.Write(b)
return
}
// JSONP sends a JSONP response with status code. It uses `callback` to construct
// the JSONP payload.
func (c *xContext) JSONP(callback string, i interface{}, codes ...int) (err error) {
if len(codes) > 0 {
c.code = codes[0]
}
if c.code == 0 {
c.code = http.StatusOK
}
b, err := json.Marshal(i)
if err != nil {
return err
}
c.response.Header().Set(HeaderContentType, MIMEApplicationJavaScriptCharsetUTF8)
c.response.WriteHeader(c.code)
if _, err = c.response.Write([]byte(callback + "(")); err != nil {
return
}
if _, err = c.response.Write(b); err != nil {
return
}
_, err = c.response.Write([]byte(");"))
return
}
// XML sends an XML response with status code.
func (c *xContext) XML(i interface{}, codes ...int) (err error) {
var b []byte
if c.echo.Debug() {
b, err = xml.MarshalIndent(i, "", " ")
} else {
b, err = xml.Marshal(i)
}
if err != nil {
return err
}
return c.XMLBlob(b, codes...)
}
// XMLBlob sends a XML blob response with status code.
func (c *xContext) XMLBlob(b []byte, codes ...int) (err error) {
if len(codes) > 0 {
c.code = codes[0]
}
if c.code == 0 {
c.code = http.StatusOK
}
c.response.Header().Set(HeaderContentType, MIMEApplicationXMLCharsetUTF8)
c.response.WriteHeader(c.code)
if _, err = c.response.Write([]byte(xml.Header)); err != nil {
return
}
_, err = c.response.Write(b)
return
}
func (c *xContext) File(file string) error {
f, err := os.Open(file)
if err != nil {
return ErrNotFound
}
defer f.Close()
fi, _ := f.Stat()
if fi.IsDir() {
file = filepath.Join(file, "index.html")
f, err = os.Open(file)
if err != nil {
return ErrNotFound
}
fi, _ = f.Stat()
}
return c.ServeContent(f, fi.Name(), fi.ModTime())
}
func (c *xContext) Attachment(r io.ReadSeeker, name string) (err error) {
c.response.Header().Set(HeaderContentType, ContentTypeByExtension(name))
c.response.Header().Set(HeaderContentDisposition, "attachment; filename="+name)
c.response.WriteHeader(http.StatusOK)
_, err = io.Copy(c.response, r)
return
}
// NoContent sends a response with no body and a status code.
func (c *xContext) NoContent(codes ...int) error {
if len(codes) > 0 {
c.code = codes[0]
}
if c.code == 0 {
c.code = http.StatusOK
}
c.response.WriteHeader(c.code)
return nil
}
// Redirect redirects the request with status code.
func (c *xContext) Redirect(url string, codes ...int) error {
code := http.StatusFound
if len(codes) > 0 {
code = codes[0]
}
if code < http.StatusMultipleChoices || code > http.StatusTemporaryRedirect {
return ErrInvalidRedirectCode
}
c.response.Redirect(url, code)
return nil
}
// Error invokes the registered HTTP error handler. Generally used by middleware.
func (c *xContext) Error(err error) {
c.echo.httpErrorHandler(err, c)
}
// Logger returns the `Logger` instance.
func (c *xContext) Logger() logger.Logger {
return c.echo.logger
}
// Object returns the `context` object.
func (c *xContext) Object() *xContext {
return c
}
func (c *xContext) ServeContent(content io.ReadSeeker, name string, modtime time.Time) error {
rq := c.Request()
rs := c.Response()
if t, err := time.Parse(http.TimeFormat, rq.Header().Get(HeaderIfModifiedSince)); err == nil && modtime.Before(t.Add(1*time.Second)) {
rs.Header().Del(HeaderContentType)
rs.Header().Del(HeaderContentLength)
return c.NoContent(http.StatusNotModified)
}
rs.Header().Set(HeaderContentType, ContentTypeByExtension(name))
rs.Header().Set(HeaderLastModified, modtime.UTC().Format(http.TimeFormat))
rs.WriteHeader(http.StatusOK)
_, err := io.Copy(rs, content)
return err
}
// ContentTypeByExtension returns the MIME type associated with the file based on
// its extension. It returns `application/octet-stream` incase MIME type is not
// found.
func ContentTypeByExtension(name string) (t string) {
if t = mime.TypeByExtension(filepath.Ext(name)); len(t) == 0 {
t = MIMEOctetStream
}
return
}
// Echo returns the `Echo` instance.
func (c *xContext) Echo() *Echo {
return c.echo
}
func (c *xContext) SetTranslator(t Translator) {
c.Translator = t
}
func (c *xContext) Reset(req engine.Request, res engine.Response) {
c.Translator = DefaultNopTranslate
c.sessioner = DefaultNopSession
c.context = context.Background()
c.request = req
c.response = res
c.store = make(store)
c.funcs = make(map[string]interface{})
c.renderer = nil
c.handler = NotFoundHandler
c.cookieOptions = nil
c.withFormatExtension = false
c.format = ""
c.code = 0
}
func (c *xContext) GetFunc(key string) interface{} {
return c.funcs[key]
}
func (c *xContext) SetFunc(key string, val interface{}) {
c.funcs[key] = val
}
func (c *xContext) ResetFuncs(funcs map[string]interface{}) {
c.funcs = funcs
}
func (c *xContext) Funcs() map[string]interface{} {
return c.funcs
}
func (c *xContext) Fetch(name string, data interface{}) (b []byte, err error) {
if c.renderer == nil {
if c.echo.renderer == nil {
return nil, ErrRendererNotRegistered
}
c.renderer = c.echo.renderer
}
buf := new(bytes.Buffer)
err = c.renderer.Render(buf, name, data, c)
if err != nil {
return
}
b = buf.Bytes()
return
}
// SetRenderer registers an HTML template renderer.
func (c *xContext) SetRenderer(r Renderer) {
c.renderer = r
}
func (c *xContext) SetSessioner(s Sessioner) {
c.sessioner = s
}
func (c *xContext) Session() Sessioner {
return c.sessioner
}
func (c *xContext) Flash(name string) (r interface{}) {
if v := c.sessioner.Flashes(name); len(v) > 0 {
r = v[0]
}
return r
}
func (c *xContext) SetCookieOptions(opts *CookieOptions) {
c.cookieOptions = opts
}
func (c *xContext) CookieOptions() *CookieOptions {
if c.cookieOptions == nil {
c.cookieOptions = &CookieOptions{}
}
return c.cookieOptions
}
func (c *xContext) NewCookie(key string, value string) *Cookie {
return NewCookie(key, value, c.CookieOptions())
}
func (c *xContext) Cookie() Cookier {
return c.cookier
}
func (c *xContext) GetCookie(key string) string {
return c.cookier.Get(key)
}
func (c *xContext) SetCookie(key string, val string, args ...interface{}) {
c.cookier.Set(key, val, args...)
}
func (c *xContext) Px(n int) param.String {
return param.String(c.P(n))
}
func (c *xContext) Paramx(name string) param.String {
return param.String(c.Param(name))
}
func (c *xContext) Queryx(name string) param.String {
return param.String(c.Query(name))
}
func (c *xContext) Formx(name string) param.String {
return param.String(c.Form(name))
}
func (c *xContext) Atop(v string) param.String {
return param.String(v)
}
func (c *xContext) Header(name string) string {
return c.Request().Header().Get(name)
}
func (c *xContext) IsAjax() bool {
return c.Header(`X-Requested-With`) == `XMLHttpRequest`
}
func (c *xContext) Method() string {
return c.Request().Method()
}
func (c *xContext) Format() string {
if len(c.format) == 0 {
c.format = c.ResolveFormat()
}
return c.format
}
// IsPost CREATE:在服务器新建一个资源
func (c *xContext) IsPost() bool {
return c.Method() == POST
}
// IsGet SELECT:从服务器取出资源(一项或多项)
func (c *xContext) IsGet() bool {
return c.Method() == GET
}
// IsPut UPDATE:在服务器更新资源(客户端提供改变后的完整资源)
func (c *xContext) IsPut() bool {
return c.Method() == PUT
}
// IsDel DELETE:从服务器删除资源
func (c *xContext) IsDel() bool {
return c.Method() == DELETE
}
// IsHead 获取资源的元数据
func (c *xContext) IsHead() bool {
return c.Method() == HEAD
}
//IsPatch UPDATE:在服务器更新资源(客户端提供改变的属性)
func (c *xContext) IsPatch() bool {
return c.Method() == PATCH
}
// IsOptions 获取信息,关于资源的哪些属性是客户端可以改变的
func (c *xContext) IsOptions() bool {
return c.Method() == OPTIONS
}
func (c *xContext) IsSecure() bool {
return c.Scheme() == `https`
}
// IsWebsocket returns boolean of this request is in webSocket.
func (c *xContext) IsWebsocket() bool {
return c.Header(`Upgrade`) == `websocket`
}
// IsUpload returns boolean of whether file uploads in this request or not..
func (c *xContext) IsUpload() bool {
return strings.Contains(c.Header(`Content-Type`), `multipart/form-data`)
}
// ResolveContentType Get the content type.
// e.g. From `multipart/form-data; boundary=--` to `multipart/form-data`
// If none is specified, returns `text/html` by default.
func (c *xContext) ResolveContentType() string {
contentType := c.Header(`Content-Type`)
if len(contentType) == 0 {
return `text/html`
}
return strings.ToLower(strings.TrimSpace(strings.SplitN(contentType, `;`, 2)[0]))
}
func (c *xContext) WithFormatExtension(on bool) {
c.withFormatExtension = on
}
// ResolveFormat maps the request's Accept MIME type declaration to
// a Request.Format attribute, specifically `html`, `xml`, `json`, or `txt`,
// returning a default of `html` when Accept header cannot be mapped to a
// value above.
func (c *xContext) ResolveFormat() string {
if format := c.Query(`format`); len(format) > 0 {
return format
}
if c.withFormatExtension {
urlPath := c.Request().URL().Path()
if pos := strings.LastIndex(urlPath, `.`); pos > -1 {
return strings.ToLower(urlPath[pos+1:])
}
}
accept := c.Header(`Accept`)
switch {
case accept == ``,
strings.HasPrefix(accept, `*/*`), // */
strings.HasPrefix(accept, `application/xhtml`),
strings.HasPrefix(accept, `text/html`):
return `html`
case strings.HasPrefix(accept, `application/json`),
strings.HasPrefix(accept, `text/javascript`),
strings.HasPrefix(accept, `application/javascript`):
return `json`
case strings.HasPrefix(accept, `application/xml`),
strings.HasPrefix(accept, `text/xml`):
return `xml`
case strings.HasPrefix(accept, `text/plain`):
return `text`
}
return `html`
}
// Protocol returns request protocol name, such as HTTP/1.1 .
func (c *xContext) Protocol() string {
return c.Request().Proto()
}
// Site returns base site url as scheme://domain type.
func (c *xContext) Site() string {
return c.Scheme() + `://` + c.Domain()
}
// Scheme returns request scheme as `http` or `https`.
func (c *xContext) Scheme() string {
if c.Request().Scheme() != `` {
return c.Request().Scheme()
}
if c.Request().IsTLS() == false {
return `http`
}
return `https`
}
// Domain returns host name.
// Alias of Host method.
func (c *xContext) Domain() string {
return c.Host()
}
// Host returns host name.
// if no host info in request, return localhost.
func (c *xContext) Host() string {
host := c.Request().Host()
if len(host) > 0 {
delim := `:`
if host[0] == '[' {
host = strings.TrimPrefix(host, `[`)
delim = `]:`
}
hostParts := strings.SplitN(host, delim, 2)
if len(hostParts) > 0 {
return hostParts[0]
}
return host
}
return `localhost`
}
// Proxy returns proxy client ips slice.
func (c *xContext) Proxy() []string {
if ips := c.Header(`X-Forwarded-For`); len(ips) > 0 {
return strings.Split(ips, `,`)
}
return []string{}
}
// Referer returns http referer header.
func (c *xContext) Referer() string {
return c.Header(`Referer`)
}
// Port returns request client port.
// when error or empty, return 80.
func (c *xContext) Port() int {
host := c.Request().Host()
delim := `:`
if len(host) > 0 && host[0] == '[' {
delim = `]:`
}
parts := strings.SplitN(host, delim, 2)
if len(parts) > 1 {
port, _ := strconv.Atoi(parts[1])
return port
}
return 80
}
func (c *xContext) SetCode(code int) {
c.code = code
}
func (c *xContext) Code() int {
return c.code
}
func (c *xContext) NewData(args ...interface{}) *Data {
length := len(args)
if length > 1 {
if code, ok := args[0].(int); ok {
return NewData(code, args[1:]...)
}
} else if length == 1 {
if code, ok := args[0].(int); ok {
return NewData(code)
} else if mapd, ok := args[0].(H); ok {
return mapd.ToData()
}
}
return &Data{}
}