Context Methods
Here is a full list of methods that the iris.Context structure provides.
1
// Clone returns a copy of the context that
2
// can be safely used outside the request's scope.
3
// Note that if the request-response lifecycle terminated
4
// or request canceled by the client (can be checked by `ctx.IsCanceled()`)
5
// then the response writer is totally useless.
6
// The http.Request pointer value is shared.
7
Clone() *Context
8
// BeginRequest is executing once for each request
9
// it should prepare the (new or acquired from pool) context's fields for the new request.
10
// Do NOT call it manually. Framework calls it automatically.
11
//
12
// Resets
13
// 1. handlers to nil.
14
// 2. values to empty.
15
// 3. the defer function.
16
// 4. response writer to the http.ResponseWriter.
17
// 5. request to the *http.Request.
18
BeginRequest(w http.ResponseWriter, r *http.Request)
19
// EndRequest is executing once after a response to the request was sent and this context is useless or released.
20
// Do NOT call it manually. Framework calls it automatically.
21
//
22
// 1. executes the OnClose function (if any).
23
// 2. flushes the response writer's result or fire any error handler.
24
// 3. releases the response writer.
25
EndRequest()
26
// IsCanceled reports whether the client canceled the request
27
// or the underlying connection has gone.
28
// Note that it will always return true
29
// when called from a goroutine after the request-response lifecycle.
30
IsCanceled() bool
31
// OnConnectionClose registers the "cb" Handler
32
// which will be fired on its on goroutine on a cloned Context
33
// when the underlying connection has gone away.
34
//
35
// The code inside the given callback is running on its own routine,
36
// as explained above, therefore the callback should NOT
37
// try to access to handler's Context response writer.
38
//
39
// This mechanism can be used to cancel long operations on the server
40
// if the client has disconnected before the response is ready.
41
//
42
// It depends on the Request's Context.Done() channel.
43
//
44
// Finally, it reports whether the protocol supports pipelines (HTTP/1.1 with pipelines disabled is not supported).
45
// The "cb" will not fire for sure if the output value is false.
46
//
47
// Note that you can register only one callback per route.
48
//
49
// See `OnClose` too.
50
OnConnectionClose(cb Handler) bool
51
// OnClose registers a callback which
52
// will be fired when the underlying connection has gone away(request canceled)
53
// on its own goroutine or in the end of the request-response lifecylce
54
// on the handler's routine itself (Context access).
55
//
56
// See `OnConnectionClose` too.
57
OnClose(cb Handler)
58
// ResponseWriter returns an http.ResponseWriter compatible response writer, as expected.
59
ResponseWriter() ResponseWriter
60
// ResetResponseWriter sets a new ResponseWriter implementation
61
// to this Context to use as its writer.
62
// Note, to change the underline http.ResponseWriter use
63
// ctx.ResponseWriter().SetWriter(http.ResponseWRiter) instead.
64
ResetResponseWriter(newResponseWriter ResponseWriter)
65
// Request returns the original *http.Request, as expected.
66
Request() *http.Request
67
// ResetRequest sets the Context's Request,
68
// It is useful to store the new request created by a std *http.Request#WithContext() into Iris' Context.
69
// Use `ResetRequest` when for some reason you want to make a full
70
// override of the *http.Request.
71
// Note that: when you just want to change one of each fields you can use the Request() which returns a pointer to Request,
72
// so the changes will have affect without a full override.
73
// Usage: you use a native http handler which uses the standard "context" package
74
// to get values instead of the Iris' Context#Values():
75
// r := ctx.Request()
76
// stdCtx := context.WithValue(r.Context(), key, val)
77
// ctx.ResetRequest(r.WithContext(stdCtx)).
78
ResetRequest(r *http.Request)
79
// SetCurrentRoute sets the route internally,
80
// See `GetCurrentRoute()` method too.
81
// It's being initialized by the Router.
82
// See `Exec` or `SetHandlers/AddHandler` methods to simulate a request.
83
SetCurrentRoute(route RouteReadOnly)
84
// GetCurrentRoute returns the current "read-only" route that
85
// was registered to this request's path.
86
GetCurrentRoute() RouteReadOnly
87
// Do sets the "handlers" as the chain
88
// and executes the first handler,
89
// handlers should not be empty.
90
//
91
// It's used by the router, developers may use that
92
// to replace and execute handlers immediately.
93
Do(handlers Handlers)
94
// AddHandler can add handler(s)
95
// to the current request in serve-time,
96
// these handlers are not persistenced to the router.
97
//
98
// Router is calling this function to add the route's handler.
99
// If AddHandler called then the handlers will be inserted
100
// to the end of the already-defined route's handler.
101
//
102
AddHandler(handlers ...Handler)
103
// SetHandlers replaces all handlers with the new.
104
SetHandlers(handlers Handlers)
105
// Handlers keeps tracking of the current handlers.
106
Handlers() Handlers
107
// HandlerIndex sets the current index of the
108
// current context's handlers chain.
109
// If n < 0 or the current handlers length is 0 then it just returns the
110
// current handler index without change the current index.
111
//
112
// Look Handlers(), Next() and StopExecution() too.
113
HandlerIndex(n int) (currentIndex int)
114
// Proceed is an alternative way to check if a particular handler
115
// has been executed and called the `ctx.Next` function inside it.
116
// This is useful only when you run a handler inside
117
// another handler. It justs checks for before index and the after index.
118
//
119
// A usecase example is when you want to execute a middleware
120
// inside controller's `BeginRequest` that calls the `ctx.Next` inside it.
121
// The Controller looks the whole flow (BeginRequest, method handler, EndRequest)
122
// as one handler, so `ctx.Next` will not be reflected to the method handler
123
// if called from the `BeginRequest`.
124
//
125
// Although `BeginRequest` should NOT be used to call other handlers,
126
// the `BeginRequest` has been introduced to be able to set
127
// common data to all method handlers before their execution.
128
// Controllers can accept middleware(s) from the MVC's Application's Router as normally.
129
//
130
// That said let's see an example of `ctx.Proceed`:
131
//
132
// var authMiddleware = basicauth.Default(map[string]string{
133
// "admin": "password",
134
// })
135
//
136
// func (c *UsersController) BeginRequest(ctx iris.Context) {
137
// if !ctx.Proceed(authMiddleware) {
138
// ctx.StopExecution()
139
// }
140
// }
141
// This Get() will be executed in the same handler as `BeginRequest`,
142
// internally controller checks for `ctx.StopExecution`.
143
// So it will not be fired if BeginRequest called the `StopExecution`.
144
// func(c *UsersController) Get() []models.User {
145
// return c.Service.GetAll()
146
//}
147
// Alternative way is `!ctx.IsStopped()` if middleware make use of the `ctx.StopExecution()` on failure.
148
Proceed(h Handler) bool
149
// HandlerName returns the current handler's name, helpful for debugging.
150
HandlerName() string
151
// HandlerFileLine returns the current running handler's function source file and line information.
152
// Useful mostly when debugging.
153
HandlerFileLine() (file string, line int)
154
// RouteName returns the route name that this handler is running on.
155
// Note that it may return empty on not found handlers.
156
RouteName() string
157
// Next calls the next handler from the handlers chain,
158
// it should be used inside a middleware.
159
Next()
160
// NextOr checks if chain has a next handler, if so then it executes it
161
// otherwise it sets a new chain assigned to this Context based on the given handler(s)
162
// and executes its first handler.
163
//
164
// Returns true if next handler exists and executed, otherwise false.
165
//
166
// Note that if no next handler found and handlers are missing then
167
// it sends a Status Not Found (404) to the client and it stops the execution.
168
NextOr(handlers ...Handler) bool
169
// NextOrNotFound checks if chain has a next handler, if so then it executes it
170
// otherwise it sends a Status Not Found (404) to the client and stops the execution.
171
//
172
// Returns true if next handler exists and executed, otherwise false.
173
NextOrNotFound() bool
174
// NextHandler returns (it doesn't execute) the next handler from the handlers chain.
175
//
176
// Use .Skip() to skip this handler if needed to execute the next of this returning handler.
177
NextHandler() Handler
178
// Skip skips/ignores the next handler from the handlers chain,
179
// it should be used inside a middleware.
180
Skip()
181
// StopExecution stops the handlers chain of this request.
182
// Meaning that any following `Next` calls are ignored,
183
// as a result the next handlers in the chain will not be fire.
184
StopExecution()
185
// IsStopped reports whether the current position of the context's handlers is -1,
186
// means that the StopExecution() was called at least once.
187
IsStopped() bool
188
// StopWithStatus stops the handlers chain and writes the "statusCode".
189
//
190
// If the status code is a failure one then
191
// it will also fire the specified error code handler.
192
StopWithStatus(statusCode int)
193
// StopWithText stops the handlers chain and writes the "statusCode"
194
// among with a message "plainText".
195
//
196
// If the status code is a failure one then
197
// it will also fire the specified error code handler.
198
StopWithText(statusCode int, plainText string)
199
// StopWithError stops the handlers chain and writes the "statusCode"
200
// among with the error "err".
201
// It Calls the `SetErr` method so error handlers can access the given error.
202
//
203
// If the status code is a failure one then
204
// it will also fire the specified error code handler.
205
StopWithError(statusCode int, err error)
206
// StopWithJSON stops the handlers chain, writes the status code
207
// and sends a JSON response.
208
//
209
// If the status code is a failure one then
210
// it will also fire the specified error code handler.
211
StopWithJSON(statusCode int, jsonObject interface{})
212
// StopWithProblem stops the handlers chain, writes the status code
213
// and sends an application/problem+json response.
214
// See `iris.NewProblem` to build a "problem" value correctly.
215
//
216
// If the status code is a failure one then
217
// it will also fire the specified error code handler.
218
StopWithProblem(statusCode int, problem Problem)
219
// Params returns the current url's named parameters key-value storage.
220
// Named path parameters are being saved here.
221
// This storage, as the whole context, is per-request lifetime.
222
Params() *RequestParams
223
// Values returns the current "user" storage.
224
// Named path parameters and any optional data can be saved here.
225
// This storage, as the whole context, is per-request lifetime.
226
//
227
// You can use this function to Set and Get local values
228
// that can be used to share information between handlers and middleware.
229
Values() *memstore.Store
230
// Method returns the request.Method, the client's http method to the server.
231
Method() string
232
// Path returns the full request path,
233
// escaped if EnablePathEscape config field is true.
234
Path() string
235
// RequestPath returns the full request path,
236
// based on the 'escape'.
237
RequestPath(escape bool) string
238
// Host returns the host part of the current URI.
239
// This method makes use of the `Configuration.HostProxyHeaders` field too.
240
Host() string
241
// Subdomain returns the subdomain of this request, if any.
242
// Note that this is a fast method which does not cover all cases.
243
Subdomain() (subdomain string)
244
// FindClosest returns a list of "n" paths close to
245
// this request based on subdomain and request path.
246
//
247
// Order may change.
248
// Example: https://github.com/kataras/iris/tree/master/_examples/routing/intelligence/manual
249
FindClosest(n int) []string
250
// IsWWW returns true if the current subdomain (if any) is www.
251
IsWWW() bool
252
// FullRequestURI returns the full URI,
253
// including the scheme, the host and the relative requested path/resource.
254
FullRequestURI() string
255
// RemoteAddr tries to parse and return the real client's request IP.
256
//
257
// Based on allowed headers names that can be modified from Configuration.RemoteAddrHeaders.
258
//
259
// If parse based on these headers fail then it will return the Request's `RemoteAddr` field
260
// which is filled by the server before the HTTP handler,
261
// unless the Configuration.RemoteAddrHeadersForce was set to true
262
// which will force this method to return the first IP from RemoteAddrHeaders
263
// even if it's part of a private network.
264
//
265
// Look `Configuration.RemoteAddrHeaders`,
266
// `Configuration.RemoteAddrHeadersForce`,
267
// `Configuration.WithRemoteAddrHeader(...)`,
268
// `Configuration.WithoutRemoteAddrHeader(...)` and
269
// `Configuration.RemoteAddrPrivateSubnets` for more.
270
RemoteAddr() string
271
// GetHeader returns the request header's value based on its name.
272
GetHeader(name string) string
273
// GetDomain resolves and returns the server's domain.
274
GetDomain() string
275
// IsAjax returns true if this request is an 'ajax request'( XMLHttpRequest)
276
//
277
// There is no a 100% way of knowing that a request was made via Ajax.
278
// You should never trust data coming from the client, they can be easily overcome by spoofing.
279
//
280
// Note that "X-Requested-With" Header can be modified by any client(because of "X-"),
281
// so don't rely on IsAjax for really serious stuff,
282
// try to find another way of detecting the type(i.e, content type),
283
// there are many blogs that describe these problems and provide different kind of solutions,
284
// it's always depending on the application you're building,
285
// this is the reason why this `IsAjax`` is simple enough for general purpose use.
286
//
287
// Read more at: https://developer.mozilla.org/en-US/docs/AJAX
288
// and https://xhr.spec.whatwg.org/
289
IsAjax() bool
290
// IsMobile checks if client is using a mobile device(phone or tablet) to communicate with this server.
291
// If the return value is true that means that the http client using a mobile
292
// device to communicate with the server, otherwise false.
293
//
294
// Keep note that this checks the "User-Agent" request header.
295
IsMobile() bool
296
// IsScript reports whether a client is a script.
297
IsScript() bool
298
// IsSSL reports whether the client is running under HTTPS SSL.
299
//
300
// See `IsHTTP2` too.
301
IsSSL() bool
302
// IsHTTP2 reports whether the protocol version for incoming request was HTTP/2.
303
// The client code always uses either HTTP/1.1 or HTTP/2.
304
//
305
// See `IsSSL` too.
306
IsHTTP2() bool
307
// IsGRPC reports whether the request came from a gRPC client.
308
IsGRPC() bool
309
// GetReferrer extracts and returns the information from the "Referer" (or "Referrer") header
310
// and url query parameter as specified in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy.
311
GetReferrer() Referrer
312
// SetLanguage force-sets the language for i18n, can be used inside a middleare.
313
// It has the highest priority over the rest and if it is empty then it is ignored,
314
// if it set to a static string of "default" or to the default language's code
315
// then the rest of the language extractors will not be called at all and
316
// the default language will be set instead.
317
//
318
// See `i18n.ExtractFunc` for a more organised way of the same feature.
319
SetLanguage(langCode string)
320
// GetLocale returns the current request's `Locale` found by i18n middleware.
321
// See `Tr` too.
322
GetLocale() Locale
323
// Tr returns a i18n localized message based on format with optional arguments.
324
// See `GetLocale` too.
325
//
326
// Example: https://github.com/kataras/iris/tree/master/_examples/i18n
327
Tr(message string, values ...interface{}) string
328
// Header adds a header to the response, if value is empty
329
// it removes the header by its name.
330
Header(name string, value string)
331
// ContentType sets the response writer's
332
// header "Content-Type" to the 'cType'.
333
ContentType(cType string)
334
// GetContentType returns the response writer's
335
// header value of "Content-Type".
336
GetContentType() string
337
// GetContentTypeRequested returns the request's
338
// trim-ed(without the charset and priority values)
339
// header value of "Content-Type".
340
GetContentTypeRequested() string
341
// GetContentLength returns the request's
342
// header value of "Content-Length".
343
GetContentLength() int64
344
// StatusCode sets the status code header to the response.
345
// Look .GetStatusCode & .FireStatusCode too.
346
//
347
// Remember, the last one before .Write matters except recorder and transactions.
348
StatusCode(statusCode int)
349
// NotFound emits an error 404 to the client, using the specific custom error error handler.
350
// Note that you may need to call ctx.StopExecution() if you don't want the next handlers
351
// to be executed. Next handlers are being executed on iris because you can alt the
352
// error code and change it to a more specific one, i.e
353
// users := app.Party("/users")
354
// users.Done(func(ctx iris.Context){ if ctx.StatusCode() == 400 { /* custom error code for /users */ }})
355
NotFound()
356
// GetStatusCode returns the current status code of the response.
357
// Look StatusCode too.
358
GetStatusCode() int
359
// URLParamExists returns true if the url parameter exists, otherwise false.
360
URLParamExists(name string) bool
361
// URLParamDefault returns the get parameter from a request, if not found then "def" is returned.
362
URLParamDefault(name string, def string) string
363
// URLParam returns the get parameter from a request, if any.
364
URLParam(name string) string
365
// URLParamTrim returns the url query parameter with trailing white spaces removed from a request.
366
URLParamTrim(name string) string
367
// URLParamEscape returns the escaped url query parameter from a request.
368
URLParamEscape(name string) string
369
// URLParamInt returns the url query parameter as int value from a request,
370
// returns -1 and an error if parse failed or not found.
371
URLParamInt(name string) (int, error)
372
// URLParamIntDefault returns the url query parameter as int value from a request,
373
// if not found or parse failed then "def" is returned.
374
URLParamIntDefault(name string, def int) int
375
// URLParamInt32Default returns the url query parameter as int32 value from a request,
376
// if not found or parse failed then "def" is returned.
377
URLParamInt32Default(name string, def int32) int32
378
// URLParamInt64 returns the url query parameter as int64 value from a request,
379
// returns -1 and an error if parse failed or not found.
380
URLParamInt64(name string) (int64, error)
381
// URLParamInt64Default returns the url query parameter as int64 value from a request,
382
// if not found or parse failed then "def" is returned.
383
URLParamInt64Default(name string, def int64) int64
384
// URLParamFloat64 returns the url query parameter as float64 value from a request,
385
// returns an error and -1 if parse failed.
386
URLParamFloat64(name string) (float64, error)
387
// URLParamFloat64Default returns the url query parameter as float64 value from a request,
388
// if not found or parse failed then "def" is returned.
389
URLParamFloat64Default(name string, def float64) float64
390
// URLParamBool returns the url query parameter as boolean value from a request,
391
// returns an error if parse failed.
392
URLParamBool(name string) (bool, error)
393
// URLParams returns a map of GET query parameters separated by comma if more than one
394
// it returns an empty map if nothing found.
395
URLParams() map[string]string
396
// FormValueDefault returns a single parsed form value by its "name",
397
// including both the URL field's query parameters and the POST or PUT form data.
398
//
399
// Returns the "def" if not found.
400
FormValueDefault(name string, def string) string
401
// FormValue returns a single parsed form value by its "name",
402
// including both the URL field's query parameters and the POST or PUT form data.
403
FormValue(name string) string
404
// FormValues returns the parsed form data, including both the URL
405
// field's query parameters and the POST or PUT form data.
406
//
407
// The default form's memory maximum size is 32MB, it can be changed by the
408
// `iris#WithPostMaxMemory` configurator at main configuration passed on `app.Run`'s second argument.
409
// NOTE: A check for nil is necessary.
410
FormValues() map[string][]string
411
// PostValueDefault returns the parsed form data from POST, PATCH,
412
// or PUT body parameters based on a "name".
413
//
414
// If not found then "def" is returned instead.
415
PostValueDefault(name string, def string) string
416
// PostValue returns the parsed form data from POST, PATCH,
417
// or PUT body parameters based on a "name"
418
PostValue(name string) string
419
// PostValueTrim returns the parsed form data from POST, PATCH,
420
// or PUT body parameters based on a "name", without trailing spaces.
421
PostValueTrim(name string) string
422
// PostValueInt returns the parsed form data from POST, PATCH,
423
// or PUT body parameters based on a "name", as int.
424
//
425
// If not found returns -1 and a non-nil error.
426
PostValueInt(name string) (int, error)
427
// PostValueIntDefault returns the parsed form data from POST, PATCH,
428
// or PUT body parameters based on a "name", as int.
429
//
430
// If not found or parse errors returns the "def".
431
PostValueIntDefault(name string, def int) int
432
// PostValueInt64 returns the parsed form data from POST, PATCH,
433
// or PUT body parameters based on a "name", as float64.
434
//
435
// If not found returns -1 and a non-nil error.
436
PostValueInt64(name string) (int64, error)
437
// PostValueInt64Default returns the parsed form data from POST, PATCH,
438
// or PUT body parameters based on a "name", as int64.
439
//
440
// If not found or parse errors returns the "def".
441
PostValueInt64Default(name string, def int64) int64
442
// PostValueFloat64 returns the parsed form data from POST, PATCH,
443
// or PUT body parameters based on a "name", as float64.
444
//
445
// If not found returns -1 and a non-nil error.
446
PostValueFloat64(name string) (float64, error)
447
// PostValueFloat64Default returns the parsed form data from POST, PATCH,
448
// or PUT body parameters based on a "name", as float64.
449
//
450
// If not found or parse errors returns the "def".
451
PostValueFloat64Default(name string, def float64) float64
452
// PostValueBool returns the parsed form data from POST, PATCH,
453
// or PUT body parameters based on a "name", as bool.
454
//
455
// If not found or value is false, then it returns false, otherwise true.
456
PostValueBool(name string) (bool, error)
457
// PostValues returns all the parsed form data from POST, PATCH,
458
// or PUT body parameters based on a "name" as a string slice.
459
//
460
// The default form's memory maximum size is 32MB, it can be changed by the
461
// `iris#WithPostMaxMemory` configurator at main configuration passed on `app.Run`'s second argument.
462
PostValues(name string) []string
463
// FormFile returns the first uploaded file that received from the client.
464
//
465
//
466
// The default form's memory maximum size is 32MB, it can be changed by the
467
// `iris#WithPostMaxMemory` configurator at main configuration passed on `app.Run`'s second argument.
468
//
469
// Example: https://github.com/kataras/iris/tree/master/_examples/file-server/upload-file
470
FormFile(key string) (multipart.File, *multipart.FileHeader, error)
471
// UploadFormFiles uploads any received file(s) from the client
472
// to the system physical location "destDirectory".
473
//
474
// The second optional argument "before" gives caller the chance to
475
// modify the *miltipart.FileHeader before saving to the disk,
476
// it can be used to change a file's name based on the current request,
477
// all FileHeader's options can be changed. You can ignore it if
478
// you don't need to use this capability before saving a file to the disk.
479
//
480
// Note that it doesn't check if request body streamed.
481
//
482
// Returns the copied length as int64 and
483
// a not nil error if at least one new file
484
// can't be created due to the operating system's permissions or
485
// http.ErrMissingFile if no file received.
486
//
487
// If you want to receive & accept files and manage them manually you can use the `context#FormFile`
488
// instead and create a copy function that suits your needs, the below is for generic usage.
489
//
490
// The default form's memory maximum size is 32MB, it can be changed by the
491
// `iris#WithPostMaxMemory` configurator at main configuration passed on `app.Run`'s second argument.
492
//
493
// See `FormFile` to a more controlled to receive a file.
494
//
495
// Example: https://github.com/kataras/iris/tree/master/_examples/file-server/upload-files
496
UploadFormFiles(destDirectory string, before ...func(*Context, *multipart.FileHeader)) (n int64, err error)
497
// AbsoluteURI parses the "s" and returns its absolute URI form.
498
AbsoluteURI(s string) string
499
// Redirect sends a redirect response to the client
500
// to a specific url or relative path.
501
// accepts 2 parameters string and an optional int
502
// first parameter is the url to redirect
503
// second parameter is the http status should send,
504
// default is 302 (StatusFound),
505
// you can set it to 301 (Permant redirect)
506
// or 303 (StatusSeeOther) if POST method,
507
// or StatusTemporaryRedirect(307) if that's nessecery.
508
Redirect(urlToRedirect string, statusHeader ...int)
509
// SetMaxRequestBodySize sets a limit to the request body size
510
// should be called before reading the request body from the client.
511
SetMaxRequestBodySize(limitOverBytes int64)
512
// GetBody reads and returns the request body.
513
// The default behavior for the http request reader is to consume the data readen
514
// but you can change that behavior by passing the `WithoutBodyConsumptionOnUnmarshal` iris option.
515
//
516
// However, whenever you can use the `ctx.Request().Body` instead.
517
GetBody() ([]byte, error)
518
// UnmarshalBody reads the request's body and binds it to a value or pointer of any type
519
// Examples of usage: context.ReadJSON, context.ReadXML.
520
//
521
// Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-custom-via-unmarshaler/main.go
522
UnmarshalBody(outPtr interface{}, unmarshaler Unmarshaler) error
523
// ReadJSON reads JSON from request's body and binds it to a value of any json-valid type.
524
//
525
// Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-json/main.go
526
ReadJSON(outPtr interface{}) error
527
// ReadXML reads XML from request's body and binds it to a value of any xml-valid type.
528
//
529
// Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-xml/main.go
530
ReadXML(outPtr interface{}) error
531
// ReadYAML reads YAML from request's body and binds it to the "outPtr" value.
532
//
533
// Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-yaml/main.go
534
ReadYAML(outPtr interface{}) error
535
// ReadForm binds the request body of a form to the "formObject".
536
// It supports any kind of type, including custom structs.
537
// It will return nothing if request data are empty.
538
// The struct field tag is "form".
539
// Note that it will return nil error on empty form data if `Configuration.FireEmptyFormError`
540
// is false (as defaulted) in this case the caller should check the pointer to
541
// see if something was actually binded.
542
//
543
// If a client sent an unknown field, this method will return an error,
544
// in order to ignore that error use the `err != nil && !iris.IsErrPath(err)`.
545
//
546
// Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-form/main.go
547
ReadForm(formObject interface{}) error
548
// ReadQuery binds url query to "ptr". The struct field tag is "url".
549
//
550
// Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-query/main.go
551
ReadQuery(ptr interface{}) error
552
// ReadProtobuf binds the body to the "ptr" of a proto Message and returns any error.
553
// Look `ReadJSONProtobuf` too.
554
ReadProtobuf(ptr proto.Message) error
555
// ReadJSONProtobuf reads a JSON body request into the given "ptr" proto.Message.
556
// Look `ReadProtobuf` too.
557
ReadJSONProtobuf(ptr proto.Message, opts ...ProtoUnmarshalOptions) error
558
// ReadMsgPack binds the request body of msgpack format to the "ptr" and returns any error.
559
ReadMsgPack(ptr interface{}) error
560
// ReadBody binds the request body to the "ptr" depending on the HTTP Method and the Request's Content-Type.
561
// If a GET method request then it reads from a form (or URL Query), otherwise
562
// it tries to match (depending on the request content-type) the data format e.g.
563
// JSON, Protobuf, MsgPack, XML, YAML, MultipartForm and binds the result to the "ptr".
564
ReadBody(ptr interface{}) error
565
// Write writes the data to the connection as part of an HTTP reply.
566
//
567
// If WriteHeader has not yet been called, Write calls
568
// WriteHeader(http.StatusOK) before writing the data. If the Header
569
// does not contain a Content-Type line, Write adds a Content-Type set
570
// to the result of passing the initial 512 bytes of written data to
571
// DetectContentType.
572
//
573
// Depending on the HTTP protocol version and the client, calling
574
// Write or WriteHeader may prevent future reads on the
575
// Request.Body. For HTTP/1.x requests, handlers should read any
576
// needed request body data before writing the response. Once the
577
// headers have been flushed (due to either an explicit Flusher.Flush
578
// call or writing enough data to trigger a flush), the request body
579
// may be unavailable. For HTTP/2 requests, the Go HTTP server permits
580
// handlers to continue to read the request body while concurrently
581
// writing the response. However, such behavior may not be supported
582
// by all HTTP/2 clients. Handlers should read before writing if
583
// possible to maximize compatibility.
584
Write(rawBody []byte) (int, error)
585
// Writef formats according to a format specifier and writes to the response.
586
//
587
// Returns the number of bytes written and any write error encountered.
588
Writef(format string, a ...interface{}) (n int, err error)
589
// WriteString writes a simple string to the response.
590
//
591
// Returns the number of bytes written and any write error encountered.
592
WriteString(body string) (n int, err error)
593
// SetLastModified sets the "Last-Modified" based on the "modtime" input.
594
// If "modtime" is zero then it does nothing.
595
//
596
// It's mostly internally on core/router and context packages.
597
SetLastModified(modtime time.Time)
598
// CheckIfModifiedSince checks if the response is modified since the "modtime".
599
// Note that it has nothing to do with server-side caching.
600
// It does those checks by checking if the "If-Modified-Since" request header
601
// sent by client or a previous server response header
602
// (e.g with WriteWithExpiration or HandleDir or Favicon etc.)
603
// is a valid one and it's before the "modtime".
604
//
605
// A check for !modtime && err == nil is necessary to make sure that
606
// it's not modified since, because it may return false but without even
607
// had the chance to check the client-side (request) header due to some errors,
608
// like the HTTP Method is not "GET" or "HEAD" or if the "modtime" is zero
609
// or if parsing time from the header failed. See `ErrPreconditionFailed` too.
610
//
611
// It's mostly used internally, e.g. `context#WriteWithExpiration`.
612
CheckIfModifiedSince(modtime time.Time) (bool, error)
613
// WriteNotModified sends a 304 "Not Modified" status code to the client,
614
// it makes sure that the content type, the content length headers
615
// and any "ETag" are removed before the response sent.
616
//
617
// It's mostly used internally on core/router/fs.go and context methods.
618
WriteNotModified()
619
// WriteWithExpiration works like `Write` but it will check if a resource is modified,
620
// based on the "modtime" input argument,
621
// otherwise sends a 304 status code in order to let the client-side render the cached content.
622
WriteWithExpiration(body []byte, modtime time.Time) (int, error)
623
// StreamWriter registers the given stream writer for populating
624
// response body.
625
//
626
// Access to context's and/or its' members is forbidden from writer.
627
//
628
// This function may be used in the following cases:
629
//
630
// * if response body is too big (more than iris.LimitRequestBodySize(if set)).
631
// * if response body is streamed from slow external sources.
632
// * if response body must be streamed to the client in chunks.
633
// (aka `http server push`).
634
StreamWriter(writer func(w io.Writer) error) error
635
// ClientSupportsEncoding reports whether the
636
// client expects one of the given "encodings" compression.
637
//
638
// Note, this method just reports back the first valid encoding it sees,
639
// meaning that request accept-encoding offers don't matter here.
640
// See `CompressWriter` too.
641
ClientSupportsEncoding(encodings ...string) bool
642
// CompressWriter enables or disables the compress response writer.
643
// if the client expects a valid compression algorithm then this
644
// will change the response writer to a compress writer instead.
645
// All future write and rich write methods will respect this option.
646
// Usage:
647
// app.Use(func(ctx iris.Context){
648
// err := ctx.CompressWriter(true)
649
// ctx.Next()
650
// })
651
// The recommendation is to compress data as much as possible and therefore to use this field,
652
// but some types of resources, such as jpeg images, are already compressed.
653
// Sometimes, using additional compression doesn't reduce payload size and
654
// can even make the payload longer.
655
CompressWriter(enable bool) error
656
// CompressReader accepts a boolean, which, if set to true
657
// it wraps the request body reader with a reader which decompresses request data before read.
658
// If the "enable" input argument is false then the request body will reset to the default one.
659
//
660
// Useful when incoming request data are compressed.
661
// All future calls of `ctx.GetBody/ReadXXX/UnmarshalBody` methods will respect this option.
662
//
663
// Usage:
664
// app.Use(func(ctx iris.Context){
665
// err := ctx.CompressReader(true)
666
// ctx.Next()
667
// })
668
// More:
669
// if cr, ok := ctx.Request().Body.(*CompressReader); ok {
670
// cr.Src // the original request body
671
// cr.Encoding // the compression algorithm.
672
// }
673
//
674
// It returns `ErrRequestNotCompressed` if client's request data are not compressed
675
// (or empty)
676
// or `ErrNotSupportedCompression` if server missing the decompression algorithm.
677
CompressReader(enable bool) error
678
// ViewLayout sets the "layout" option if and when .View
679
// is being called afterwards, in the same request.
680
// Useful when need to set or/and change a layout based on the previous handlers in the chain.
681
//
682
// Note that the 'layoutTmplFile' argument can be set to iris.NoLayout || view.NoLayout || context.NoLayout
683
// to disable the layout for a specific view render action,
684
// it disables the engine's configuration's layout property.
685
//
686
// Look .ViewData and .View too.
687
//
688
// Example: https://github.com/kataras/iris/tree/master/_examples/view/context-view-data/
689
ViewLayout(layoutTmplFile string)
690
// ViewData saves one or more key-value pair in order to be passed if and when .View
691
// is being called afterwards, in the same request.
692
// Useful when need to set or/and change template data from previous hanadlers in the chain.
693
//
694
// If .View's "binding" argument is not nil and it's not a type of map
695
// then these data are being ignored, binding has the priority, so the main route's handler can still decide.
696
// If binding is a map or context.Map then these data are being added to the view data
697
// and passed to the template.
698
//
699
// After .View, the data are not destroyed, in order to be re-used if needed (again, in the same request as everything else),
700
// to clear the view data, developers can call:
701
// ctx.Set(ctx.Application().ConfigurationReadOnly().GetViewDataContextKey(), nil)
702
//
703
// If 'key' is empty then the value is added as it's (struct or map) and developer is unable to add other value.
704
//
705
// Look .ViewLayout and .View too.
706
//
707
// Example: https://github.com/kataras/iris/tree/master/_examples/view/context-view-data/
708
ViewData(key string, value interface{})
709
// GetViewData returns the values registered by `context#ViewData`.
710
// The return value is `map[string]interface{}`, this means that
711
// if a custom struct registered to ViewData then this function
712
// will try to parse it to map, if failed then the return value is nil
713
// A check for nil is always a good practise if different
714
// kind of values or no data are registered via `ViewData`.
715
//
716
// Similarly to `viewData := ctx.Values().Get("iris.viewData")` or
717
// `viewData := ctx.Values().Get(ctx.Application().ConfigurationReadOnly().GetViewDataContextKey())`.
718
GetViewData() map[string]interface{}
719
// View renders a template based on the registered view engine(s).
720
// First argument accepts the filename, relative to the view engine's Directory and Extension,
721
// i.e: if directory is "./templates" and want to render the "./templates/users/index.html"
722
// then you pass the "users/index.html" as the filename argument.
723
//
724
// The second optional argument can receive a single "view model"
725
// that will be binded to the view template if it's not nil,
726
// otherwise it will check for previous view data stored by the `ViewData`
727
// even if stored at any previous handler(middleware) for the same request.
728
//
729
// Look .ViewData and .ViewLayout too.
730
//
731
// Examples: https://github.com/kataras/iris/tree/master/_examples/view
732
View(filename string, optionalViewModel ...interface{}) error
733
// Binary writes out the raw bytes as binary data.
734
Binary(data []byte) (int, error)
735
// Text writes out a string as plain text.
736
Text(format string, args ...interface{}) (int, error)
737
// HTML writes out a string as text/html.
738
HTML(format string, args ...interface{}) (int, error)
739
// JSON marshals the given interface object and writes the JSON response to the client.
740
// If the value is a compatible `proto.Message` one
741
// then it only uses the options.Proto settings to marshal.
742
JSON(v interface{}, opts ...JSON) (n int, err error)
743
// JSONP marshals the given interface object and writes the JSON response to the client.
744
JSONP(v interface{}, opts ...JSONP) (int, error)
745
// XML marshals the given interface object and writes the XML response to the client.
746
// To render maps as XML see the `XMLMap` package-level function.
747
XML(v interface{}, opts ...XML) (int, error)
748
// Problem writes a JSON or XML problem response.
749
// Order of Problem fields are not always rendered the same.
750
//
751
// Behaves exactly like `Context.JSON`
752
// but with default ProblemOptions.JSON indent of " " and
753
// a response content type of "application/problem+json" instead.
754
//
755
// Use the options.RenderXML and XML fields to change this behavior and
756
// send a response of content type "application/problem+xml" instead.
757
//
758
// Read more at: https://github.com/kataras/iris/wiki/Routing-error-handlers
759
Problem(v interface{}, opts ...ProblemOptions) (int, error)
760
// Markdown parses the markdown to html and renders its result to the client.
761
Markdown(markdownB []byte, opts ...Markdown) (int, error)
762
// YAML marshals the "v" using the yaml marshaler and renders its result to the client.
763
YAML(v interface{}) (int, error)
764
// Protobuf parses the "v" of proto Message and renders its result to the client.
765
Protobuf(v proto.Message) (int, error)
766
// MsgPack parses the "v" of msgpack format and renders its result to the client.
767
MsgPack(v interface{}) (int, error)
768
// Negotiation creates once and returns the negotiation builder
769
// to build server-side available prioritized content
770
// for specific content type(s), charset(s) and encoding algorithm(s).
771
//
772
// See `Negotiate` method too.
773
Negotiation() *NegotiationBuilder
774
// Negotiate used for serving different representations of a resource at the same URI.
775
//
776
// The "v" can be a single `N` struct value.
777
// The "v" can be any value completes the `ContentSelector` interface.
778
// The "v" can be any value completes the `ContentNegotiator` interface.
779
// The "v" can be any value of struct(JSON, JSONP, XML, YAML, Protobuf, MsgPack) or
780
// string(TEXT, HTML) or []byte(Markdown, Binary) or []byte with any matched mime type.
781
//
782
// If the "v" is nil, the `Context.Negotitation()` builder's
783
// content will be used instead, otherwise "v" overrides builder's content
784
// (server mime types are still retrieved by its registered, supported, mime list)
785
//
786
// Set mime type priorities by `Negotiation().JSON().XML().HTML()...`.
787
// Set charset priorities by `Negotiation().Charset(...)`.
788
// Set encoding algorithm priorities by `Negotiation().Encoding(...)`.
789
// Modify the accepted by
790
// `Negotiation().Accept./Override()/.XML().JSON().Charset(...).Encoding(...)...`.
791
//
792
// It returns `ErrContentNotSupported` when not matched mime type(s).
793
//
794
// Resources:
795
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation
796
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept
797
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Charset
798
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
799
//
800
// Supports the above without quality values.
801
//
802
// Read more at: https://github.com/kataras/iris/wiki/Content-negotiation
803
Negotiate(v interface{}) (int, error)
804
// ServeContent replies to the request using the content in the
805
// provided ReadSeeker. The main benefit of ServeContent over io.Copy
806
// is that it handles Range requests properly, sets the MIME type, and
807
// handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since,
808
// and If-Range requests.
809
//
810
// If the response's Content-Type header is not set, ServeContent
811
// first tries to deduce the type from name's file extension.
812
//
813
// The name is otherwise unused; in particular it can be empty and is
814
// never sent in the response.
815
//
816
// If modtime is not the zero time or Unix epoch, ServeContent
817
// includes it in a Last-Modified header in the response. If the
818
// request includes an If-Modified-Since header, ServeContent uses
819
// modtime to decide whether the content needs to be sent at all.
820
//
821
// The content's Seek method must work: ServeContent uses
822
// a seek to the end of the content to determine its size.
823
//
824
// If the caller has set w's ETag header formatted per RFC 7232, section 2.3,
825
// ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.
826
//
827
// Note that *os.File implements the io.ReadSeeker interface.
828
// Note that compression can be registered
829
// through `ctx.CompressWriter(true)` or `app.Use(iris.Compression)`.
830
ServeContent(content io.ReadSeeker, filename string, modtime time.Time)
831
// ServeContentWithRate same as `ServeContent` but it can throttle the speed of reading
832
// and though writing the "content" to the client.
833
ServeContentWithRate(content io.ReadSeeker, filename string, modtime time.Time, limit float64, burst int)
834
// ServeFile replies to the request with the contents of the named
835
// file or directory.
836
//
837
// If the provided file or directory name is a relative path, it is
838
// interpreted relative to the current directory and may ascend to
839
// parent directories. If the provided name is constructed from user
840
// input, it should be sanitized before calling `ServeFile`.
841
//
842
// Use it when you want to serve assets like css and javascript files.
843
// If client should confirm and save the file use the `SendFile` instead.
844
// Note that compression can be registered
845
// through `ctx.CompressWriter(true)` or `app.Use(iris.Compression)`.
846
ServeFile(filename string) error
847
// ServeFileWithRate same as `ServeFile` but it can throttle the speed of reading
848
// and though writing the file to the client.
849
ServeFileWithRate(filename string, limit float64, burst int) error
850
// SendFile sends a file as an attachment, that is downloaded and saved locally from client.
851
// Note that compression can be registered
852
// through `ctx.CompressWriter(true)` or `app.Use(iris.Compression)`.
853
// Use `ServeFile` if a file should be served as a page asset instead.
854
SendFile(src string, destName string) error
855
// SendFileWithRate same as `SendFile` but it can throttle the speed of reading
856
// and though writing the file to the client.
857
SendFileWithRate(src, destName string, limit float64, burst int) error
858
// AddCookieOptions adds cookie options for `SetCookie`,
859
// `SetCookieKV, UpsertCookie` and `RemoveCookie` methods
860
// for the current request. It can be called from a middleware before
861
// cookies sent or received from the next Handler in the chain.
862
//
863
// Available builtin Cookie options are:
864
// * CookieAllowReclaim
865
// * CookieAllowSubdomains
866
// * CookieSecure
867
// * CookieHTTPOnly
868
// * CookieSameSite
869
// * CookiePath
870
// * CookieCleanPath
871
// * CookieExpires
872
// * CookieEncoding
873
//
874
// Example at: https://github.com/kataras/iris/tree/master/_examples/cookies/securecookie
875
AddCookieOptions(options ...CookieOption)
876
// ClearCookieOptions clears any previously registered cookie options.
877
// See `AddCookieOptions` too.
878
ClearCookieOptions()
879
// SetCookie adds a cookie.
880
// Use of the "options" is not required, they can be used to amend the "cookie".
881
//
882
// Example: https://github.com/kataras/iris/tree/master/_examples/cookies/basic
883
SetCookie(cookie *iris.Cookie, options ...CookieOption)
884
// UpsertCookie adds a cookie to the response like `SetCookie` does
885
// but it will also perform a replacement of the cookie
886
// if already set by a previous `SetCookie` call.
887
// It reports whether the cookie is new (true) or an existing one was updated (false).
888
UpsertCookie(cookie *iris.Cookie, options ...CookieOption) bool
889
// SetCookieKV adds a cookie, requires the name(string) and the value(string).
890
//
891
// By default it expires at 2 hours and it's added to the root path,
892
// use the `CookieExpires` and `CookiePath` to modify them.
893
// Alternatively: ctx.SetCookie(&iris.Cookie{...})
894
//
895
// If you want to set custom the path:
896
// ctx.SetCookieKV(name, value, iris.CookiePath("/custom/path/cookie/will/be/stored"))
897
//
898
// If you want to be visible only to current request path:
899
// (note that client should be responsible for that if server sent an empty cookie's path, all browsers are compatible)
900
// ctx.SetCookieKV(name, value, iris.CookieCleanPath/iris.CookiePath(""))
901
// More:
902
// iris.CookieExpires(time.Duration)
903
// iris.CookieHTTPOnly(false)
904
//
905
// Examples: https://github.com/kataras/iris/tree/master/_examples/cookies/basic
906
SetCookieKV(name, value string, options ...CookieOption)
907
// GetCookie returns cookie's value by its name
908
// returns empty string if nothing was found.
909
//
910
// If you want more than the value then:
911
// cookie, err := ctx.Request().Cookie("name")
912
//
913
// Example: https://github.com/kataras/iris/tree/master/_examples/cookies/basic
914
GetCookie(name string, options ...CookieOption) string
915
// RemoveCookie deletes a cookie by its name and path = "/".
916
// Tip: change the cookie's path to the current one by: RemoveCookie("name", iris.CookieCleanPath)
917
//
918
// Example: https://github.com/kataras/iris/tree/master/_examples/cookies/basic
919
RemoveCookie(name string, options ...CookieOption)
920
// VisitAllCookies takes a visitor function which is called
921
// on each (request's) cookies' name and value.
922
VisitAllCookies(visitor func(name string, value string))
923
// MaxAge returns the "cache-control" request header's value
924
// seconds as int64
925
// if header not found or parse failed then it returns -1.
926
MaxAge() int64
927
// Record transforms the context's basic and direct responseWriter to a *ResponseRecorder
928
// which can be used to reset the body, reset headers, get the body,
929
// get & set the status code at any time and more.
930
Record()
931
// Recorder returns the context's ResponseRecorder
932
// if not recording then it starts recording and returns the new context's ResponseRecorder
933
Recorder() *ResponseRecorder
934
// IsRecording returns the response recorder and a true value
935
// when the response writer is recording the status code, body, headers and so on,
936
// else returns nil and false.
937
IsRecording() (*ResponseRecorder, bool)
938
// BeginTransaction starts a scoped transaction.
939
//
940
// Can't say a lot here because it will take more than 200 lines to write about.
941
// You can search third-party articles or books on how Business Transaction works (it's quite simple, especially here).
942
//
943
// Note that this is unique and new
944
// (=I haver never seen any other examples or code in Golang on this subject, so far, as with the most of iris features...)
945
// it's not covers all paths,
946
// such as databases, this should be managed by the libraries you use to make your database connection,
947
// this transaction scope is only for context's response.
948
// Transactions have their own middleware ecosystem also.
949
//
950
// See https://github.com/kataras/iris/tree/master/_examples/ for more
951
BeginTransaction(pipe func(t *Transaction))
952
// SkipTransactions if called then skip the rest of the transactions
953
// or all of them if called before the first transaction
954
SkipTransactions()
955
// TransactionsSkipped returns true if the transactions skipped or canceled at all.
956
TransactionsSkipped() bool
957
// Exec calls the framewrok's ServeHTTPC
958
// based on this context but with a changed method and path
959
// like it was requested by the user, but it is not.
960
//
961
// Offline means that the route is registered to the iris and have all features that a normal route has
962
// BUT it isn't available by browsing, its handlers executed only when other handler's context call them
963
// it can validate paths, has sessions, path parameters and all.
964
//
965
// You can find the Route by app.GetRoute("theRouteName")
966
// you can set a route name as: myRoute := app.Get("/mypath", handler)("theRouteName")
967
// that will set a name to the route and returns its RouteInfo instance for further usage.
968
//
969
// It doesn't changes the global state, if a route was "offline" it remains offline.
970
//
971
// app.None(...) and app.GetRoutes().Offline(route)/.Online(route, method)
972
//
973
// Example: https://github.com/kataras/iris/tree/master/_examples/routing/route-state
974
//
975
// User can get the response by simple using rec := ctx.Recorder(); rec.Body()/rec.StatusCode()/rec.Header().
976
//
977
// context's Values and the Session are kept in order to be able to communicate via the result route.
978
//
979
// It's for extreme use cases, 99% of the times will never be useful for you.
980
Exec(method string, path string)
981
// RouteExists reports whether a particular route exists
982
// It will search from the current subdomain of context's host, if not inside the root domain.
983
RouteExists(method, path string) bool
984
// ReflectValue caches and returns a []reflect.Value{reflect.ValueOf(ctx)}.
985
// It's just a helper to maintain variable inside the context itself.
986
ReflectValue() []reflect.Value
987
// Controller returns a reflect Value of the custom Controller from which this handler executed.
988
// It will return a Kind() == reflect.Invalid if the handler was not executed from within a controller.
989
Controller() reflect.Value
990
// RegisterDependency registers a struct or slice
991
// or pointer to struct dependency at request-time
992
// for the next handler in the chain. One value per type.
993
// Note that it's highly recommended to register
994
// your dependencies before server ran
995
// through Party.ConfigureContainer or mvc.Application.Register
996
// in sake of minimum performance cost.
997
//
998
// See `UnregisterDependency` too.
999
RegisterDependency(v interface{})
1000
// UnregisterDependency removes a dependency based on its type.
1001
// Reports whether a dependency with that type was found and removed successfully.
1002
UnregisterDependency(typ reflect.Type) bool
1003
// Application returns the iris app instance which belongs to this context.
1004
// Worth to notice that this function returns an interface
1005
// of the Application, which contains methods that are safe
1006
// to be executed at serve-time. The full app's fields
1007
// and methods are not available here for the developer's safety.
1008
Application() Application
1009
// SetErr is just a helper that sets an error value
1010
// as a context value, it does nothing more.
1011
// Also, by-default this error's value is written to the client
1012
// on failures when no registered error handler is available (see `Party.On(Any)ErrorCode`).
1013
// See `GetError` to retrieve it back.
1014
//
1015
// Note that, if you want to stop the chain
1016
// with an error see the `StopWithError` instead.
1017
SetErr(err error)
Copied!
Last modified 1yr ago
Export as PDF
Copy link