-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathcontext.go
6521 lines (5653 loc) · 203 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 context
import (
"bytes"
stdContext "context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
"unsafe"
"github.com/kataras/iris/v12/core/memstore"
"github.com/kataras/iris/v12/core/netutil"
"github.com/Shopify/goreferrer"
"github.com/fatih/structs"
"github.com/iris-contrib/schema"
"github.com/mailru/easyjson"
"github.com/mailru/easyjson/jwriter"
"github.com/microcosm-cc/bluemonday"
"github.com/russross/blackfriday/v2"
"github.com/vmihailenco/msgpack/v5"
"golang.org/x/net/publicsuffix"
"golang.org/x/time/rate"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"gopkg.in/yaml.v3"
)
var (
// BuildRevision holds the vcs commit id information of the program's build.
// Available at go version 1.18+
BuildRevision string
// BuildTime holds the vcs commit time information of the program's build.
// Available at go version 1.18+
BuildTime string
)
type (
// 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.
//
// Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-custom-per-type/main.go
BodyDecoder interface {
Decode(data []byte) error
}
// BodyDecoderWithContext same as BodyDecoder but it can accept a standard context,
// which is binded to the HTTP request's context.
BodyDecoderWithContext interface {
DecodeContext(ctx stdContext.Context, data []byte) error
}
// Unmarshaler is the interface implemented by types that can unmarshal any raw data.
// TIP INFO: Any pointer to a value which implements the BodyDecoder can be override the unmarshaler.
Unmarshaler interface {
Unmarshal(data []byte, outPtr interface{}) error
}
// UnmarshalerFunc a shortcut for the Unmarshaler interface
//
// See 'Unmarshaler' and 'BodyDecoder' for more.
//
// Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-custom-via-unmarshaler/main.go
UnmarshalerFunc func(data []byte, outPtr interface{}) error
// DecodeFunc is a generic type of decoder function.
// When the returned error is not nil the decode operation
// is terminated and the error is received by the ReadJSONStream method,
// otherwise it continues to read the next available object.
// Look the `Context.ReadJSONStream` method.
DecodeFunc func(outPtr 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)
}
// LimitRequestBodySize is a middleware which sets a request body size limit
// for all next handlers in the chain.
var LimitRequestBodySize = func(maxRequestBodySizeBytes int64) Handler {
return func(ctx *Context) {
ctx.SetMaxRequestBodySize(maxRequestBodySizeBytes)
ctx.Next()
}
}
// Map is just a type alias of the map[string]interface{} type.
type Map = map[string]interface{}
// Context is the midle-man server's "object" dealing with incoming requests.
//
// A New context is being acquired from a sync.Pool on each connection.
// The Context is the most important thing on the iris's http flow.
//
// Developers send responses to the client's request through a Context.
// Developers get request information from the client's request a Context.
type Context struct {
// the http.ResponseWriter wrapped by custom writer.
writer ResponseWriter
// the original http.Request
request *http.Request
// the current route registered to this request path.
currentRoute RouteReadOnly
// the local key-value storage
params RequestParams // url named parameters.
values memstore.Store // generic storage, middleware communication.
query url.Values // GET url query temp cache, useful on many URLParamXXX calls.
// the underline application app.
app Application
// the route's handlers
handlers Handlers
// the current position of the handler's chain
currentHandlerIndex int
// proceeded reports whether `Proceed` method
// called before a `Next`. It is a flash field and it is set
// to true on `Next` call when its called on the last handler in the chain.
// Reports whether a `Next` is called,
// even if the handler index remains the same (last handler).
//
// Also it's responsible to keep the old value of the last known handler index
// before StopExecution. See ResumeExecution.
proceeded int
// if true, caller is responsible to release the context (put the context to the pool).
manualRelease bool
}
// NewContext returns a new Context instance.
func NewContext(app Application) *Context {
return &Context{app: app}
}
/* Not required, unless requested.
// SetApplication sets an Iris Application on-fly.
// Do NOT use it after ServeHTTPC is fired.
func (ctx *Context) SetApplication(app Application) {
ctx.app = app
}
*/
// Clone returns a copy of the context that
// can be safely used outside the request's scope.
// Note that if the request-response lifecycle terminated
// or request canceled by the client (can be checked by `ctx.IsCanceled()`)
// then the response writer is totally useless.
// The http.Request pointer value is shared.
func (ctx *Context) Clone() *Context {
valuesCopy := make(memstore.Store, len(ctx.values))
copy(valuesCopy, ctx.values)
paramsCopy := make(memstore.Store, len(ctx.params.Store))
copy(paramsCopy, ctx.params.Store)
queryCopy := make(url.Values, len(ctx.query))
for k, v := range ctx.query {
queryCopy[k] = v
}
req := ctx.request.Clone(ctx.request.Context())
return &Context{
app: ctx.app,
values: valuesCopy,
params: RequestParams{Store: paramsCopy},
query: queryCopy,
writer: ctx.writer.Clone(),
request: req,
currentHandlerIndex: stopExecutionIndex,
proceeded: ctx.proceeded,
manualRelease: ctx.manualRelease,
currentRoute: ctx.currentRoute,
}
}
// BeginRequest is executing once for each request
// it should prepare the (new or acquired from pool) context's fields for the new request.
// Do NOT call it manually. Framework calls it automatically.
//
// Resets
// 1. handlers to nil.
// 2. values to empty.
// 3. the defer function.
// 4. response writer to the http.ResponseWriter.
// 5. request to the *http.Request.
func (ctx *Context) BeginRequest(w http.ResponseWriter, r *http.Request) {
ctx.currentRoute = nil
ctx.handlers = nil // will be filled by router.Serve/HTTP
ctx.values = ctx.values[0:0] // >> >> by context.Values().Set
ctx.params.Store = ctx.params.Store[0:0]
ctx.query = nil
ctx.request = r
ctx.currentHandlerIndex = 0
ctx.proceeded = 0
ctx.manualRelease = false
ctx.writer = AcquireResponseWriter()
ctx.writer.BeginResponse(w)
}
// EndRequest is executing once after a response to the request was sent and this context is useless or released.
// Do NOT call it manually. Framework calls it automatically.
//
// 1. executes the OnClose function (if any).
// 2. flushes the response writer's result or fire any error handler.
// 3. releases the response writer.
func (ctx *Context) EndRequest() {
if !ctx.app.ConfigurationReadOnly().GetDisableAutoFireStatusCode() &&
StatusCodeNotSuccessful(ctx.GetStatusCode()) {
ctx.app.FireErrorCode(ctx)
}
ctx.writer.FlushResponse()
ctx.writer.EndResponse()
}
// DisablePoolRelease disables the auto context pool Put call.
// Do NOT use it, unless you know what you are doing.
func (ctx *Context) DisablePoolRelease() {
ctx.manualRelease = true
}
// IsCanceled reports whether the client canceled the request
// or the underlying connection has gone.
// Note that it will always return true
// when called from a goroutine after the request-response lifecycle.
func (ctx *Context) IsCanceled() bool {
var err error
if reqCtx := ctx.request.Context(); reqCtx != nil {
err = reqCtx.Err()
} else {
err = ctx.GetErr()
}
return IsErrCanceled(err)
}
// IsErrCanceled reports whether the "err" is caused by a cancellation or timeout.
func IsErrCanceled(err error) bool {
if err == nil {
return false
}
var netErr net.Error
return (errors.As(err, &netErr) && netErr.Timeout()) ||
errors.Is(err, stdContext.Canceled) ||
errors.Is(err, stdContext.DeadlineExceeded) ||
errors.Is(err, http.ErrHandlerTimeout) ||
err.Error() == "closed pool"
}
// OnConnectionClose registers the "cb" Handler
// which will be fired on its on goroutine on a cloned Context
// when the underlying connection has gone away.
//
// The code inside the given callback is running on its own routine,
// as explained above, therefore the callback should NOT
// try to access to handler's Context response writer.
//
// This mechanism can be used to cancel long operations on the server
// if the client has disconnected before the response is ready.
//
// It depends on the Request's Context.Done() channel.
//
// Finally, it reports whether the protocol supports pipelines (HTTP/1.1 with pipelines disabled is not supported).
// The "cb" will not fire for sure if the output value is false.
//
// Note that you can register only one callback per route.
//
// See `OnClose` too.
func (ctx *Context) OnConnectionClose(cb Handler) bool {
if cb == nil {
return false
}
reqCtx := ctx.Request().Context()
if reqCtx == nil {
return false
}
notifyClose := reqCtx.Done()
if notifyClose == nil {
return false
}
go func() {
<-notifyClose
// Note(@kataras): No need to clone if not canceled,
// EndRequest will be called on the end of the handler chain,
// no matter the cancelation.
// therefore the context will still be there.
cb(ctx.Clone())
}()
return true
}
// OnConnectionCloseErr same as `OnConnectionClose` but instead it
// receives a function which returns an error.
// If error is not nil, it will be logged as a debug message.
func (ctx *Context) OnConnectionCloseErr(cb func() error) bool {
if cb == nil {
return false
}
reqCtx := ctx.Request().Context()
if reqCtx == nil {
return false
}
notifyClose := reqCtx.Done()
if notifyClose == nil {
return false
}
go func() {
<-notifyClose
if err := cb(); err != nil {
// Can be ignored.
ctx.app.Logger().Debugf("OnConnectionCloseErr: received error: %v", err)
}
}()
return true
}
// OnClose registers a callback which
// will be fired when the underlying connection has gone away(request canceled)
// on its own goroutine or in the end of the request-response lifecylce
// on the handler's routine itself (Context access).
//
// See `OnConnectionClose` too.
func (ctx *Context) OnClose(cb Handler) {
if cb == nil {
return
}
// Note(@kataras):
// - on normal request-response lifecycle
// the `SetBeforeFlush` will be called first
// and then `OnConnectionClose`,
// - when request was canceled before handler finish its job
// then the `OnConnectionClose` will be called first instead,
// and when the handler function completed then `SetBeforeFlush` is fired.
// These are synchronized, they cannot be executed the same exact time,
// below we just make sure the "cb" is executed once
// by simple boolean check or an atomic one.
var executed uint32
callback := func(ctx *Context) {
if atomic.CompareAndSwapUint32(&executed, 0, 1) {
cb(ctx)
}
}
ctx.OnConnectionClose(callback)
onFlush := func() {
callback(ctx)
}
ctx.writer.SetBeforeFlush(onFlush)
}
// OnCloseErr same as `OnClose` but instead it
// receives a function which returns an error.
// If error is not nil, it will be logged as a debug message.
func (ctx *Context) OnCloseErr(cb func() error) {
if cb == nil {
return
}
var executed uint32
callback := func() error {
if atomic.CompareAndSwapUint32(&executed, 0, 1) {
return cb()
}
return nil
}
ctx.OnConnectionCloseErr(callback)
onFlush := func() {
if err := callback(); err != nil {
// Can be ignored.
ctx.app.Logger().Debugf("OnClose: SetBeforeFlush: received error: %v", err)
}
}
ctx.writer.SetBeforeFlush(onFlush)
}
/* Note(@kataras): just leave end-developer decide.
const goroutinesContextKey = "iris.goroutines"
type goroutines struct {
wg *sync.WaitGroup
length int
mu sync.RWMutex
}
var acquireGoroutines = func() interface{} {
return &goroutines{wg: new(sync.WaitGroup)}
}
func (ctx *Context) Go(fn func(cancelCtx stdContext.Context)) (running int) {
g := ctx.values.GetOrSet(goroutinesContextKey, acquireGoroutines).(*goroutines)
if fn != nil {
g.wg.Add(1)
g.mu.Lock()
g.length++
g.mu.Unlock()
ctx.waitFunc = g.wg.Wait
go func(reqCtx stdContext.Context) {
fn(reqCtx)
g.wg.Done()
g.mu.Lock()
g.length--
g.mu.Unlock()
}(ctx.request.Context())
}
g.mu.RLock()
running = g.length
g.mu.RUnlock()
return
}
*/
// ResponseWriter returns an http.ResponseWriter compatible response writer, as expected.
func (ctx *Context) ResponseWriter() ResponseWriter {
return ctx.writer
}
// ResetResponseWriter sets a new ResponseWriter implementation
// to this Context to use as its writer.
// Note, to change the underline http.ResponseWriter use
// ctx.ResponseWriter().SetWriter(http.ResponseWriter) instead.
func (ctx *Context) ResetResponseWriter(newResponseWriter ResponseWriter) {
if rec, ok := ctx.IsRecording(); ok {
releaseResponseRecorder(rec)
}
ctx.writer = newResponseWriter
}
// Request returns the original *http.Request, as expected.
func (ctx *Context) Request() *http.Request {
return ctx.request
}
// ResetRequest sets the Context's Request,
// It is useful to store the new request created by a std *http.Request#WithContext() into Iris' Context.
// Use `ResetRequest` when for some reason you want to make a full
// override of the *http.Request.
// Note that: when you just want to change one of each fields you can use the Request() which returns a pointer to Request,
// so the changes will have affect without a full override.
// Usage: you use a native http handler which uses the standard "context" package
// to get values instead of the Iris' Context#Values():
// r := ctx.Request()
// stdCtx := context.WithValue(r.Context(), key, val)
// ctx.ResetRequest(r.WithContext(stdCtx)).
func (ctx *Context) ResetRequest(r *http.Request) {
ctx.request = r
}
// SetCurrentRoute sets the route internally,
// See `GetCurrentRoute()` method too.
// It's being initialized by the Router.
// See `Exec` or `SetHandlers/AddHandler` methods to simulate a request.
func (ctx *Context) SetCurrentRoute(route RouteReadOnly) {
ctx.currentRoute = route
}
// GetCurrentRoute returns the current "read-only" route that
// was registered to this request's path.
func (ctx *Context) GetCurrentRoute() RouteReadOnly {
return ctx.currentRoute
}
// Do sets the "handlers" as the chain
// and executes the first handler,
// handlers should not be empty.
//
// It's used by the router, developers may use that
// to replace and execute handlers immediately.
func (ctx *Context) Do(handlers Handlers) {
if len(handlers) == 0 {
return
}
ctx.handlers = handlers
handlers[0](ctx)
}
// AddHandler can add handler(s)
// to the current request in serve-time,
// these handlers are not persistenced to the router.
//
// Router is calling this function to add the route's handler.
// If AddHandler called then the handlers will be inserted
// to the end of the already-defined route's handler.
func (ctx *Context) AddHandler(handlers ...Handler) {
ctx.handlers = append(ctx.handlers, handlers...)
}
// SetHandlers replaces all handlers with the new.
func (ctx *Context) SetHandlers(handlers Handlers) {
ctx.handlers = handlers
}
// Handlers keeps tracking of the current handlers.
func (ctx *Context) Handlers() Handlers {
return ctx.handlers
}
// HandlerIndex sets the current index of the
// current context's handlers chain.
// If n < 0 or the current handlers length is 0 then it just returns the
// current handler index without change the current index.
//
// Look Handlers(), Next() and StopExecution() too.
func (ctx *Context) HandlerIndex(n int) (currentIndex int) {
if n < 0 || n > len(ctx.handlers)-1 {
return ctx.currentHandlerIndex
}
ctx.currentHandlerIndex = n
return n
}
// Proceed is an alternative way to check if a particular handler
// has been executed.
// The given "h" Handler can report a failure with `StopXXX` methods
// or ignore calling a `Next` (see `iris.ExecutionRules` too).
//
// This is useful only when you run a handler inside
// another handler. It justs checks for before index and the after index.
//
// A usecase example is when you want to execute a middleware
// inside controller's `BeginRequest` that calls the `ctx.Next` inside it.
// The Controller looks the whole flow (BeginRequest, method handler, EndRequest)
// as one handler, so `ctx.Next` will not be reflected to the method handler
// if called from the `BeginRequest`.
//
// Although `BeginRequest` should NOT be used to call other handlers,
// the `BeginRequest` has been introduced to be able to set
// common data to all method handlers before their execution.
// Controllers can accept middleware(s) from the MVC's Application's Router as normally.
//
// That said let's see an example of `ctx.Proceed`:
//
// var authMiddleware = basicauth.New(basicauth.Config{
// Users: map[string]string{
// "admin": "password",
// },
// })
//
// func (c *UsersController) BeginRequest(ctx iris.Context) {
// if !ctx.Proceed(authMiddleware) {
// ctx.StopExecution()
// }
// }
//
// This Get() will be executed in the same handler as `BeginRequest`,
// internally controller checks for `ctx.StopExecution`.
// So it will not be fired if BeginRequest called the `StopExecution`.
//
// func(c *UsersController) Get() []models.User {
// return c.Service.GetAll()
// }
//
// Alternative way is `!ctx.IsStopped()` if middleware make use of the `ctx.StopExecution()` on failure.
func (ctx *Context) Proceed(h Handler) bool {
_, ok := ctx.ProceedAndReportIfStopped(h)
return ok
}
// ProceedAndReportIfStopped same as "Proceed" method
// but the first output parameter reports whether the "h"
// called "StopExecution" manually.
func (ctx *Context) ProceedAndReportIfStopped(h Handler) (bool, bool) {
ctx.proceeded = internalPauseExecutionIndex
// Store the current index.
beforeIdx := ctx.currentHandlerIndex
h(ctx)
// Retrieve the next one, if Next is called this is beforeIdx + 1 and so on.
afterIdx := ctx.currentHandlerIndex
// Restore prev index, no matter what.
ctx.currentHandlerIndex = beforeIdx
proceededByNext := ctx.proceeded == internalProceededHandlerIndex
ctx.proceeded = beforeIdx
// Stop called, return false but keep the handlers index.
if afterIdx == stopExecutionIndex {
return true, false
}
if proceededByNext {
return false, true
}
// Next called or not.
return false, afterIdx > beforeIdx
}
// HandlerName returns the current handler's name, helpful for debugging.
func (ctx *Context) HandlerName() string {
return HandlerName(ctx.handlers[ctx.currentHandlerIndex])
}
// HandlerFileLine returns the current running handler's function source file and line information.
// Useful mostly when debugging.
func (ctx *Context) HandlerFileLine() (file string, line int) {
return HandlerFileLine(ctx.handlers[ctx.currentHandlerIndex])
}
// RouteName returns the route name that this handler is running on.
// Note that it may return empty on not found handlers.
func (ctx *Context) RouteName() string {
if ctx.currentRoute == nil {
return ""
}
return ctx.currentRoute.Name()
}
// Next calls the next handler from the handlers chain,
// it should be used inside a middleware.
func (ctx *Context) Next() {
if ctx.IsStopped() {
return
}
if ctx.proceeded <= internalPauseExecutionIndex /* pause and proceeded */ {
ctx.proceeded = internalProceededHandlerIndex
return
}
nextIndex, n := ctx.currentHandlerIndex+1, len(ctx.handlers)
if nextIndex < n {
ctx.currentHandlerIndex = nextIndex
ctx.handlers[nextIndex](ctx)
}
}
// NextOr checks if chain has a next handler, if so then it executes it
// otherwise it sets a new chain assigned to this Context based on the given handler(s)
// and executes its first handler.
//
// Returns true if next handler exists and executed, otherwise false.
//
// Note that if no next handler found and handlers are missing then
// it sends a Status Not Found (404) to the client and it stops the execution.
func (ctx *Context) NextOr(handlers ...Handler) bool {
if next := ctx.NextHandler(); next != nil {
ctx.Skip() // skip this handler from the chain.
next(ctx)
return true
}
if len(handlers) == 0 {
ctx.NotFound()
ctx.StopExecution()
return false
}
ctx.Do(handlers)
return false
}
// NextOrNotFound checks if chain has a next handler, if so then it executes it
// otherwise it sends a Status Not Found (404) to the client and stops the execution.
//
// Returns true if next handler exists and executed, otherwise false.
func (ctx *Context) NextOrNotFound() bool { return ctx.NextOr() }
// NextHandler returns (it doesn't execute) the next handler from the handlers chain.
//
// Use .Skip() to skip this handler if needed to execute the next of this returning handler.
func (ctx *Context) NextHandler() Handler {
if ctx.IsStopped() {
return nil
}
nextIndex := ctx.currentHandlerIndex + 1
// check if it has a next middleware
if nextIndex < len(ctx.handlers) {
return ctx.handlers[nextIndex]
}
return nil
}
// Skip skips/ignores the next handler from the handlers chain,
// it should be used inside a middleware.
func (ctx *Context) Skip() {
ctx.HandlerIndex(ctx.currentHandlerIndex + 1)
}
const (
stopExecutionIndex = -1
internalPauseExecutionIndex = -2
internalProceededHandlerIndex = -3
)
// StopExecution stops the handlers chain of this request.
// Meaning that any following `Next` calls are ignored,
// as a result the next handlers in the chain will not be fire.
//
// See ResumeExecution too.
func (ctx *Context) StopExecution() {
if curIdx := ctx.currentHandlerIndex; curIdx != stopExecutionIndex {
// Protect against multiple calls of StopExecution.
// Resume should set the last proceeded handler index.
// Store the current index.
ctx.proceeded = curIdx
// And stop.
ctx.currentHandlerIndex = stopExecutionIndex
}
}
// IsStopped reports whether the current position of the context's handlers is -1,
// means that the StopExecution() was called at least once.
func (ctx *Context) IsStopped() bool {
return ctx.currentHandlerIndex == stopExecutionIndex
}
// ResumeExecution sets the current handler index to the last
// index of the executed handler before StopExecution method was fired.
//
// Reports whether it's restored after a StopExecution call.
func (ctx *Context) ResumeExecution() bool {
if ctx.IsStopped() {
ctx.currentHandlerIndex = ctx.proceeded
return true
}
return false
}
// StopWithStatus stops the handlers chain and writes the "statusCode".
//
// If the status code is a failure one then
// it will also fire the specified error code handler.
func (ctx *Context) StopWithStatus(statusCode int) {
ctx.StopExecution()
ctx.StatusCode(statusCode)
}
// StopWithText stops the handlers chain and writes the "statusCode"
// among with a fmt-style text of "format" and optional arguments.
//
// If the status code is a failure one then
// it will also fire the specified error code handler.
func (ctx *Context) StopWithText(statusCode int, format string, args ...interface{}) {
ctx.StopWithStatus(statusCode)
ctx.WriteString(fmt.Sprintf(format, args...))
}
// StopWithError stops the handlers chain and writes the "statusCode"
// among with the error "err".
// It Calls the `SetErr` method so error handlers can access the given error.
//
// If the status code is a failure one then
// it will also fire the specified error code handler.
//
// If the given "err" is private then the
// status code's text is rendered instead (unless a registered error handler overrides it).
func (ctx *Context) StopWithError(statusCode int, err error) {
if err == nil {
return
}
ctx.SetErr(err)
if _, ok := err.(ErrPrivate); ok {
// error is private, we SHOULD not render it,
// leave the error handler alone to
// render the code's text instead.
ctx.StopWithStatus(statusCode)
return
}
ctx.StopWithText(statusCode, err.Error())
}
// StopWithPlainError like `StopWithError` but it does NOT
// write anything to the response writer, it stores the error
// so any error handler matching the given "statusCode" can handle it by its own.
func (ctx *Context) StopWithPlainError(statusCode int, err error) {
if err == nil {
return
}
ctx.SetErr(err)
ctx.StopWithStatus(statusCode)
}
// StopWithJSON stops the handlers chain, writes the status code
// and sends a JSON response.
//
// If the status code is a failure one then
// it will also fire the specified error code handler.
func (ctx *Context) StopWithJSON(statusCode int, jsonObject interface{}) error {
ctx.StopWithStatus(statusCode)
return ctx.writeJSON(jsonObject, &DefaultJSONOptions) // do not modify - see errors.DefaultContextErrorHandler.
}
// StopWithProblem stops the handlers chain, writes the status code
// and sends an application/problem+json response.
// See `iris.NewProblem` to build a "problem" value correctly.
//
// If the status code is a failure one then
// it will also fire the specified error code handler.
func (ctx *Context) StopWithProblem(statusCode int, problem Problem) error {
ctx.StopWithStatus(statusCode)
problem.Status(statusCode)
return ctx.Problem(problem)
}
// +------------------------------------------------------------+
// | Current "user/request" storage |
// | and share information between the handlers - Values(). |
// | Save and get named path parameters - Params() |
// +------------------------------------------------------------+
// Params returns the current url's named parameters key-value storage.
// Named path parameters are being saved here.
// This storage, as the whole context, is per-request lifetime.
func (ctx *Context) Params() *RequestParams {
return &ctx.params
}
// Values returns the current "user" storage.
// Named path parameters and any optional data can be saved here.
// This storage, as the whole context, is per-request lifetime.
//
// You can use this function to Set and Get local values
// that can be used to share information between handlers and middleware.
func (ctx *Context) Values() *memstore.Store {
return &ctx.values
}
// +------------------------------------------------------------+
// | Path, Host, Subdomain, IP, Headers etc... |
// +------------------------------------------------------------+
// Method returns the request.Method, the client's http method to the server.
func (ctx *Context) Method() string {
return ctx.request.Method
}
// Path returns the full request path,
// escaped if EnablePathEscape config field is true.
func (ctx *Context) Path() string {
return ctx.RequestPath(ctx.app.ConfigurationReadOnly().GetEnablePathEscape())
}
// DecodeQuery returns the uri parameter as url (string)
// useful when you want to pass something to a database and be valid to retrieve it via context.Param
// use it only for special cases, when the default behavior doesn't suits you.
//
// http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
// it uses just the url.QueryUnescape
func DecodeQuery(path string) string {
if path == "" {
return ""
}
encodedPath, err := url.QueryUnescape(path)
if err != nil {
return path
}
return encodedPath
}
// DecodeURL returns the decoded uri
// useful when you want to pass something to a database and be valid to retrieve it via context.Param
// use it only for special cases, when the default behavior doesn't suits you.
//
// http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
// it uses just the url.Parse
func DecodeURL(uri string) string {
u, err := url.Parse(uri)
if err != nil {
return uri
}
return u.String()
}
// RequestPath returns the full request path,
// based on the 'escape'.
func (ctx *Context) RequestPath(escape bool) string {
if escape {
return ctx.request.URL.EscapedPath() // DecodeQuery(ctx.request.URL.EscapedPath())
}
return ctx.request.URL.Path // RawPath returns empty, requesturi can be used instead also.
}
const sufscheme = "://"
// GetScheme returns the full scheme of the request URL (https://, http:// or ws:// and e.t.c.).
func GetScheme(r *http.Request) string {
scheme := r.URL.Scheme
if scheme == "" {
if r.TLS != nil {
scheme = netutil.SchemeHTTPS
} else {
scheme = netutil.SchemeHTTP
}
}
return scheme + sufscheme
}
// Scheme returns the full scheme of the request (including :// suffix).
func (ctx *Context) Scheme() string {
return GetScheme(ctx.Request())
}
// PathPrefixMap accepts a map of string and a handler.
// The key of "m" is the key, which is the prefix, regular expressions are not valid.
// The value of "m" is the handler that will be executed if HasPrefix(context.Path).
// func (ctx *Context) PathPrefixMap(m map[string]context.Handler) bool {
// path := ctx.Path()
// for k, v := range m {
// if strings.HasPrefix(path, k) {
// v(ctx)
// return true
// }
// }
// return false
// } no, it will not work because map is a random peek data structure.
// GetHost returns the host part of the current URI.
func GetHost(r *http.Request) string {
// contains subdomain.
if host := r.URL.Host; host != "" {
return host
}
return r.Host
}
// Host returns the host:port part of the request URI, calls the `Request().Host`.
// To get the subdomain part as well use the `Request().URL.Host` method instead.
// To get the subdomain only use the `Subdomain` method instead.
// This method makes use of the `Configuration.HostProxyHeaders` field too.
func (ctx *Context) Host() string {
for header, ok := range ctx.app.ConfigurationReadOnly().GetHostProxyHeaders() {
if !ok {
continue
}
if host := ctx.GetHeader(header); host != "" {
return host
}
}
return GetHost(ctx.request)
}