forked from kataras/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
1860 lines (1630 loc) · 66.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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package iris
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
"os"
"path"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/iris-contrib/formBinder"
"github.com/kataras/go-errors"
)
const (
// ContentType represents the header["Content-Type"]
contentType = "Content-Type"
// ContentLength represents the header["Content-Length"]
contentLength = "Content-Length"
// contentEncodingHeader represents the header["Content-Encoding"]
contentEncodingHeader = "Content-Encoding"
// varyHeader represents the header "Vary"
varyHeader = "Vary"
// acceptEncodingHeader represents the header key & value "Accept-Encoding"
acceptEncodingHeader = "Accept-Encoding"
// ContentHTML is the string of text/html response headers
contentHTML = "text/html"
// ContentBinary header value for binary data.
contentBinary = "application/octet-stream"
// ContentJSON header value for JSON data.
contentJSON = "application/json"
// ContentJSONP header value for JSONP & Javascript data.
contentJSONP = "application/javascript"
// ContentJavascript header value for Javascript/JSONP
// conversional
contentJavascript = "application/javascript"
// ContentText header value for Text data.
contentText = "text/plain"
// ContentXML header value for XML data.
contentXML = "text/xml"
// contentMarkdown custom key/content type, the real is the text/html
contentMarkdown = "text/markdown"
// LastModified "Last-Modified"
lastModified = "Last-Modified"
// IfModifiedSince "If-Modified-Since"
ifModifiedSince = "If-Modified-Since"
// ContentDisposition "Content-Disposition"
contentDisposition = "Content-Disposition"
// CacheControl "Cache-Control"
cacheControl = "Cache-Control"
// stopExecutionPosition used inside the Context, is the number which shows us that the context's middleware manually stop the execution
stopExecutionPosition = 255
)
type (
requestValue struct {
key []byte
value interface{}
}
requestValues []requestValue
)
func (r *requestValues) Set(key string, value interface{}) {
args := *r
n := len(args)
for i := 0; i < n; i++ {
kv := &args[i]
if string(kv.key) == key {
kv.value = value
return
}
}
c := cap(args)
if c > n {
args = args[:n+1]
kv := &args[n]
kv.key = append(kv.key[:0], key...)
kv.value = value
*r = args
return
}
kv := requestValue{}
kv.key = append(kv.key[:0], key...)
kv.value = value
*r = append(args, kv)
}
func (r *requestValues) Get(key string) interface{} {
args := *r
n := len(args)
for i := 0; i < n; i++ {
kv := &args[i]
if string(kv.key) == key {
return kv.value
}
}
return nil
}
func (r *requestValues) Reset() {
*r = (*r)[:0]
}
type (
// ContextPool is a set of temporary *Context that may be individually saved and
// retrieved.
//
// Any item stored in the Pool may be removed automatically at any time without
// notification. If the Pool holds the only reference when this happens, the
// item might be deallocated.
//
// The ContextPool is safe for use by multiple goroutines simultaneously.
//
// ContextPool's purpose is to cache allocated but unused Contexts for later reuse,
// relieving pressure on the garbage collector.
ContextPool interface {
// Acquire returns a Context from pool.
// See Release.
Acquire(w http.ResponseWriter, r *http.Request) *Context
// Release puts a Context back to its pull, this function releases its resources.
// See Acquire.
Release(ctx *Context)
// Framework is never used, except when you're in a place where you don't have access to the *iris.Framework station
// but you need to fire a func or check its Config.
//
// Used mostly inside external routers to take the .Config.VHost
// without the need of other param receivers and refactors when changes
//
// note: we could make a variable inside contextPool which would be received by newContextPool
// but really doesn't need, we just need to borrow a context: we are in pre-build state
// so the server is not actually running yet, no runtime performance cost.
Framework() *Framework
// Run is a combination of Acquire and Release , between these two the `runner` runs,
// when `runner` finishes its job then the Context is being released.
Run(w http.ResponseWriter, r *http.Request, runner func(ctx *Context))
}
contextPool struct {
pool sync.Pool
}
)
var _ ContextPool = &contextPool{}
func (c *contextPool) Acquire(w http.ResponseWriter, r *http.Request) *Context {
ctx := c.pool.Get().(*Context)
ctx.Middleware = nil
ctx.session = nil
ctx.ResponseWriter = acquireResponseWriter(w)
ctx.Request = r
ctx.values = ctx.values[0:0]
return ctx
}
func (c *contextPool) Release(ctx *Context) {
// flush the body (on recorder) or just the status code (on basic response writer)
// when all finished
ctx.ResponseWriter.flushResponse()
///TODO:
ctx.ResponseWriter.releaseMe()
c.pool.Put(ctx)
}
func (c *contextPool) Framework() *Framework {
ctx := c.pool.Get().(*Context)
s := ctx.framework
c.pool.Put(ctx)
return s
}
func (c *contextPool) Run(w http.ResponseWriter, r *http.Request, runner func(*Context)) {
ctx := c.Acquire(w, r)
runner(ctx)
c.Release(ctx)
}
type (
// Map is just a conversion for a map[string]interface{}
Map map[string]interface{}
// Context is the "midle-man"" server's object for the clients.
//
// A New Context is being acquired from a sync.Pool on each connection.
// The Context is the most important thing on the Iris' http flow.
//
// Developers send responses to the client's request through a Context.
// Developers get request information from the client's request a Context.
Context struct {
ResponseWriter // *responseWriter by default, when record is on then *ResponseRecorder
Request *http.Request
values requestValues
framework *Framework
//keep track all registered middleware (handlers)
Middleware Middleware // exported because is useful for debugging
session Session
// Pos is the position number of the Context, look .Next to understand
Pos int // exported because is useful for debugging
}
)
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// -----------------------------Handler(s) Execution------------------------------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// Do calls the first handler only, it's like Next with negative pos, used only on Router&MemoryRouter
func (ctx *Context) Do() {
ctx.Pos = 0
ctx.Middleware[0].Serve(ctx)
}
// Next calls all the next handler from the middleware stack, it used inside a middleware
func (ctx *Context) Next() {
//set position to the next
ctx.Pos++
//run the next
if ctx.Pos < len(ctx.Middleware) {
ctx.Middleware[ctx.Pos].Serve(ctx)
}
}
// NextHandler returns the next handler in the chain (ctx.Middleware)
// otherwise nil.
// Notes:
// If the result of NextHandler() will be executed then
// the ctx.Pos (which is exported for these reasons) should be manually increment(++)
// otherwise your app will visit twice the same handler.
func (ctx *Context) NextHandler() Handler {
nextPos := ctx.Pos + 1
// check if it has a next middleware
if nextPos < len(ctx.Middleware) {
return ctx.Middleware[nextPos]
}
return nil
}
// StopExecution just sets the .pos to 255 in order to not move to the next middlewares(if any)
func (ctx *Context) StopExecution() {
ctx.Pos = stopExecutionPosition
}
// IsStopped checks and returns true if the current position of the Context is 255, means that the StopExecution has called
func (ctx *Context) IsStopped() bool {
return ctx.Pos == stopExecutionPosition
}
// GetHandlerName as requested returns the stack-name of the function which the Middleware is setted from
func (ctx *Context) GetHandlerName() string {
return runtime.FuncForPC(reflect.ValueOf(ctx.Middleware[len(ctx.Middleware)-1]).Pointer()).Name()
}
// ParamValidate receives a compiled Regexp and execute a parameter's value
// against this regexp, returns true if matched or param not found, otherwise false.
//
// It accepts a compiled regexp to reduce the performance cost on serve time.
// If you need a more automative solution, use the `app.Regex` or `app.RegexSingle` instead.
//
// This function helper is ridiculous simple but it's good to have it on one place.
func (ctx *Context) ParamValidate(compiledExpr *regexp.Regexp, paramName string) bool {
pathPart := ctx.Param(paramName)
if pathPart == "" {
// take care, the router already
// does the param validations
// so if it's empty here it means that
// the router has label it as optional.
// so we skip the check.
return true
}
if pathPart[0] == '/' {
// it's probably wildcard, we 'should' remove that part to do the matching below
pathPart = pathPart[1:]
}
// the improtant thing:
// if the path part didn't match with the relative exp, then fire status not found.
return compiledExpr.MatchString(pathPart)
}
// ExecRoute calls any route (mostly "offline" route) like it was requested by the user, but it is not.
// Offline means that the route is registered to the iris and have all features that a normal route has
// BUT it isn't available by browsing, its handlers executed only when other handler's context call them
// it can validate paths, has sessions, path parameters and all.
//
// You can find the Route by iris.Default.Routes().Lookup("theRouteName")
// you can set a route name as: myRoute := iris.Default.Get("/mypath", handler)("theRouteName")
// that will set a name to the route and returns its iris.Route instance for further usage.
//
// It doesn't changes the global state, if a route was "offline" it remains offline.
//
// see ExecRouteAgainst(routeName, againstRequestPath string),
// iris.Default.None(...) and iris.Default.SetRouteOnline/SetRouteOffline
// For more details look: https://github.com/kataras/iris/issues/585
//
// Example: https://github.com/iris-contrib/examples/tree/master/route_state
func (ctx *Context) ExecRoute(r RouteInfo) {
ctx.ExecRouteAgainst(r, ctx.Path())
}
// ExecRouteAgainst calls any iris.Route against a 'virtually' request path
// like it was requested by the user, but it is not.
// Offline means that the route is registered to the iris and have all features that a normal route has
// BUT it isn't available by browsing, its handlers executed only when other handler's context call them
// it can validate paths, has sessions, path parameters and all.
//
// You can find the Route by iris.Default.Routes().Lookup("theRouteName")
// you can set a route name as: myRoute := iris.Default.Get("/mypath", handler)("theRouteName")
// that will set a name to the route and returns its iris.Route instance for further usage.
//
// It doesn't changes the global state, if a route was "offline" it remains offline.
//
// see ExecRoute(routeName),
// iris.Default.None(...) and iris.Default.SetRouteOnline/SetRouteOffline
// For more details look: https://github.com/kataras/iris/issues/585
//
// Example: https://github.com/iris-contrib/examples/tree/master/route_state
//
// User can get the response by simple using rec := ctx.Recorder(); rec.Body()/rec.StatusCode()/rec.Header()
// The route will be executed via the Router, as it would requested by client.
func (ctx *Context) ExecRouteAgainst(r RouteInfo, againstRequestPath string) {
if r != nil && againstRequestPath != "" {
// ok no need to clone the whole context, let's be dirty here for the sake of performance.
backupMidldeware := ctx.Middleware[0:]
backupPath := ctx.Path()
bakcupMethod := ctx.Method()
backupValues := ctx.values
backupPos := ctx.Pos
// sessions stays.
ctx.values.Reset()
ctx.Middleware = ctx.Middleware[0:0]
ctx.Request.RequestURI = againstRequestPath
ctx.Request.URL.Path = againstRequestPath
ctx.Request.Method = r.Method()
ctx.framework.Router.ServeHTTP(ctx.ResponseWriter, ctx.Request)
ctx.Middleware = backupMidldeware
ctx.Request.RequestURI = backupPath
ctx.Request.URL.Path = backupPath
ctx.Request.Method = bakcupMethod
ctx.values = backupValues
ctx.Pos = backupPos
}
}
// Prioritize is a middleware which executes a route against this path
// when the request's Path has a prefix of the route's STATIC PART
// is not executing ExecRoute to determinate if it's valid, for performance reasons
// if this function is not enough for you and you want to test more than one parameterized path
// then use the: if c := ExecRoute(r); c == nil { /* move to the next, the route is not valid */ }
//
// You can find the Route by iris.Default.Routes().Lookup("theRouteName")
// you can set a route name as: myRoute := iris.Default.Get("/mypath", handler)("theRouteName")
// that will set a name to the route and returns its iris.Route instance for further usage.
//
// if the route found then it executes that and don't continue to the next handler
// if not found then continue to the next handler
func Prioritize(r RouteInfo) HandlerFunc {
if r != nil {
return func(ctx *Context) {
reqPath := ctx.Path()
staticPath := ctx.framework.policies.RouterReversionPolicy.StaticPath(r.Path())
if strings.HasPrefix(reqPath, staticPath) {
ctx.ExecRouteAgainst(r, reqPath) // returns 404 page from EmitErrors, these things depends on router adaptors
// we are done here.
return
}
// execute the next handler if no prefix
// here look, the only error we catch is the 404,
// we can't go ctx.Next() and believe that the next handler will manage the error
// because it will not, we are not on the router.
ctx.Next()
}
}
return func(ctx *Context) { ctx.Next() }
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// -----------------------------Request URL, Method, IP & Headers getters---------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// Method returns the http request method
// same as *http.Request.Method
func (ctx *Context) Method() string {
return ctx.Request.Method
}
// Host returns the host part of the current url
func (ctx *Context) Host() string {
h := ctx.Request.URL.Host
if h == "" {
h = ctx.Request.Host
}
return h
}
// ServerHost returns the server host taken by *http.Request.Host
func (ctx *Context) ServerHost() string {
return ctx.Request.Host
}
// Subdomain returns the subdomain (string) of this request, if any
func (ctx *Context) Subdomain() (subdomain string) {
host := ctx.Host()
if index := strings.IndexByte(host, '.'); index > 0 {
subdomain = host[0:index]
}
return
}
// VirtualHostname returns the hostname that user registers,
// host path maybe differs from the real which is the Host(), which taken from a net.listener
func (ctx *Context) VirtualHostname() string {
realhost := ctx.Host()
hostname := realhost
virtualhost := ctx.framework.Config.VHost
if portIdx := strings.IndexByte(hostname, ':'); portIdx > 0 {
hostname = hostname[0:portIdx]
}
if idxDotAnd := strings.LastIndexByte(hostname, '.'); idxDotAnd > 0 {
s := hostname[idxDotAnd:]
// means that we have the request's host mymachine.com or 127.0.0.1/0.0.0.0, but for the second option we will need to replace it with the hostname that the dev was registered
// this needed to parse correct the {{ url }} iris global template engine's function
if s == ".1" {
hostname = strings.Replace(hostname, "127.0.0.1", virtualhost, 1)
} else if s == ".0" {
hostname = strings.Replace(hostname, "0.0.0.0", virtualhost, 1)
}
//
} else {
hostname = strings.Replace(hostname, "localhost", virtualhost, 1)
}
return hostname
}
// Path returns the full escaped path as string
// for unescaped use: ctx.RequestCtx.RequestURI() or RequestPath(escape bool)
func (ctx *Context) Path() string {
return ctx.RequestPath(ctx.framework.Config.EnablePathEscape)
}
// RequestPath returns the requested path
func (ctx *Context) RequestPath(escape bool) string {
if escape {
// NOTE: for example:
// DecodeURI decodes %2F to '/'
// DecodeQuery decodes any %20 to whitespace
// here we choose to be query-decoded only
// and with context.ParamDecoded the user receives a URI decoded path parameter.
// see https://github.com/iris-contrib/examples/tree/master/named_parameters_pathescape
// and https://github.com/iris-contrib/examples/tree/master/pathescape
return DecodeQuery(ctx.Request.URL.EscapedPath())
}
return ctx.Request.URL.Path
}
// RemoteAddr tries to return the real client's request IP
func (ctx *Context) RemoteAddr() string {
header := ctx.RequestHeader("X-Real-Ip")
realIP := strings.TrimSpace(header)
if realIP != "" {
return realIP
}
realIP = ctx.RequestHeader("X-Forwarded-For")
idx := strings.IndexByte(realIP, ',')
if idx >= 0 {
realIP = realIP[0:idx]
}
realIP = strings.TrimSpace(realIP)
if realIP != "" {
return realIP
}
addr := strings.TrimSpace(ctx.Request.RemoteAddr)
if len(addr) == 0 {
return ""
}
// if addr has port use the net.SplitHostPort otherwise(error occurs) take as it is
if ip, _, err := net.SplitHostPort(addr); err == nil {
return ip
}
return addr
}
// RequestHeader returns the request header's value
// accepts one parameter, the key of the header (string)
// returns string
func (ctx *Context) RequestHeader(k string) string {
return ctx.Request.Header.Get(k)
}
// IsAjax returns true if this request is an 'ajax request'( XMLHttpRequest)
//
// Read more at: http://www.w3schools.com/ajax/
func (ctx *Context) IsAjax() bool {
return ctx.RequestHeader("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest"
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// -----------------------------GET & POST arguments------------------------------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// URLParam returns the get parameter from a request , if any
func (ctx *Context) URLParam(key string) string {
return ctx.Request.URL.Query().Get(key)
}
// URLParams returns a map of GET query parameters separated by comma if more than one
// it returns an empty map if nothing founds
func (ctx *Context) URLParams() map[string]string {
values := map[string]string{}
q := ctx.URLParamsAsMulti()
if q != nil {
for k, v := range q {
values[k] = strings.Join(v, ",")
}
}
return values
}
// URLParamsAsMulti returns a map of list contains the url get parameters
func (ctx *Context) URLParamsAsMulti() map[string][]string {
return ctx.Request.URL.Query()
}
// URLParamInt returns the url query parameter as int value from a request , returns error on parse fail
func (ctx *Context) URLParamInt(key string) (int, error) {
return strconv.Atoi(ctx.URLParam(key))
}
// URLParamInt64 returns the url query parameter as int64 value from a request , returns error on parse fail
func (ctx *Context) URLParamInt64(key string) (int64, error) {
return strconv.ParseInt(ctx.URLParam(key), 10, 64)
}
func (ctx *Context) askParseForm() error {
if ctx.Request.Form == nil {
if err := ctx.Request.ParseForm(); err != nil {
return err
}
}
return nil
}
// FormValues returns all post data values with their keys
// form data, get, post & put query arguments
//
// NOTE: A check for nil is necessary for zero results
func (ctx *Context) FormValues() map[string][]string {
// we skip the check of multipart form, takes too much memory, if user wants it can do manually now.
if err := ctx.askParseForm(); err != nil {
return nil
}
return ctx.Request.Form // nothing more to do, it's already contains both query and post & put args.
}
// FormValue returns a single form value by its name/key
func (ctx *Context) FormValue(name string) string {
return ctx.Request.FormValue(name)
}
// PostValue returns a form's only-post value by its name
// same as Request.PostFormValue
func (ctx *Context) PostValue(name string) string {
return ctx.Request.PostFormValue(name)
}
// FormFile returns the first file for the provided form key.
// FormFile calls ctx.Request.ParseMultipartForm and ParseForm if necessary.
//
// same as Request.FormFile
func (ctx *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error) {
return ctx.Request.FormFile(key)
}
var (
errTemplateExecute = errors.New("Unable to execute a template. Trace: %s")
errReadBody = errors.New("While trying to read %s from the request body. Trace %s")
errServeContent = errors.New("While trying to serve content to the client. Trace %s")
)
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// -----------------------------Request Body Binders/Readers----------------------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// NOTE: No default max body size http package has some built'n protection for DoS attacks
// See iris.Default.Config.MaxBytesReader, https://github.com/golang/go/issues/2093#issuecomment-66057813
// and https://github.com/golang/go/issues/2093#issuecomment-66057824
// LimitRequestBodySize is a middleware which sets a request body size limit for all next handlers
// should be registered before all other handlers
var LimitRequestBodySize = func(maxRequestBodySizeBytes int64) HandlerFunc {
return func(ctx *Context) {
ctx.SetMaxRequestBodySize(maxRequestBodySizeBytes)
ctx.Next()
}
}
// SetMaxRequestBodySize sets a limit to the request body size
// should be called before reading the request body from the client
func (ctx *Context) SetMaxRequestBodySize(limitOverBytes int64) {
ctx.Request.Body = http.MaxBytesReader(ctx.ResponseWriter, ctx.Request.Body, limitOverBytes)
}
// BodyDecoder is an interface which any struct can implement in order to customize the decode action
// from ReadJSON and ReadXML
//
// Trivial example of this could be:
// type User struct { Username string }
//
// func (u *User) Decode(data []byte) error {
// return json.Unmarshal(data, u)
// }
//
// the 'context.ReadJSON/ReadXML(&User{})' will call the User's
// Decode option to decode the request body
//
// Note: This is totally optionally, the default decoders
// for ReadJSON is the encoding/json and for ReadXML is the encoding/xml
type BodyDecoder interface {
Decode(data []byte) error
}
// Unmarshaler is the interface implemented by types that can unmarshal any raw data
// TIP INFO: Any v object which implements the BodyDecoder can be override the unmarshaler
type Unmarshaler interface {
Unmarshal(data []byte, v interface{}) error
}
// UnmarshalerFunc a shortcut for the Unmarshaler interface
//
// See 'Unmarshaler' and 'BodyDecoder' for more
type UnmarshalerFunc func(data []byte, v interface{}) error
// Unmarshal parses the X-encoded data and stores the result in the value pointed to by v.
// Unmarshal uses the inverse of the encodings that Marshal uses, allocating maps,
// slices, and pointers as necessary.
func (u UnmarshalerFunc) Unmarshal(data []byte, v interface{}) error {
return u(data, v)
}
// UnmarshalBody reads the request's body and binds it to a value or pointer of any type
// Examples of usage: context.ReadJSON, context.ReadXML
func (ctx *Context) UnmarshalBody(v interface{}, unmarshaler Unmarshaler) error {
if ctx.Request.Body == nil {
return errors.New("unmarshal: empty body")
}
rawData, err := ioutil.ReadAll(ctx.Request.Body)
if err != nil {
return err
}
if ctx.framework.Config.DisableBodyConsumptionOnUnmarshal {
// * remember, Request.Body has no Bytes(), we have to consume them first
// and after re-set them to the body, this is the only solution.
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(rawData))
}
// check if the v contains its own decode
// in this case the v should be a pointer also,
// but this is up to the user's custom Decode implementation*
//
// See 'BodyDecoder' for more
if decoder, isDecoder := v.(BodyDecoder); isDecoder {
return decoder.Decode(rawData)
}
// check if v is already a pointer, if yes then pass as it's
if reflect.TypeOf(v).Kind() == reflect.Ptr {
return unmarshaler.Unmarshal(rawData, v)
}
// finally, if the v doesn't contains a self-body decoder and it's not a pointer
// use the custom unmarshaler to bind the body
return unmarshaler.Unmarshal(rawData, &v)
}
// ReadJSON reads JSON from request's body and binds it to a value of any json-valid type
func (ctx *Context) ReadJSON(jsonObject interface{}) error {
return ctx.UnmarshalBody(jsonObject, UnmarshalerFunc(json.Unmarshal))
}
// ReadXML reads XML from request's body and binds it to a value of any xml-valid type
func (ctx *Context) ReadXML(xmlObject interface{}) error {
return ctx.UnmarshalBody(xmlObject, UnmarshalerFunc(xml.Unmarshal))
}
// ReadForm binds the formObject with the form data
// it supports any kind of struct
func (ctx *Context) ReadForm(formObject interface{}) error {
values := ctx.FormValues()
if values == nil {
return errors.New("An empty form passed on context.ReadForm")
}
return errReadBody.With(formBinder.Decode(values, formObject))
}
/* Response */
// SetContentType sets the response writer's header key 'Content-Type' to a given value(s)
func (ctx *Context) SetContentType(s string) {
ctx.ResponseWriter.Header().Set(contentType, s)
}
// SetHeader write to the response writer's header to a given key the given value
func (ctx *Context) SetHeader(k string, v string) {
ctx.ResponseWriter.Header().Add(k, v)
}
// SetStatusCode sets the status code header to the response
//
// same as .WriteHeader, iris takes cares of your status code seriously
func (ctx *Context) SetStatusCode(statusCode int) {
ctx.ResponseWriter.WriteHeader(statusCode)
}
// Redirect redirect sends a redirect response the client
// accepts 2 parameters string and an optional int
// first parameter is the url to redirect
// second parameter is the http status should send, default is 302 (StatusFound),
// you can set it to 301 (Permant redirect), if that's nessecery
func (ctx *Context) Redirect(urlToRedirect string, statusHeader ...int) {
ctx.StopExecution()
httpStatus := StatusFound // a 'temporary-redirect-like' which works better than for our purpose
if len(statusHeader) > 0 && statusHeader[0] > 0 {
httpStatus = statusHeader[0]
}
// we don't know the Method of the url to redirect,
// sure we can find it by reverse routing as we already implemented
// but it will take too much time for a simple redirect, it doesn't worth it.
// So we are checking the CURRENT Method for GET, HEAD, CONNECT and TRACE.
// the
// Fixes: http: //support.iris-go.com/d/21-wrong-warning-message-while-redirecting
shouldCheckForCycle := urlToRedirect == ctx.Path() && ctx.Method() == MethodGet
// from POST to GET on the same path will give a warning message but developers don't use the iris.DevLogger
// for production, so I assume it's OK to let it logs it
// (it can solve issues when developer redirects to the same handler over and over again)
// Note: it doesn't stops the redirect, the developer gets what he/she expected.
if shouldCheckForCycle {
ctx.Log(DevMode, "warning: redirect from: '%s' to: '%s',\ncurrent method: '%s'", ctx.Path(), urlToRedirect, ctx.Method())
}
http.Redirect(ctx.ResponseWriter, ctx.Request, urlToRedirect, httpStatus)
}
// RedirectTo does the same thing as Redirect but instead of receiving a uri or path it receives a route name
func (ctx *Context) RedirectTo(routeName string, args ...interface{}) {
s := ctx.framework.URL(routeName, args...)
if s != "" {
ctx.Redirect(s, StatusFound)
}
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// -----------------------------(Custom) Errors-----------------------------------------
// ----------------------Look iris.OnError/EmitError for more---------------------------
// -------------------------------------------------------------------------------------
// NotFound emits an error 404 to the client, using the custom http errors
// if no custom errors provided then it sends the default error message
func (ctx *Context) NotFound() {
ctx.framework.EmitError(StatusNotFound, ctx)
}
// Panic emits an error 500 to the client, using the custom http errors
// if no custom errors rpovided then it sends the default error message
func (ctx *Context) Panic() {
ctx.framework.EmitError(StatusInternalServerError, ctx)
}
// EmitError executes the custom error by the http status code passed to the function
func (ctx *Context) EmitError(statusCode int) {
ctx.framework.EmitError(statusCode, ctx)
ctx.StopExecution()
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// -------------------------Context's gzip inline response writer ----------------------
// ---------------------Look adaptors/view & iris.go for more options-------------------
// -------------------------------------------------------------------------------------
var (
errClientDoesNotSupportGzip = errors.New("Client doesn't supports gzip compression")
)
func (ctx *Context) clientAllowsGzip() bool {
if h := ctx.RequestHeader(acceptEncodingHeader); h != "" {
for _, v := range strings.Split(h, ";") {
if strings.Contains(v, "gzip") { // we do Contains because sometimes browsers has the q=, we don't use it atm. || strings.Contains(v,"deflate"){
return true
}
}
}
return false
}
// WriteGzip accepts bytes, which are compressed to gzip format and sent to the client.
// returns the number of bytes written and an error ( if the client doesn' supports gzip compression)
func (ctx *Context) WriteGzip(b []byte) (int, error) {
if ctx.clientAllowsGzip() {
ctx.ResponseWriter.Header().Add(varyHeader, acceptEncodingHeader)
gzipWriter := acquireGzipWriter(ctx.ResponseWriter)
defer releaseGzipWriter(gzipWriter)
n, err := gzipWriter.Write(b)
if err == nil {
ctx.SetHeader(contentEncodingHeader, "gzip")
} // else write the contents as it is? no let's create a new func for this
return n, err
}
return 0, errClientDoesNotSupportGzip
}
// TryWriteGzip accepts bytes, which are compressed to gzip format and sent to the client.
// If client does not supprots gzip then the contents are written as they are, uncompressed.
func (ctx *Context) TryWriteGzip(b []byte) (int, error) {
n, err := ctx.WriteGzip(b)
if err != nil {
// check if the error came from gzip not allowed and not the writer itself
if _, ok := err.(*errors.Error); ok {
// client didn't supported gzip, write them uncompressed:
return ctx.ResponseWriter.Write(b)
}
}
return n, err
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// -----------------------------Render and powerful content negotiation-----------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// getGzipOption receives a default value and the render options map and returns if gzip is enabled for this render action
func getGzipOption(defaultValue bool, options map[string]interface{}) bool {
gzipOpt := options["gzip"] // we only need that, so don't create new map to keep the options.
if b, isBool := gzipOpt.(bool); isBool {
return b
}
return defaultValue
}
// gtCharsetOption receives a default value and the render options map and returns the correct charset for this render action
func getCharsetOption(defaultValue string, options map[string]interface{}) string {
charsetOpt := options["charset"]
if s, isString := charsetOpt.(string); isString {
return s
}
return defaultValue
}
func (ctx *Context) fastRenderWithStatus(status int, cType string, data []byte) (err error) {
if _, shouldFirstStatusCode := ctx.ResponseWriter.(*responseWriter); shouldFirstStatusCode {
ctx.SetStatusCode(status)
}
gzipEnabled := ctx.framework.Config.Gzip
charset := ctx.framework.Config.Charset
if cType != contentBinary {
cType += "; charset=" + charset
}
// add the content type to the response
ctx.SetContentType(cType)
var out io.Writer
if gzipEnabled && ctx.clientAllowsGzip() {
ctx.ResponseWriter.Header().Add(varyHeader, acceptEncodingHeader)
ctx.SetHeader(contentEncodingHeader, "gzip")
gzipWriter := acquireGzipWriter(ctx.ResponseWriter)
defer releaseGzipWriter(gzipWriter)
out = gzipWriter
} else {
out = ctx.ResponseWriter
}
// no need to loop through the RenderPolicy, these types must be fast as possible
// with the features like gzip and custom charset too.
_, err = out.Write(data)
// we don't care for the last one it will not be written more than one if we have the *responseWriter
///TODO:
// if we have ResponseRecorder order doesn't matters but I think the transactions have bugs,
// temporary let's keep it here because it 'fixes' one of them...
ctx.SetStatusCode(status)
return
}
const (
// NoLayout to disable layout for a particular template file
NoLayout = "@.|.@no_layout@.|.@"
// ViewLayoutContextKey is the name of the user values which can be used to set a template layout from a middleware and override the parent's
ViewLayoutContextKey = "@viewLayout"
ViewDataContextKey = "@viewData"
// conversions
// TemplateLayoutContextKey same as ViewLayoutContextKey
TemplateLayoutContextKey = ViewLayoutContextKey
)
// ViewLayout sets the "layout" option if and when .Render
// is being called afterwards, in the same request.
// Useful when need to set or/and change a layout based on the previous handlers in the chain.
//
// Look: .ViewData | .Render
// .MustRender | .RenderWithStatus also.
//
// Example: https://github.com/kataras/iris/tree/v6/_examples/intermediate/view/context-view-data/
func (ctx *Context) ViewLayout(layoutTmplFile string) {
ctx.Set(ViewLayoutContextKey, layoutTmplFile)
}
// ViewData saves one or more key-value pair in order to be passed if and when .Render
// is being called afterwards, in the same request.
// Useful when need to set or/and change template data from previous hanadlers in the chain.
//
// If .Render's "binding" argument is not nil and it's not a type of map
// then these data are being ignored, binding has the priority, so the main route's handler can still decide.
// If binding is a map or iris.Map then theese data are being added to the view data
// and passed to the template.
//
// After .Render, the data are not destroyed, in order to be re-used if needed (again, in the same request as everything else),
// to manually clear the view data, developers can call:
// ctx.Set(iris.ViewDataContextKey, iris.Map{})
//
// Look: .ViewLayout | .Render
// .MustRender | .RenderWithStatus also.
//
// Example: https://github.com/kataras/iris/tree/v6/_examples/intermediate/view/context-view-data/
func (ctx *Context) ViewData(key string, value interface{}) {
v := ctx.Get(ViewDataContextKey)
if v == nil {
ctx.Set(ViewDataContextKey, Map{key: value})
return
}
if data, ok := v.(Map); ok {
data[key] = value
}
}
// RenderWithStatus builds up the response from the specified template or a serialize engine.
// Note: the options: "gzip" and "charset" are built'n support by Iris, so you can pass these on any template engine or serialize engines.
//
// Look: .ViewData | .Render
// .ViewLayout | .MustRender also.
//
// Examples: https://github.com/kataras/iris/tree/v6/_examples/intermediate/view/
func (ctx *Context) RenderWithStatus(status int, name string, binding interface{}, options ...map[string]interface{}) (err error) {
if _, shouldFirstStatusCode := ctx.ResponseWriter.(*responseWriter); shouldFirstStatusCode {
ctx.SetStatusCode(status)
}
// we do all these because we don't want to initialize a new map for each execution...
gzipEnabled := ctx.framework.Config.Gzip
charset := ctx.framework.Config.Charset