Documentation ¶
Index ¶
- Constants
- Variables
- func AddGzipHeaders(w ResponseWriter)
- func CookieCleanPath(c *http.Cookie)
- func DecodeQuery(path string) string
- func DecodeURL(uri string) string
- func DefaultNext(ctx Context)
- func Do(ctx Context, handlers Handlers)
- func FormValueDefault(r *http.Request, name string, def string, postMaxMemory int64, resetBody bool) string
- func GetBody(r *http.Request, resetBody bool) ([]byte, error)
- func GetForm(r *http.Request, postMaxMemory int64, resetBody bool) (form map[string][]string, found bool)
- func GetHost(r *http.Request) string
- func HandlerFileLine(h Handler) (file string, line int)
- func HandlerName(h Handler) string
- func IsZeroTime(t time.Time) bool
- func LastCapturedContextID() uint64
- func MainHandlerName(handlers Handlers) (name string)
- func ParamResolverByTypeAndIndex(typ reflect.Type, paramIndex int) (reflect.Value, bool)
- func WriteJSON(writer io.Writer, v interface{}, options JSON, enableOptimization ...bool) (int, error)
- func WriteJSONP(writer io.Writer, v interface{}, options JSONP, enableOptimization ...bool) (int, error)
- func WriteMarkdown(writer io.Writer, markdownB []byte, options Markdown) (int, error)
- func WriteXML(writer io.Writer, v interface{}, options XML) (int, error)
- func XMLMap(elementName string, v Map) xml.Marshaler
- type Application
- type BodyDecoder
- type ConfigurationReadOnly
- type ContentNegotiator
- type ContentSelector
- type Context
- type CookieDecoder
- type CookieEncoder
- type CookieOption
- type Filter
- type GzipResponseWriter
- func (w *GzipResponseWriter) BeginGzipResponse(underline ResponseWriter)
- func (w *GzipResponseWriter) Disable()
- func (w *GzipResponseWriter) EndResponse()
- func (w *GzipResponseWriter) FlushResponse()
- func (w *GzipResponseWriter) ResetBody()
- func (w *GzipResponseWriter) Write(contents []byte) (int, error)
- func (w *GzipResponseWriter) WriteNow(contents []byte) (int, error)
- func (w *GzipResponseWriter) WriteString(s string) (n int, err error)
- func (w *GzipResponseWriter) Writef(format string, a ...interface{}) (n int, err error)
- type Handler
- type Handlers
- type I18nReadOnly
- type JSON
- type JSONP
- type Locale
- type Map
- type Markdown
- type N
- type NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Binary() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Charset(charset ...string) *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Encoding(encoding ...string) *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) EncodingGzip() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) HTML() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) JSON() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) JSONP() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) MIME(mimeType ...string) *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Markdown() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Override() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Problem() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Text() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) XML() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) YAML() *NegotiationAcceptBuilder
- type NegotiationBuilder
- func (n *NegotiationBuilder) Any(v ...interface{}) *NegotiationBuilder
- func (n *NegotiationBuilder) Binary(v ...[]byte) *NegotiationBuilder
- func (n *NegotiationBuilder) Build() (contentType, charset, encoding string, content interface{})
- func (n *NegotiationBuilder) Charset(charset ...string) *NegotiationBuilder
- func (n *NegotiationBuilder) Clear() *NegotiationBuilder
- func (n *NegotiationBuilder) Encoding(encoding ...string) *NegotiationBuilder
- func (n *NegotiationBuilder) EncodingGzip() *NegotiationBuilder
- func (n *NegotiationBuilder) HTML(v ...string) *NegotiationBuilder
- func (n *NegotiationBuilder) JSON(v ...interface{}) *NegotiationBuilder
- func (n *NegotiationBuilder) JSONP(v ...interface{}) *NegotiationBuilder
- func (n *NegotiationBuilder) MIME(mime string, content interface{}) *NegotiationBuilder
- func (n *NegotiationBuilder) Markdown(v ...[]byte) *NegotiationBuilder
- func (n *NegotiationBuilder) Problem(v ...interface{}) *NegotiationBuilder
- func (n *NegotiationBuilder) Text(v ...string) *NegotiationBuilder
- func (n *NegotiationBuilder) XML(v ...interface{}) *NegotiationBuilder
- func (n *NegotiationBuilder) YAML(v ...interface{}) *NegotiationBuilder
- type Pool
- type Problem
- func (p Problem) Cause(cause Problem) Problem
- func (p Problem) Detail(detail string) Problem
- func (p Problem) Error() string
- func (p Problem) GetTempKey(key string) interface{}
- func (p Problem) Instance(instanceURI string) Problem
- func (p Problem) Key(key string, value interface{}) Problem
- func (p Problem) MarshalXML(e *xml.Encoder, start xml.StartElement) error
- func (p Problem) Status(statusCode int) Problem
- func (p Problem) TempKey(key string, value interface{}) Problem
- func (p Problem) Title(title string) Problem
- func (p Problem) Type(uri string) Problem
- func (p Problem) Validate() bool
- type ProblemOptions
- type Referrer
- type ReferrerGoogleSearchType
- type ReferrerType
- type RequestParams
- func (r RequestParams) Get(key string) string
- func (r RequestParams) GetDecoded(key string) string
- func (r *RequestParams) GetEntry(key string) memstore.Entry
- func (r *RequestParams) GetEntryAt(index int) memstore.Entry
- func (r RequestParams) GetEscape(key string) string
- func (r RequestParams) GetIntUnslashed(key string) (int, bool)
- func (r RequestParams) GetTrim(key string) string
- func (r *RequestParams) Set(key, value string)
- func (r *RequestParams) Visit(visitor func(key string, value string))
- type ResponseRecorder
- func (w *ResponseRecorder) BeginRecord(underline ResponseWriter)
- func (w *ResponseRecorder) Body() []byte
- func (w *ResponseRecorder) ClearHeaders()
- func (w *ResponseRecorder) Clone() ResponseWriter
- func (w *ResponseRecorder) EndResponse()
- func (w *ResponseRecorder) Flush()
- func (w *ResponseRecorder) FlushResponse()
- func (w *ResponseRecorder) Naive() http.ResponseWriter
- func (w *ResponseRecorder) Push(target string, opts *http.PushOptions) error
- func (w *ResponseRecorder) Reset()
- func (w *ResponseRecorder) ResetBody()
- func (w *ResponseRecorder) ResetHeaders()
- func (w *ResponseRecorder) SetBody(b []byte)
- func (w *ResponseRecorder) SetBodyString(s string)
- func (w *ResponseRecorder) Write(contents []byte) (int, error)
- func (w *ResponseRecorder) WriteString(s string) (n int, err error)
- func (w *ResponseRecorder) WriteTo(res ResponseWriter)
- func (w *ResponseRecorder) Writef(format string, a ...interface{}) (n int, err error)
- type ResponseWriter
- type RouteReadOnly
- type StaticSite
- type Transaction
- type TransactionErrResult
- type TransactionScope
- type TransactionScopeFunc
- type Unmarshaler
- type UnmarshalerFunc
- type XML
Constants ¶
const ( ReferrerInvalid ReferrerType = iota ReferrerIndirect ReferrerDirect ReferrerEmail ReferrerSearch ReferrerSocial ReferrerNotGoogleSearch ReferrerGoogleSearchType = iota ReferrerGoogleOrganicSearch ReferrerGoogleAdwords )
Contains the available values of the goreferrer enums.
const ( // ContentTypeHeaderKey is the header key of "Content-Type". ContentTypeHeaderKey = "Content-Type" // LastModifiedHeaderKey is the header key of "Last-Modified". LastModifiedHeaderKey = "Last-Modified" // IfModifiedSinceHeaderKey is the header key of "If-Modified-Since". IfModifiedSinceHeaderKey = "If-Modified-Since" // CacheControlHeaderKey is the header key of "Cache-Control". CacheControlHeaderKey = "Cache-Control" // ETagHeaderKey is the header key of "ETag". ETagHeaderKey = "ETag" // ContentDispositionHeaderKey is the header key of "Content-Disposition". ContentDispositionHeaderKey = "Content-Disposition" // ContentLengthHeaderKey is the header key of "Content-Length" ContentLengthHeaderKey = "Content-Length" // ContentEncodingHeaderKey is the header key of "Content-Encoding". ContentEncodingHeaderKey = "Content-Encoding" // GzipHeaderValue is the header value of "gzip". GzipHeaderValue = "gzip" // AcceptEncodingHeaderKey is the header key of "Accept-Encoding". AcceptEncodingHeaderKey = "Accept-Encoding" // VaryHeaderKey is the header key of "Vary". VaryHeaderKey = "Vary" )
const ( // ContentBinaryHeaderValue header value for binary data. ContentBinaryHeaderValue = "application/octet-stream" // ContentHTMLHeaderValue is the string of text/html response header's content type value. ContentHTMLHeaderValue = "text/html" // ContentJSONHeaderValue header value for JSON data. ContentJSONHeaderValue = "application/json" // ContentJSONProblemHeaderValue header value for JSON API problem error. // Read more at: https://tools.ietf.org/html/rfc7807 ContentJSONProblemHeaderValue = "application/problem+json" // ContentXMLProblemHeaderValue header value for XML API problem error. // Read more at: https://tools.ietf.org/html/rfc7807 ContentXMLProblemHeaderValue = "application/problem+xml" // ContentJavascriptHeaderValue header value for JSONP & Javascript data. ContentJavascriptHeaderValue = "application/javascript" // ContentTextHeaderValue header value for Text data. ContentTextHeaderValue = "text/plain" // ContentXMLHeaderValue header value for XML data. ContentXMLHeaderValue = "text/xml" // ContentXMLUnreadableHeaderValue obselete header value for XML. ContentXMLUnreadableHeaderValue = "application/xml" // ContentMarkdownHeaderValue custom key/content type, the real is the text/html. ContentMarkdownHeaderValue = "text/markdown" // ContentYAMLHeaderValue header value for YAML data. ContentYAMLHeaderValue = "application/x-yaml" // ContentFormHeaderValue header value for post form data. ContentFormHeaderValue = "application/x-www-form-urlencoded" // ContentFormMultipartHeaderValue header value for post multipart form data. ContentFormMultipartHeaderValue = "multipart/form-data" )
const ( // NoWritten !=-1 => when nothing written before NoWritten = -1 // StatusCodeWritten != 0 => when only status code written StatusCodeWritten = 0 )
const (
// NoLayout to disable layout for a particular template file
NoLayout = "iris.nolayout"
)
Variables ¶
var DefaultJSONOptions = JSON{}
DefaultJSONOptions is the optional settings that are being used inside `ctx.JSON`.
var DefaultJSONPOptions = JSONP{}
DefaultJSONPOptions is the optional settings that are being used inside `ctx.JSONP`.
var DefaultMarkdownOptions = Markdown{}
DefaultMarkdownOptions is the optional settings that are being used from `WriteMarkdown` and `ctx.Markdown`.
var DefaultProblemOptions = ProblemOptions{ JSON: JSON{Indent: " "}, XML: XML{Indent: " "}, }
DefaultProblemOptions the default options for `Context.Problem` method.
var DefaultProblemStatusCode = http.StatusBadRequest
DefaultProblemStatusCode is being sent to the client when Problem's status is not a valid one.
var DefaultXMLOptions = XML{}
DefaultXMLOptions is the optional settings that are being used from `ctx.XML`.
var ErrContentNotSupported = errors.New("unsupported content")
ErrContentNotSupported returns from the `Negotiate` method when server responds with 406.
var ErrGzipNotSupported = errors.New("client does not support gzip compression")
ErrGzipNotSupported may be returned from `WriteGzip` methods if the client does not support the "gzip" compression.
var ErrNotFound = errors.New("not found")
ErrNotFound is the type error which API users can make use of to check if a `Context` action of a `Handler` is type of Not Found, e.g. URL Query Parameters. Example:
n, err := context.URLParamInt("url_query_param_name")
if errors.Is(err, context.ErrNotFound) { // [handle error...] }
Another usage would be `err == context.ErrNotFound` HOWEVER prefer use the new `errors.Is` as API details may change in the future.
var ErrPreconditionFailed = errors.New("precondition failed")
ErrPreconditionFailed may be returned from `Context` methods that has to perform one or more client side preconditions before the actual check, e.g. `CheckIfModifiedSince`. Usage: ok, err := context.CheckIfModifiedSince(modTime)
if err != nil { if errors.Is(err, context.ErrPreconditionFailed) { [handle missing client conditions,such as not valid request method...] }else { [the error is probably a time parse error...] } }
var ErrPushNotSupported = errors.New("push feature is not supported by this ResponseWriter")
ErrPushNotSupported is returned by the Push method to indicate that HTTP/2 Push support is not available.
var ErrTransactionInterrupt = errors.New("transaction interrupted")
ErrTransactionInterrupt can be used to manually force-complete a Context's transaction and log(warn) the wrapped error's message. Usage: `... return fmt.Errorf("my custom error message: %w", context.ErrTransactionInterrupt)`.
var FormatTime = func(ctx Context, t time.Time) string {
return t.Format(ctx.Application().ConfigurationReadOnly().GetTimeFormat())
}
FormatTime returns a textual representation of the time value formatted according to the Application's configuration's TimeFormat field which defines the format.
Look `context#ParseTime` for the opossite operation (string to Time).
var Gzip = func(ctx Context) { ctx.Gzip(true) ctx.Next() }
Gzip is a middleware which enables writing using gzip compression, if client supports.
var IsErrPath = schema.IsErrPath
IsErrPath can be used at `context#ReadForm` and `context#ReadQuery`. It reports whether the incoming error can be ignored when server allows unknown post values to be sent by the client.
A shortcut for the `schema#IsErrPath`.
var LimitRequestBodySize = func(maxRequestBodySizeBytes int64) Handler { return func(ctx Context) { ctx.SetMaxRequestBodySize(maxRequestBodySizeBytes) ctx.Next() } }
LimitRequestBodySize is a middleware which sets a request body size limit for all next handlers in the chain.
var Next = DefaultNext
Next is the function that executed when `ctx.Next()` is called. It can be changed to a customized one if needed (very advanced usage).
See `DefaultNext` for more information about this and why it's exported like this.
var ParamResolvers = map[reflect.Type]func(paramIndex int) interface{}{ reflect.TypeOf(""): func(paramIndex int) interface{} { return func(ctx Context) string { if ctx.Params().Len() <= paramIndex { return "" } return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(string) } }, reflect.TypeOf(int(1)): func(paramIndex int) interface{} { return func(ctx Context) int { if ctx.Params().Len() <= paramIndex { return 0 } return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int) } }, reflect.TypeOf(int8(1)): func(paramIndex int) interface{} { return func(ctx Context) int8 { if ctx.Params().Len() <= paramIndex { return 0 } return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int8) } }, reflect.TypeOf(int16(1)): func(paramIndex int) interface{} { return func(ctx Context) int16 { if ctx.Params().Len() <= paramIndex { return 0 } return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int16) } }, reflect.TypeOf(int32(1)): func(paramIndex int) interface{} { return func(ctx Context) int32 { if ctx.Params().Len() <= paramIndex { return 0 } return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int32) } }, reflect.TypeOf(int64(1)): func(paramIndex int) interface{} { return func(ctx Context) int64 { if ctx.Params().Len() <= paramIndex { return 0 } return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(int64) } }, reflect.TypeOf(uint(1)): func(paramIndex int) interface{} { return func(ctx Context) uint { if ctx.Params().Len() <= paramIndex { return 0 } return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint) } }, reflect.TypeOf(uint8(1)): func(paramIndex int) interface{} { return func(ctx Context) uint8 { if ctx.Params().Len() <= paramIndex { return 0 } return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint8) } }, reflect.TypeOf(uint16(1)): func(paramIndex int) interface{} { return func(ctx Context) uint16 { if ctx.Params().Len() <= paramIndex { return 0 } return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint16) } }, reflect.TypeOf(uint32(1)): func(paramIndex int) interface{} { return func(ctx Context) uint32 { if ctx.Params().Len() <= paramIndex { return 0 } return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint32) } }, reflect.TypeOf(uint64(1)): func(paramIndex int) interface{} { return func(ctx Context) uint64 { if ctx.Params().Len() <= paramIndex { return 0 } return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(uint64) } }, reflect.TypeOf(true): func(paramIndex int) interface{} { return func(ctx Context) bool { if ctx.Params().Len() <= paramIndex { return false } return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(bool) } }, }
ParamResolvers is the global param resolution for a parameter type for a specific go std or custom type.
Key is the specific type, which should be unique. The value is a function which accepts the parameter index and it should return the value as the parameter type evaluator expects it.
i.e [reflect.TypeOf("string")] = func(paramIndex int) interface{} { return func(ctx Context) <T> { return ctx.Params().GetEntryAt(paramIndex).ValueRaw.(<T>) } }
Read https://github.com/kataras/iris/tree/master/_examples/routing/macros for more details. Checks for total available request parameters length and parameter index based on the hero/mvc function added in order to support the MVC.HandleMany("GET", "/path/{ps}/{pssecond} /path/{ps}") when on the second requested path, the 'pssecond' should be empty.
var ParseTime = func(ctx Context, text string) (t time.Time, err error) { t, err = time.Parse(ctx.Application().ConfigurationReadOnly().GetTimeFormat(), text) if err != nil { return http.ParseTime(text) } return }
ParseTime parses a time header (such as the Date: header), trying each forth formats (or three if Application's configuration's TimeFormat is defaulted) that are allowed by HTTP/1.1: Application's configuration's TimeFormat or/and http.TimeFormat, time.RFC850, and time.ANSIC.
Look `context#FormatTime` for the opossite operation (Time to string).
var Recorder = func(ctx Context) {
ctx.Record()
ctx.Next()
}
Recorder the middleware to enable response writer recording ( ResponseWriter -> ResponseRecorder)
var RequestTransactionScope = TransactionScopeFunc(func(maybeErr TransactionErrResult, ctx Context) bool { if maybeErr.IsFailure() { ctx.ResponseWriter().SetBeforeFlush(func() { w := ctx.ResponseWriter().(*ResponseRecorder) if maybeErr.Reason != "" { w.SetBodyString(maybeErr.Reason) w.WriteHeader(maybeErr.StatusCode) ctx.ContentType(maybeErr.ContentType) } else { ctx.StatusCode(maybeErr.StatusCode) ctx.StopExecution() } }) return false } return true })
RequestTransactionScope explanation:
if scope fails (if transaction.IsFailure() == true) then the rest of the context's response (transaction or normal flow) is not written to the client, and an error status code is written instead.
var SetCookieKVExpiration = time.Duration(8760) * time.Hour
SetCookieKVExpiration is 365 days by-default you can change it or simple, use the SetCookie for more control.
See `SetCookieKVExpiration` and `CookieExpires` for more.
var StatusCodeNotSuccessful = func(statusCode int) bool {
return statusCode < 200 || statusCode >= 400
}
StatusCodeNotSuccessful defines if a specific "statusCode" is not a valid status code for a successful response. It defaults to < 200 || >= 400
Read more at `iris#DisableAutoFireStatusCode`, `iris/core/router#ErrorCodeHandler` and `iris/core/router#OnAnyErrorCode` for relative information.
Do NOT change it.
It's exported for extreme situations--special needs only, when the Iris server and the client is not following the RFC: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
var TransientTransactionScope = TransactionScopeFunc(func(maybeErr TransactionErrResult, ctx Context) bool { if maybeErr.IsFailure() { ctx.Recorder().Reset() } return true })
TransientTransactionScope explanation:
independent 'silent' scope, if transaction fails (if transaction.IsFailure() == true) then its response is not written to the real context no error is provided to the user. useful for the most cases.
Functions ¶
func AddGzipHeaders ¶
func AddGzipHeaders(w ResponseWriter)
AddGzipHeaders just adds the headers "Vary" to "Accept-Encoding" and "Content-Encoding" to "gzip".
func CookieCleanPath ¶
CookieCleanPath is a `CookieOption`. Use it to clear the cookie's Path field, exactly the same as `CookiePath("")`.
func DecodeQuery ¶
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 DecodeURL ¶
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 DefaultNext ¶
func DefaultNext(ctx Context)
DefaultNext is the default function that executed on each middleware if `ctx.Next()` is called.
DefaultNext calls the next handler from the handlers chain by registration order, it should be used inside a middleware.
It can be changed to a customized one if needed (very advanced usage).
Developers are free to customize the whole or part of the Context's implementation by implementing a new `context.Context` (see https://github.com/kataras/iris/tree/master/_examples/routing/custom-context) or by just override the `context.Next` package-level field, `context.DefaultNext` is exported in order to be able for developers to merge your customized version one with the default behavior as well.
func Do ¶
Do calls the SetHandlers(handlers) 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 FormValueDefault ¶
func FormValueDefault(r *http.Request, name string, def string, postMaxMemory int64, resetBody bool) string
FormValueDefault retruns a single parsed form value.
func GetForm ¶
func GetForm(r *http.Request, postMaxMemory int64, resetBody bool) (form map[string][]string, found bool)
GetForm returns the request form (url queries, post or multipart) values.
func HandlerFileLine ¶
HandlerFileLine returns the handler's file and line information. See `context.HandlerFileLine` to get the file, line of the current running handler in the chain.
func HandlerName ¶
HandlerName returns the handler's function name. See `context.HandlerName` to get function name of the current running handler in the chain.
func IsZeroTime ¶
IsZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
func LastCapturedContextID ¶
func LastCapturedContextID() uint64
LastCapturedContextID returns the total number of `context#String` calls.
func MainHandlerName ¶
MainHandlerName tries to find the main handler than end-developer registered on the provided chain of handlers and returns its function name.
func ParamResolverByTypeAndIndex ¶
ParamResolverByTypeAndIndex will return a function that can be used to bind path parameter's exact value by its Go std type and the parameter's index based on the registered path. Usage: nameResolver := ParamResolverByKindAndKey(reflect.TypeOf(""), 0) Inside a Handler: nameResolver.Call(ctx)[0]
it will return the reflect.Value Of the exact type of the parameter(based on the path parameters and macros).
It is only useful for dynamic binding of the parameter, it is used on "hero" package and it should be modified only when Macros are modified in such way that the default selections for the available go std types are not enough.
Returns empty value and false if "k" does not match any valid parameter resolver.
func WriteJSON ¶
func WriteJSON(writer io.Writer, v interface{}, options JSON, enableOptimization ...bool) (int, error)
WriteJSON marshals the given interface object and writes the JSON response to the 'writer'. Ignores StatusCode, Gzip, StreamingJSON options.
func WriteJSONP ¶
func WriteJSONP(writer io.Writer, v interface{}, options JSONP, enableOptimization ...bool) (int, error)
WriteJSONP marshals the given interface object and writes the JSON response to the writer.
func WriteMarkdown ¶
WriteMarkdown parses the markdown to html and writes these contents to the writer.
Types ¶
type Application ¶
type Application interface { // ConfigurationReadOnly returns all the available configuration values can be used on a request. ConfigurationReadOnly() ConfigurationReadOnly // Logger returns the golog logger instance(pointer) that is being used inside the "app". Logger() *golog.Logger // I18nReadOnly returns the i18n's read-only features. I18nReadOnly() I18nReadOnly // View executes and write the result of a template file to the writer. // // Use context.View to render templates to the client instead. // Returns an error on failure, otherwise nil. View(writer io.Writer, filename string, layout string, bindingData interface{}) error // ServeHTTPC is the internal router, it's visible because it can be used for advanced use cases, // i.e: routing within a foreign context. // // It is ready to use after Build state. ServeHTTPC(ctx Context) // ServeHTTP is the main router handler which calls the .Serve and acquires a new context from the pool. // // It is ready to use after Build state. ServeHTTP(w http.ResponseWriter, r *http.Request) // GetRouteReadOnly returns the registered "read-only" route based on its name, otherwise nil. // One note: "routeName" should be case-sensitive. Used by the context to get the current route. // It returns an interface instead to reduce wrong usage and to keep the decoupled design between // the context and the routes. // // Look core/router/APIBuilder#GetRoute for more. GetRouteReadOnly(routeName string) RouteReadOnly // GetRoutesReadOnly returns the registered "read-only" routes. // // Look core/router/APIBuilder#GetRoutes for more. GetRoutesReadOnly() []RouteReadOnly // FireErrorCode executes an error http status code handler // based on the context's status code. // // If a handler is not already registered, // then it creates & registers a new trivial handler on the-fly. FireErrorCode(ctx Context) // RouteExists reports whether a particular route exists // It will search from the current subdomain of context's host, if not inside the root domain. RouteExists(ctx Context, method, path string) bool // FindClosestPaths returns a list of "n" paths close to "path" under the given "subdomain". // // Order may change. FindClosestPaths(subdomain, searchPath string, n int) []string }
Application is the context's owner. This interface contains the functions that can be used with safety inside a Handler by `context.Application()`.
type BodyDecoder ¶
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/http_request/read-custom-per-type/main.go
type ConfigurationReadOnly ¶
type ConfigurationReadOnly interface { // GetVHost returns the non-exported vhost config field. // // If original addr ended with :443 or :80, it will return the host without the port. // If original addr was :https or :http, it will return localhost. // If original addr was 0.0.0.0, it will return localhost. GetVHost() string // GetDisablePathCorrection returns the configuration.DisablePathCorrection, // DisablePathCorrection corrects and redirects the requested path to the registered path // for example, if /home/ path is requested but no handler for this Route found, // then the Router checks if /home handler exists, if yes, // (permant)redirects the client to the correct path /home. GetDisablePathCorrection() bool // GetDisablePathCorrectionRedirection returns the Configuration#DisablePathCorrectionRedirection field. // If DisablePathCorrectionRedirection set to true then it will fire the handler of the matching route without // the last slash ("/") instead of send a redirection status. GetDisablePathCorrectionRedirection() bool // GetEnablePathEscape is the configuration.EnablePathEscape, // returns true when its escapes the path, the named parameters (if any). GetEnablePathEscape() bool // GetEnableOptimizations returns whether // the application has performance optimizations enabled. GetEnableOptimizations() bool // GetFireMethodNotAllowed returns the configuration.FireMethodNotAllowed. GetFireMethodNotAllowed() bool // GetDisableBodyConsumptionOnUnmarshal returns the configuration.GetDisableBodyConsumptionOnUnmarshal, // manages the reading behavior of the context's body readers/binders. // If returns true then the body consumption by the `context.UnmarshalBody/ReadJSON/ReadXML` // is disabled. // // By-default io.ReadAll` is used to read the body from the `context.Request.Body which is an `io.ReadCloser`, // if this field set to true then a new buffer will be created to read from and the request body. // The body will not be changed and existing data before the // context.UnmarshalBody/ReadJSON/ReadXML will be not consumed. GetDisableBodyConsumptionOnUnmarshal() bool // GetDisableAutoFireStatusCode returns the configuration.DisableAutoFireStatusCode. // Returns true when the http error status code handler automatic execution turned off. GetDisableAutoFireStatusCode() bool // GetTimeFormat returns the configuration.TimeFormat, // format for any kind of datetime parsing. GetTimeFormat() string // GetCharset returns the configuration.Charset, // the character encoding for various rendering // used for templates and the rest of the responses. GetCharset() string // GetPostMaxMemory returns the maximum configured post data size // that a client can send to the server, this differs // from the overral request body size which can be modified // by the `context#SetMaxRequestBodySize` or `iris#LimitRequestBodySize`. // // Defaults to 32MB or 32 << 20 if you prefer. GetPostMaxMemory() int64 // GetTranslateLanguageContextKey returns the configuration's LocaleContextKey value, // used for i18n. Defaults to "iris.locale". GetLocaleContextKey() string // GetViewLayoutContextKey returns the key of the context's user values' key // which is being used to set the template // layout from a middleware or the main handler. // Overrides the parent's or the configuration's. GetViewLayoutContextKey() string // GetViewDataContextKey returns the key of the context's user values' key // which is being used to set the template // binding data from a middleware or the main handler. GetViewDataContextKey() string // GetRemoteAddrHeaders returns the allowed request headers names // that can be valid to parse the client's IP based on. // // Defaults to: // "X-Real-Ip": true, // "X-Forwarded-For": true, // "CF-Connecting-IP": false // // Look `context.RemoteAddr()` for more. GetRemoteAddrHeaders() map[string]bool // GetOther returns the configuration.Other map. GetOther() map[string]interface{} }
ConfigurationReadOnly can be implemented by Configuration, it's being used inside the Context. All methods that it contains should be "safe" to be called by the context at "serve time". A configuration field may be missing when it's not safe or its useless to be called from a request handler.
type ContentNegotiator ¶
type ContentNegotiator interface { // mime and charset can be retrieved by: // mime, charset := Context.Negotiation().Build() // Pass this method to `Context.Negotiate` method // to write custom content. // Overriding the existing behavior of Context.Negotiate for selecting values based on // content types, although it can accept any custom mime type with []byte. // Content type is already set. // Use it with caution, 99.9% you don't need this but it's here for extreme cases. Negotiate(ctx Context) (int, error) }
ContentNegotiator is the interface which structs can implement to override the `Context.Negotiate` default implementation and manually respond to the client based on a manuall call of `Context.Negotiation().Build()` to get the final negotiated mime and charset. It can be passed to the `Context.Negotiate` method.
type ContentSelector ¶
type ContentSelector interface {
SelectContent(mime string) interface{}
}
ContentSelector is the interface which structs can implement to manually choose a content based on the negotiated mime (content type). It can be passed to the `Context.Negotiate` method.
See the `N` struct too.
type Context ¶
type Context interface { // BeginRequest is executing once for each request // it should prepare the (new or acquired from pool) context's fields for the new request. // // To follow the iris' flow, developer should: // 1. reset handlers to nil // 2. reset values to empty // 3. reset sessions to nil // 4. reset response writer to the http.ResponseWriter // 5. reset request to the *http.Request // and any other optional steps, depends on dev's application type. BeginRequest(http.ResponseWriter, *http.Request) // EndRequest is executing once after a response to the request was sent and this context is useless or released. // // To follow the iris' flow, developer should: // 1. flush the response writer's result // 2. release the response writer // and any other optional steps, depends on dev's application type. EndRequest() // ResponseWriter returns an http.ResponseWriter compatible response writer, as expected. ResponseWriter() ResponseWriter // ResetResponseWriter should change or upgrade the Context's ResponseWriter. ResetResponseWriter(ResponseWriter) // Request returns the original *http.Request, as expected. Request() *http.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)). ResetRequest(r *http.Request) // SetCurrentRouteName sets the route's name internally, // in order to be able to find the correct current "read-only" Route when // end-developer calls the `GetCurrentRoute()` function. // It's being initialized by the Router, if you change that name // manually nothing really happens except that you'll get other // route via `GetCurrentRoute()`. // Instead, to execute a different path // from this context you should use the `Exec` function // or change the handlers via `SetHandlers/AddHandler` functions. SetCurrentRouteName(currentRouteName string) // GetCurrentRoute returns the current registered "read-only" route that // was being registered to this request's path. GetCurrentRoute() RouteReadOnly // Do calls the SetHandlers(handlers) // 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. Do(Handlers) // 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. // AddHandler(...Handler) // SetHandlers replaces all handlers with the new. SetHandlers(Handlers) // Handlers keeps tracking of the current handlers. Handlers() Handlers // HandlerIndex sets the current index of the // current context's handlers chain. // If -1 passed then it just returns the // current handler index without change the current index. // // Look Handlers(), Next() and StopExecution() too. HandlerIndex(n int) (currentIndex int) // Proceed is an alternative way to check if a particular handler // has been executed and called the `ctx.Next` function inside it. // 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. Proceed(Handler) bool // HandlerName returns the current handler's name, helpful for debugging. HandlerName() string // HandlerFileLine returns the current running handler's function source file and line information. // Useful mostly when debugging. HandlerFileLine() (file string, line int) // RouteName returns the route name that this handler is running on. // Note that it will return empty on not found handlers. RouteName() string // Next calls all the next handler from the handlers chain, // it should be used inside a middleware. // // Note: Custom context should override this method in order to be able to pass its own context.Context implementation. Next() // 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. NextOr(handlers ...Handler) bool // 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. NextOrNotFound() bool // 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. NextHandler() Handler // Skip skips/ignores the next handler from the handlers chain, // it should be used inside a middleware. Skip() // StopExecution if called then the following .Next calls are ignored, // as a result the next handlers in the chain will not be fire. StopExecution() // IsStopped checks and returns true if the current position of the Context is 255, // means that the StopExecution() was called. IsStopped() bool // OnConnectionClose registers the "cb" function which will fire (on its own goroutine, no need to be registered goroutine by the end-dev) // when the underlying connection has gone away. // // 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 `http#CloseNotify`. // CloseNotify may wait to notify until Request.Body has been // fully read. // // After the main Handler has returned, there is no guarantee // that the channel receives a value. // // 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 for the entire request handler chain/per route. // // Look the `ResponseWriter#CloseNotifier` for more. OnConnectionClose(fnGoroutine func()) bool // OnClose registers the callback function "cb" to the underline connection closing event using the `Context#OnConnectionClose` // and also in the end of the request handler using the `ResponseWriter#SetBeforeFlush`. // Note that you can register only one callback for the entire request handler chain/per route. // // Look the `Context#OnConnectionClose` and `ResponseWriter#SetBeforeFlush` for more. OnClose(cb func()) // 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. Params() *RequestParams // 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. Values() *memstore.Store // Method returns the request.Method, the client's http method to the server. Method() string // Path returns the full request path, // escaped if EnablePathEscape config field is true. Path() string // RequestPath returns the full request path, // based on the 'escape'. RequestPath(escape bool) string // Host returns the host part of the current url. Host() string // Subdomain returns the subdomain of this request, if any. // Note that this is a fast method which does not cover all cases. Subdomain() (subdomain string) // FindClosest returns a list of "n" paths close to // this request based on subdomain and request path. // // Order may change. // Example: https://github.com/kataras/iris/tree/master/_examples/routing/not-found-suggests FindClosest(n int) []string // IsWWW returns true if the current subdomain (if any) is www. IsWWW() bool // FullRqeuestURI returns the full URI, // including the scheme, the host and the relative requested path/resource. FullRequestURI() string // RemoteAddr tries to parse and return the real client's request IP. // // Based on allowed headers names that can be modified from Configuration.RemoteAddrHeaders. // // If parse based on these headers fail then it will return the Request's `RemoteAddr` field // which is filled by the server before the HTTP handler. // // Look `Configuration.RemoteAddrHeaders`, // `Configuration.WithRemoteAddrHeader(...)`, // `Configuration.WithoutRemoteAddrHeader(...)` for more. RemoteAddr() string // GetHeader returns the request header's value based on its name. GetHeader(name string) string // IsAjax returns true if this request is an 'ajax request'( XMLHttpRequest) // // There is no a 100% way of knowing that a request was made via Ajax. // You should never trust data coming from the client, they can be easily overcome by spoofing. // // Note that "X-Requested-With" Header can be modified by any client(because of "X-"), // so don't rely on IsAjax for really serious stuff, // try to find another way of detecting the type(i.e, content type), // there are many blogs that describe these problems and provide different kind of solutions, // it's always depending on the application you're building, // this is the reason why this `IsAjax“ is simple enough for general purpose use. // // Read more at: https://developer.mozilla.org/en-US/docs/AJAX // and https://xhr.spec.whatwg.org/ IsAjax() bool // IsMobile checks if client is using a mobile device(phone or tablet) to communicate with this server. // If the return value is true that means that the http client using a mobile // device to communicate with the server, otherwise false. // // Keep note that this checks the "User-Agent" request header. IsMobile() bool // GetReferrer extracts and returns the information from the "Referer" header as specified // in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy // or by the URL query parameter "referer". GetReferrer() Referrer // GetLocale returns the current request's `Locale` found by i18n middleware. // See `Tr` too. GetLocale() Locale // Tr returns a i18n localized message based on format with optional arguments. // See `GetLocale` too. // Example: https://github.com/kataras/iris/tree/master/_examples/i18n Tr(format string, args ...interface{}) string // Header adds a header to the response writer. Header(name string, value string) // ContentType sets the response writer's header key "Content-Type" to the 'cType'. ContentType(cType string) // GetContentType returns the response writer's header value of "Content-Type" // which may, set before with the 'ContentType'. GetContentType() string // GetContentType returns the request's header value of "Content-Type". GetContentTypeRequested() string // GetContentLength returns the request's header value of "Content-Length". // Returns 0 if header was unable to be found or its value was not a valid number. GetContentLength() int64 // StatusCode sets the status code header to the response. // Look .`GetStatusCode` too. StatusCode(statusCode int) // GetStatusCode returns the current status code of the response. // Look `StatusCode` too. GetStatusCode() int // AbsoluteURI parses the "s" and returns its absolute URI form. AbsoluteURI(s string) string // Redirect sends a redirect response to the client // to a specific url or relative path. // 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) // or 303 (StatusSeeOther) if POST method, // or StatusTemporaryRedirect(307) if that's nessecery. Redirect(urlToRedirect string, statusHeader ...int) // URLParam returns true if the url parameter exists, otherwise false. URLParamExists(name string) bool // URLParamDefault returns the get parameter from a request, // if not found then "def" is returned. URLParamDefault(name string, def string) string // URLParam returns the get parameter from a request, if any. URLParam(name string) string // URLParamTrim returns the url query parameter with trailing white spaces removed from a request. URLParamTrim(name string) string // URLParamEscape returns the escaped url query parameter from a request. URLParamEscape(name string) string // URLParamInt returns the url query parameter as int value from a request, // returns -1 and an error if parse failed. URLParamInt(name string) (int, error) // URLParamIntDefault returns the url query parameter as int value from a request, // if not found or parse failed then "def" is returned. URLParamIntDefault(name string, def int) int // URLParamInt32Default returns the url query parameter as int32 value from a request, // if not found or parse failed then "def" is returned. URLParamInt32Default(name string, def int32) int32 // URLParamInt64 returns the url query parameter as int64 value from a request, // returns -1 and an error if parse failed. URLParamInt64(name string) (int64, error) // URLParamInt64Default returns the url query parameter as int64 value from a request, // if not found or parse failed then "def" is returned. URLParamInt64Default(name string, def int64) int64 // URLParamFloat64 returns the url query parameter as float64 value from a request, // returns -1 and an error if parse failed. URLParamFloat64(name string) (float64, error) // URLParamFloat64Default returns the url query parameter as float64 value from a request, // if not found or parse failed then "def" is returned. URLParamFloat64Default(name string, def float64) float64 // URLParamBool returns the url query parameter as boolean value from a request, // returns an error if parse failed or not found. URLParamBool(name string) (bool, error) // URLParams returns a map of GET query parameters separated by comma if more than one // it returns an empty map if nothing found. URLParams() map[string]string // FormValueDefault returns a single parsed form value by its "name", // including both the URL field's query parameters and the POST or PUT form data. // // Returns the "def" if not found. FormValueDefault(name string, def string) string // FormValue returns a single parsed form value by its "name", // including both the URL field's query parameters and the POST or PUT form data. FormValue(name string) string // FormValues returns the parsed form data, including both the URL // field's query parameters and the POST or PUT form data. // // The default form's memory maximum size is 32MB, it can be changed by the // `iris#WithPostMaxMemory` configurator at main configuration passed on `app.Run`'s second argument. // // NOTE: A check for nil is necessary. FormValues() map[string][]string // PostValueDefault returns the parsed form data from POST, PATCH, // or PUT body parameters based on a "name". // // If not found then "def" is returned instead. PostValueDefault(name string, def string) string // PostValue returns the parsed form data from POST, PATCH, // or PUT body parameters based on a "name" PostValue(name string) string // PostValueTrim returns the parsed form data from POST, PATCH, // or PUT body parameters based on a "name", without trailing spaces. PostValueTrim(name string) string // PostValueInt returns the parsed form data from POST, PATCH, // or PUT body parameters based on a "name", as int. // // If not found returns -1 and a non-nil error. PostValueInt(name string) (int, error) // PostValueIntDefault returns the parsed form data from POST, PATCH, // or PUT body parameters based on a "name", as int. // // If not found returns or parse errors the "def". PostValueIntDefault(name string, def int) int // PostValueInt64 returns the parsed form data from POST, PATCH, // or PUT body parameters based on a "name", as float64. // // If not found returns -1 and a no-nil error. PostValueInt64(name string) (int64, error) // PostValueInt64Default returns the parsed form data from POST, PATCH, // or PUT body parameters based on a "name", as int64. // // If not found or parse errors returns the "def". PostValueInt64Default(name string, def int64) int64 // PostValueInt64Default returns the parsed form data from POST, PATCH, // or PUT body parameters based on a "name", as float64. // // If not found returns -1 and a non-nil error. PostValueFloat64(name string) (float64, error) // PostValueInt64Default returns the parsed form data from POST, PATCH, // or PUT body parameters based on a "name", as float64. // // If not found or parse errors returns the "def". PostValueFloat64Default(name string, def float64) float64 // PostValueInt64Default returns the parsed form data from POST, PATCH, // or PUT body parameters based on a "name", as bool. // // If not found or value is false, then it returns false, otherwise true. PostValueBool(name string) (bool, error) // PostValues returns all the parsed form data from POST, PATCH, // or PUT body parameters based on a "name" as a string slice. // // The default form's memory maximum size is 32MB, it can be changed by the // `iris#WithPostMaxMemory` configurator at main configuration passed on `app.Run`'s second argument. PostValues(name string) []string // FormFile returns the first uploaded file that received from the client. // // The default form's memory maximum size is 32MB, it can be changed by the // `iris#WithPostMaxMemory` configurator at main configuration passed on `app.Run`'s second argument. // // Example: https://github.com/kataras/iris/tree/master/_examples/http_request/upload-file FormFile(key string) (multipart.File, *multipart.FileHeader, error) // UploadFormFiles uploads any received file(s) from the client // to the system physical location "destDirectory". // // The second optional argument "before" gives caller the chance to // modify the *miltipart.FileHeader before saving to the disk, // it can be used to change a file's name based on the current request, // all FileHeader's options can be changed. You can ignore it if // you don't need to use this capability before saving a file to the disk. // // Note that it doesn't check if request body streamed. // // Returns the copied length as int64 and // a not nil error if at least one new file // can't be created due to the operating system's permissions or // http.ErrMissingFile if no file received. // // If you want to receive & accept files and manage them manually you can use the `context#FormFile` // instead and create a copy function that suits your needs, the below is for generic usage. // // The default form's memory maximum size is 32MB, it can be changed by the // `iris#WithPostMaxMemory` configurator at main configuration passed on `app.Run`'s second argument. // // See `FormFile` to a more controlled to receive a file. // // // Example: https://github.com/kataras/iris/tree/master/_examples/http_request/upload-files UploadFormFiles(destDirectory string, before ...func(Context, *multipart.FileHeader)) (n int64, err error) // NotFound emits an error 404 to the client, using the specific custom error error handler. // Note that you may need to call ctx.StopExecution() if you don't want the next handlers // to be executed. Next handlers are being executed on iris because you can alt the // error code and change it to a more specific one, i.e // users := app.Party("/users") // users.Done(func(ctx context.Context){ if ctx.StatusCode() == 400 { /* custom error code for /users */ }}) NotFound() // SetMaxRequestBodySize sets a limit to the request body size // should be called before reading the request body from the client. SetMaxRequestBodySize(limitOverBytes int64) // GetBody reads and returns the request body. // The default behavior for the http request reader is to consume the data readen // but you can change that behavior by passing the `WithoutBodyConsumptionOnUnmarshal` iris option. // // However, whenever you can use the `ctx.Request().Body` instead. GetBody() ([]byte, error) // UnmarshalBody reads the request's body and binds it to a value or pointer of any type. // Examples of usage: context.ReadJSON, context.ReadXML. // // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-custom-via-unmarshaler/main.go // // UnmarshalBody does not check about gzipped data. // Do not rely on compressed data incoming to your server. The main reason is: https://en.wikipedia.org/wiki/Zip_bomb // However you are still free to read the `ctx.Request().Body io.Reader` manually. UnmarshalBody(outPtr interface{}, unmarshaler Unmarshaler) error // ReadJSON reads JSON from request's body and binds it to a pointer of a value of any json-valid type. // // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-json/main.go ReadJSON(jsonObjectPtr interface{}) error // ReadXML reads XML from request's body and binds it to a pointer of a value of any xml-valid type. // // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-xml/main.go ReadXML(xmlObjectPtr interface{}) error // ReadYAML reads YAML from request's body and binds it to the "outPtr" value. // // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-yaml/main.go ReadYAML(outPtr interface{}) error // ReadForm binds the formObject with the form data // it supports any kind of type, including custom structs. // It will return nothing if request data are empty. // The struct field tag is "form". // // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-form/main.go ReadForm(formObject interface{}) error // ReadQuery binds the "ptr" with the url query string. The struct field tag is "url". // // Example: https://github.com/kataras/iris/blob/master/_examples/http_request/read-query/main.go ReadQuery(ptr interface{}) error // Write writes the data to the connection as part of an HTTP reply. // // If WriteHeader has not yet been called, Write calls // WriteHeader(http.StatusOK) before writing the data. If the Header // does not contain a Content-Type line, Write adds a Content-Type set // to the result of passing the initial 512 bytes of written data to // DetectContentType. // // Depending on the HTTP protocol version and the client, calling // Write or WriteHeader may prevent future reads on the // Request.Body. For HTTP/1.x requests, handlers should read any // needed request body data before writing the response. Once the // headers have been flushed (due to either an explicit Flusher.Flush // call or writing enough data to trigger a flush), the request body // may be unavailable. For HTTP/2 requests, the Go HTTP server permits // handlers to continue to read the request body while concurrently // writing the response. However, such behavior may not be supported // by all HTTP/2 clients. Handlers should read before writing if // possible to maximize compatibility. Write(body []byte) (int, error) // Writef formats according to a format specifier and writes to the response. // // Returns the number of bytes written and any write error encountered. Writef(format string, args ...interface{}) (int, error) // WriteString writes a simple string to the response. // // Returns the number of bytes written and any write error encountered. WriteString(body string) (int, error) // SetLastModified sets the "Last-Modified" based on the "modtime" input. // If "modtime" is zero then it does nothing. // // It's mostly internally on core/router and context packages. // // Note that modtime.UTC() is being used instead of just modtime, so // you don't have to know the internals in order to make that works. SetLastModified(modtime time.Time) // CheckIfModifiedSince checks if the response is modified since the "modtime". // Note that it has nothing to do with server-side caching. // It does those checks by checking if the "If-Modified-Since" request header // sent by client or a previous server response header // (e.g with WriteWithExpiration or HandleDir or Favicon etc.) // is a valid one and it's before the "modtime". // // A check for !modtime && err == nil is necessary to make sure that // it's not modified since, because it may return false but without even // had the chance to check the client-side (request) header due to some errors, // like the HTTP Method is not "GET" or "HEAD" or if the "modtime" is zero // or if parsing time from the header failed. // // It's mostly used internally, e.g. `context#WriteWithExpiration`. See `ErrPreconditionFailed` too. // // Note that modtime.UTC() is being used instead of just modtime, so // you don't have to know the internals in order to make that works. CheckIfModifiedSince(modtime time.Time) (bool, error) // WriteNotModified sends a 304 "Not Modified" status code to the client, // it makes sure that the content type, the content length headers // and any "ETag" are removed before the response sent. // // It's mostly used internally on core/router/fs.go and context methods. WriteNotModified() // WriteWithExpiration works like `Write` but it will check if a resource is modified, // based on the "modtime" input argument, // otherwise sends a 304 status code in order to let the client-side render the cached content. WriteWithExpiration(body []byte, modtime time.Time) (int, error) // StreamWriter registers the given stream writer for populating // response body. // // Access to context's and/or its' members is forbidden from writer. // // This function may be used in the following cases: // // * if response body is too big (more than iris.LimitRequestBodySize(if set)). // * if response body is streamed from slow external sources. // * if response body must be streamed to the client in chunks. // (aka `http server push`). // // receives a function which receives the response writer // and returns false when it should stop writing, otherwise true in order to continue StreamWriter(writer func(w io.Writer) bool) // +------------------------------------------------------------+ // | Body Writers with compression | // +------------------------------------------------------------+ // ClientSupportsGzip retruns true if the client supports gzip compression. ClientSupportsGzip() bool // 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) // You may re-use this function in the same handler // to write more data many times without any troubles. WriteGzip(b []byte) (int, error) // 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. TryWriteGzip(b []byte) (int, error) // GzipResponseWriter converts the current response writer into a response writer // which when its .Write called it compress the data to gzip and writes them to the client. // // Can be also disabled with its .Disable and .ResetBody to rollback to the usual response writer. GzipResponseWriter() *GzipResponseWriter // Gzip enables or disables (if enabled before) the gzip response writer,if the client // supports gzip compression, so the following response data will // be sent as compressed gzip data to the client. Gzip(enable bool) // ViewLayout sets the "layout" option if and when .View // 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. // // Note that the 'layoutTmplFile' argument can be set to iris.NoLayout || view.NoLayout // to disable the layout for a specific view render action, // it disables the engine's configuration's layout property. // // Look .ViewData and .View too. // // Example: https://github.com/kataras/iris/tree/master/_examples/view/context-view-data/ ViewLayout(layoutTmplFile string) // ViewData saves one or more key-value pair in order to be passed if and when .View // 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 .View'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 context.Map then these data are being added to the view data // and passed to the template. // // After .View, the data are not destroyed, in order to be re-used if needed (again, in the same request as everything else), // to clear the view data, developers can call: // ctx.Set(ctx.Application().ConfigurationReadOnly().GetViewDataContextKey(), nil) // // If 'key' is empty then the value is added as it's (struct or map) and developer is unable to add other value. // // Look .ViewLayout and .View too. // // Example: https://github.com/kataras/iris/tree/master/_examples/view/context-view-data/ ViewData(key string, value interface{}) // GetViewData returns the values registered by `context#ViewData`. // The return value is `map[string]interface{}`, this means that // if a custom struct registered to ViewData then this function // will try to parse it to map, if failed then the return value is nil // A check for nil is always a good practise if different // kind of values or no data are registered via `ViewData`. // // Similarly to `viewData := ctx.Values().Get("iris.viewData")` or // `viewData := ctx.Values().Get(ctx.Application().ConfigurationReadOnly().GetViewDataContextKey())`. GetViewData() map[string]interface{} // View renders a template based on the registered view engine(s). // First argument accepts the filename, relative to the view engine's Directory and Extension, // i.e: if directory is "./templates" and want to render the "./templates/users/index.html" // then you pass the "users/index.html" as the filename argument. // // The second optional argument can receive a single "view model" // that will be binded to the view template if it's not nil, // otherwise it will check for previous view data stored by the `ViewData` // even if stored at any previous handler(middleware) for the same request. // // Look .ViewData` and .ViewLayout too. // // Examples: https://github.com/kataras/iris/tree/master/_examples/view View(filename string, optionalViewModel ...interface{}) error // Binary writes out the raw bytes as binary data. Binary(data []byte) (int, error) // Text writes out a string as plain text. Text(format string, args ...interface{}) (int, error) // HTML writes out a string as text/html. HTML(format string, args ...interface{}) (int, error) // JSON marshals the given interface object and writes the JSON response. JSON(v interface{}, options ...JSON) (int, error) // JSONP marshals the given interface object and writes the JSON response. JSONP(v interface{}, options ...JSONP) (int, error) // XML marshals the given interface object and writes the XML response. // To render maps as XML see the `XMLMap` package-level function. XML(v interface{}, options ...XML) (int, error) // Problem writes a JSON or XML problem response. // Order of Problem fields are not always rendered the same. // // Behaves exactly like `Context.JSON` // but with default ProblemOptions.JSON indent of " " and // a response content type of "application/problem+json" instead. // // Use the options.RenderXML and XML fields to change this behavior and // send a response of content type "application/problem+xml" instead. // // Read more at: https://github.com/kataras/iris/wiki/Routing-error-handlers Problem(v interface{}, opts ...ProblemOptions) (int, error) // Markdown parses the markdown to html and renders its result to the client. Markdown(markdownB []byte, options ...Markdown) (int, error) // YAML parses the "v" using the yaml parser and renders its result to the client. YAML(v interface{}) (int, error) // Negotiation creates once and returns the negotiation builder // to build server-side available content for specific mime type(s) // and charset(s). // // See `Negotiate` method too. Negotiation() *NegotiationBuilder // Negotiate used for serving different representations of a resource at the same URI. // // The "v" can be a single `N` struct value. // The "v" can be any value completes the `ContentSelector` interface. // The "v" can be any value completes the `ContentNegotiator` interface. // The "v" can be any value of struct(JSON, JSONP, XML, YAML) or // string(TEXT, HTML) or []byte(Markdown, Binary) or []byte with any matched mime type. // // If the "v" is nil, the `Context.Negotitation()` builder's // content will be used instead, otherwise "v" overrides builder's content // (server mime types are still retrieved by its registered, supported, mime list) // // Set mime type priorities by `Negotiation().JSON().XML().HTML()...`. // Set charset priorities by `Negotiation().Charset(...)`. // Set encoding algorithm priorities by `Negotiation().Encoding(...)`. // Modify the accepted by // `Negotiation().Accept./Override()/.XML().JSON().Charset(...).Encoding(...)...`. // // It returns `ErrContentNotSupported` when not matched mime type(s). // // Resources: // https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Charset // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding // // Supports the above without quality values. // // Read more at: https://github.com/kataras/iris/wiki/Content-negotiation Negotiate(v interface{}) (int, error) // ServeContent serves content, headers are autoset // receives three parameters, it's low-level function, instead you can use .ServeFile(string,bool)/SendFile(string,string) // // // You can define your own "Content-Type" with `context#ContentType`, before this function call. // // This function doesn't support resuming (by range), // use ctx.SendFile or router's `HandleDir` instead. ServeContent(content io.ReadSeeker, filename string, modtime time.Time, gzipCompression bool) error // ServeFile serves a file (to send a file, a zip for example to the client you should use the `SendFile` instead) // receives two parameters // filename/path (string) // gzipCompression (bool) // // You can define your own "Content-Type" with `context#ContentType`, before this function call. // // This function doesn't support resuming (by range), // use ctx.SendFile or router's `HandleDir` instead. // // Use it when you want to serve dynamic files to the client. ServeFile(filename string, gzipCompression bool) error // SendFile sends file for force-download to the client // // Use this instead of ServeFile to 'force-download' bigger files to the client. SendFile(filename string, destinationName string) error // SetCookie adds a cookie. // Use of the "options" is not required, they can be used to amend the "cookie". // // Example: https://github.com/kataras/iris/tree/master/_examples/cookies/basic SetCookie(cookie *http.Cookie, options ...CookieOption) // SetCookieKV adds a cookie, requires the name(string) and the value(string). // // By default it expires at 2 hours and it's added to the root path, // use the `CookieExpires` and `CookiePath` to modify them. // Alternatively: ctx.SetCookie(&http.Cookie{...}) // // If you want to set custom the path: // ctx.SetCookieKV(name, value, iris.CookiePath("/custom/path/cookie/will/be/stored")) // // If you want to be visible only to current request path: // ctx.SetCookieKV(name, value, iris.CookieCleanPath/iris.CookiePath("")) // More: // iris.CookieExpires(time.Duration) // iris.CookieHTTPOnly(false) // // Example: https://github.com/kataras/iris/tree/master/_examples/cookies/basic SetCookieKV(name, value string, options ...CookieOption) // GetCookie returns cookie's value by its name // returns empty string if nothing was found. // // If you want more than the value then: // cookie, err := ctx.Request().Cookie("name") // // Example: https://github.com/kataras/iris/tree/master/_examples/cookies/basic GetCookie(name string, options ...CookieOption) string // RemoveCookie deletes a cookie by its name and path = "/". // Tip: change the cookie's path to the current one by: RemoveCookie("name", iris.CookieCleanPath) // // Example: https://github.com/kataras/iris/tree/master/_examples/cookies/basic RemoveCookie(name string, options ...CookieOption) // VisitAllCookies accepts a visitor function which is called // on each (request's) cookies' name and value. VisitAllCookies(visitor func(name string, value string)) // MaxAge returns the "cache-control" request header's value // seconds as int64 // if header not found or parse failed then it returns -1. MaxAge() int64 // Record transforms the context's basic and direct responseWriter to a ResponseRecorder // which can be used to reset the body, reset headers, get the body, // get & set the status code at any time and more. Record() // Recorder returns the context's ResponseRecorder // if not recording then it starts recording and returns the new context's ResponseRecorder Recorder() *ResponseRecorder // IsRecording returns the response recorder and a true value // when the response writer is recording the status code, body, headers and so on, // else returns nil and false. IsRecording() (*ResponseRecorder, bool) // BeginTransaction starts a scoped transaction. // // You can search third-party articles or books on how Business Transaction works (it's quite simple, especially here). // // Note that this is unique and new // (=I haver never seen any other examples or code in Golang on this subject, so far, as with the most of iris features...) // it's not covers all paths, // such as databases, this should be managed by the libraries you use to make your database connection, // this transaction scope is only for context's response. // Transactions have their own middleware ecosystem also, look iris.go:UseTransaction. // // See https://github.com/kataras/iris/tree/master/_examples/ for more BeginTransaction(pipe func(t *Transaction)) // SkipTransactions if called then skip the rest of the transactions // or all of them if called before the first transaction SkipTransactions() // TransactionsSkipped returns true if the transactions skipped or canceled at all. TransactionsSkipped() bool // Exec calls the `context/Application#ServeCtx` // based on this context but with a changed method and 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 app.GetRoute("theRouteName") // you can set a route name as: myRoute := app.Get("/mypath", handler)("theRouteName") // that will set a name to the route and returns its RouteInfo instance for further usage. // // It doesn't changes the global state, if a route was "offline" it remains offline. // // app.None(...) and app.GetRoutes().Offline(route)/.Online(route, method) // // Example: https://github.com/kataras/iris/tree/master/_examples/routing/route-state // // User can get the response by simple using rec := ctx.Recorder(); rec.Body()/rec.StatusCode()/rec.Header(). // // Context's Values and the Session are kept in order to be able to communicate via the result route. // // It's for extreme use cases, 99% of the times will never be useful for you. Exec(method, path string) // RouteExists reports whether a particular route exists // It will search from the current subdomain of context's host, if not inside the root domain. RouteExists(method, path string) bool // Application returns the iris app instance which belongs to this context. // Worth to notice that this function returns an interface // of the Application, which contains methods that are safe // to be executed at serve-time. The full app's fields // and methods are not available here for the developer's safety. Application() Application // String returns the string representation of this request. // Each context has a unique string representation. // It can be used for simple debugging scenarios, i.e print context as string. // // What it returns? A number which declares the length of the // total `String` calls per executable application, followed // by the remote IP (the client) and finally the method:url. String() string }
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.
This context is an implementation of the context.Context sub-package. context.Context is very extensible and developers can override its methods if that is actually needed.
func NewContext ¶
func NewContext(app Application) Context
NewContext returns the default, internal, context implementation. You may use this function to embed the default context implementation to a custom one.
This context is received by the context pool.
type CookieDecoder ¶
CookieDecoder should decode the cookie value. Should accept the cookie's name as its first argument, as second argument the encoded cookie value and as third argument the decoded value ptr. Should return a decoded value or an empty one if decode operation failed. Should return an error if decode operation failed.
Note: Errors are not printed, so you have to know what you're doing, and remember: if you use AES it only supports key sizes of 16, 24 or 32 bytes. You either need to provide exactly that amount or you derive the key from what you type in.
See `CookieEncoder` too.
type CookieEncoder ¶
CookieEncoder should encode the cookie value. Should accept the cookie's name as its first argument and as second argument the cookie value ptr. Should return an encoded value or an empty one if encode operation failed. Should return an error if encode operation failed.
Note: Errors are not printed, so you have to know what you're doing, and remember: if you use AES it only supports key sizes of 16, 24 or 32 bytes. You either need to provide exactly that amount or you derive the key from what you type in.
See `CookieDecoder` too.
type CookieOption ¶
CookieOption is the type of function that is accepted on context's methods like `SetCookieKV`, `RemoveCookie` and `SetCookie` as their (last) variadic input argument to amend the end cookie's form.
Any custom or builtin `CookieOption` is valid, see `CookiePath`, `CookieCleanPath`, `CookieExpires` and `CookieHTTPOnly` for more.
func CookieDecode ¶
func CookieDecode(decode CookieDecoder) CookieOption
CookieDecode is a `CookieOption`. Provides decoding functionality when retrieving a cookie. Accepts a `CookieDecoder` and sets the cookie's value to the decoded value before return by the `GetCookie`. User of that is the `GetCookie`.
Example: https://github.com/kataras/iris/tree/master/_examples/cookies/securecookie
func CookieEncode ¶
func CookieEncode(encode CookieEncoder) CookieOption
CookieEncode is a `CookieOption`. Provides encoding functionality when adding a cookie. Accepts a `CookieEncoder` and sets the cookie's value to the encoded value. Users of that is the `SetCookie` and `SetCookieKV`.
Example: https://github.com/kataras/iris/tree/master/_examples/cookies/securecookie
func CookieExpires ¶
func CookieExpires(durFromNow time.Duration) CookieOption
CookieExpires is a `CookieOption`. Use it to change the cookie's Expires and MaxAge fields by passing the lifetime of the cookie.
func CookieHTTPOnly ¶
func CookieHTTPOnly(httpOnly bool) CookieOption
CookieHTTPOnly is a `CookieOption`. Use it to set the cookie's HttpOnly field to false or true. HttpOnly field defaults to true for `RemoveCookie` and `SetCookieKV`.
func CookiePath ¶
func CookiePath(path string) CookieOption
CookiePath is a `CookieOption`. Use it to change the cookie's Path field.
type Filter ¶
Filter is just a type of func(Handler) bool which reports whether an action must be performed based on the incoming request.
See `NewConditionalHandler` for more.
type GzipResponseWriter ¶
type GzipResponseWriter struct { ResponseWriter // contains filtered or unexported fields }
GzipResponseWriter is an upgraded response writer which writes compressed data to the underline ResponseWriter.
It's a separate response writer because iris gives you the ability to "fallback" and "roll-back" the gzip encoding if something went wrong with the response, and write http errors in plain form instead.
func AcquireGzipResponseWriter ¶
func AcquireGzipResponseWriter() *GzipResponseWriter
AcquireGzipResponseWriter returns a new *GzipResponseWriter from the pool. Releasing is done automatically when request and response is done.
func (*GzipResponseWriter) BeginGzipResponse ¶
func (w *GzipResponseWriter) BeginGzipResponse(underline ResponseWriter)
BeginGzipResponse accepts a ResponseWriter and prepares the new gzip response writer. It's being called per-handler, when caller decide to change the response writer type.
func (*GzipResponseWriter) Disable ¶
func (w *GzipResponseWriter) Disable()
Disable turns off the gzip compression for the next .Write's data, if called then the contents are being written in plain form.
func (*GzipResponseWriter) EndResponse ¶
func (w *GzipResponseWriter) EndResponse()
EndResponse called right before the contents of this response writer are flushed to the client.
func (*GzipResponseWriter) FlushResponse ¶
func (w *GzipResponseWriter) FlushResponse()
FlushResponse validates the response headers in order to be compatible with the gzip written data and writes the data to the underline ResponseWriter.
func (*GzipResponseWriter) ResetBody ¶
func (w *GzipResponseWriter) ResetBody()
ResetBody resets the response body.
func (*GzipResponseWriter) Write ¶
func (w *GzipResponseWriter) Write(contents []byte) (int, error)
Write prepares the data write to the gzip writer and finally to its underline response writer, returns the uncompressed len(contents).
func (*GzipResponseWriter) WriteNow ¶
func (w *GzipResponseWriter) WriteNow(contents []byte) (int, error)
WriteNow compresses and writes that data to the underline response writer, returns the compressed written len.
Use `WriteNow` instead of `Write` when you need to know the compressed written size before the `FlushResponse`, note that you can't post any new headers after that, so that information is not closed to the handler anymore.
func (*GzipResponseWriter) WriteString ¶
func (w *GzipResponseWriter) WriteString(s string) (n int, err error)
WriteString prepares the string data write to the gzip writer and finally to its underline response writer, returns the uncompressed len(contents).
type Handler ¶
type Handler func(Context)
A Handler responds to an HTTP request. It writes reply headers and data to the Context.ResponseWriter() and then return. Returning signals that the request is finished; it is not valid to use the Context after or concurrently with the completion of the Handler call.
Depending on the HTTP client software, HTTP protocol version, and any intermediaries between the client and the iris server, it may not be possible to read from the Context.Request().Body after writing to the context.ResponseWriter(). Cautious handlers should read the Context.Request().Body first, and then reply.
Except for reading the body, handlers should not modify the provided Context.
If Handler panics, the server (the caller of Handler) assumes that the effect of the panic was isolated to the active request. It recovers the panic, logs a stack trace to the server error log, and hangs up the connection.
func NewConditionalHandler ¶
NewConditionalHandler returns a single Handler which can be registered as a middleware. Filter is just a type of Handler which returns a boolean. Handlers here should act like middleware, they should contain `ctx.Next` to proceed to the next handler of the chain. Those "handlers" are registered to the per-request context.
It checks the "filter" and if passed then it, correctly, executes the "handlers".
If passed, this function makes sure that the Context's information about its per-request handler chain based on the new "handlers" is always updated.
If not passed, then simply the Next handler(if any) is executed and "handlers" are ignored.
Example can be found at: _examples/routing/conditional-chain.
type Handlers ¶
type Handlers []Handler
Handlers is just a type of slice of []Handler.
See `Handler` for more.
type I18nReadOnly ¶ added in v12.1.0
type I18nReadOnly interface { Tags() []language.Tag GetLocale(ctx Context) Locale Tr(lang string, format string, args ...interface{}) string }
I18nReadOnly is the interface which ontains the read-only i18n features. Read the "i18n" package fo details.
type JSON ¶
type JSON struct { // http-specific StreamingJSON bool // content-specific UnescapeHTML bool Indent string Prefix string }
JSON contains the options for the JSON (Context's) Renderer.
type Locale ¶ added in v12.1.0
type Locale interface { // Index returns the current locale index from the languages list. Index() int // Tag returns the full language Tag attached tothis Locale, // it should be uniue across different Locales. Tag() *language.Tag // Language should return the exact languagecode of this `Locale` //that the user provided on `New` function. // // Same as `Tag().String()` but it's static. Language() string // GetMessage should return translated text based n the given "key". GetMessage(key string, args ...interface{}) string }
Locale is the interface which returns from a `Localizer.GetLocale` metod. It serves the transltions based on "key" or format. See `GetMessage`.
type Map ¶
type Map = map[string]interface{}
Map is just a type alias of the map[string]interface{} type.
type Markdown ¶
type Markdown struct { // content-specific Sanitize bool }
Markdown contains the options for the Markdown (Context's) Renderer.
type N ¶
type N struct {
Text, HTML string
Markdown []byte
Binary []byte
JSON interface{}
Problem Problem
JSONP interface{}
XML interface{}
YAML interface{}
Other []byte // custom content types.
}
N is a struct which can be passed on the `Context.Negotiate` method. It contains fields which should be filled based on the `Context.Negotiation()` server side values. If no matched mime then its "Other" field will be sent, which should be a string or []byte. It completes the `ContentSelector` interface.
func (N) SelectContent ¶
SelectContent returns a content based on the matched negotiated "mime".
type NegotiationAcceptBuilder ¶
type NegotiationAcceptBuilder struct {
// contains filtered or unexported fields
}
NegotiationAcceptBuilder builds the accepted mime types and charset
and "Accept-Charset" headers respectfully. The default values are set by the client side, server can append or override those. The end result will be challenged with runtime preffered set of content types and charsets.
See the `Negotiate` method too.
func (*NegotiationAcceptBuilder) Binary ¶
func (n *NegotiationAcceptBuilder) Binary() *NegotiationAcceptBuilder
Binary adds the "application/octet-stream" as accepted client content type. Returns itself.
func (*NegotiationAcceptBuilder) Charset ¶
func (n *NegotiationAcceptBuilder) Charset(charset ...string) *NegotiationAcceptBuilder
Charset adds one or more client accepted charsets. Returns itself.
func (*NegotiationAcceptBuilder) Encoding ¶
func (n *NegotiationAcceptBuilder) Encoding(encoding ...string) *NegotiationAcceptBuilder
Encoding adds one or more client accepted encoding algorithms. Returns itself.
func (*NegotiationAcceptBuilder) EncodingGzip ¶
func (n *NegotiationAcceptBuilder) EncodingGzip() *NegotiationAcceptBuilder
EncodingGzip adds the "gzip" as accepted encoding. Returns itself.
func (*NegotiationAcceptBuilder) HTML ¶
func (n *NegotiationAcceptBuilder) HTML() *NegotiationAcceptBuilder
HTML adds the "text/html" as accepted client content type. Returns itself.
func (*NegotiationAcceptBuilder) JSON ¶
func (n *NegotiationAcceptBuilder) JSON() *NegotiationAcceptBuilder
JSON adds the "application/json" as accepted client content type. Returns itself.
func (*NegotiationAcceptBuilder) JSONP ¶
func (n *NegotiationAcceptBuilder) JSONP() *NegotiationAcceptBuilder
JSONP adds the "application/javascript" as accepted client content type. Returns itself.
func (*NegotiationAcceptBuilder) MIME ¶
func (n *NegotiationAcceptBuilder) MIME(mimeType ...string) *NegotiationAcceptBuilder
MIME adds accepted client's mime type(s). Returns itself.
func (*NegotiationAcceptBuilder) Markdown ¶
func (n *NegotiationAcceptBuilder) Markdown() *NegotiationAcceptBuilder
Markdown adds the "text/markdown" as accepted client content type. Returns itself.
func (*NegotiationAcceptBuilder) Override ¶
func (n *NegotiationAcceptBuilder) Override() *NegotiationAcceptBuilder
Override clears the default values for accept and accept charset. Returns itself.
func (*NegotiationAcceptBuilder) Problem ¶
func (n *NegotiationAcceptBuilder) Problem() *NegotiationAcceptBuilder
Problem adds the "application/problem+json" and "application/problem-xml" as accepted client content types. Returns itself.
func (*NegotiationAcceptBuilder) Text ¶
func (n *NegotiationAcceptBuilder) Text() *NegotiationAcceptBuilder
Text adds the "text/plain" as accepted client content type. Returns itself.
func (*NegotiationAcceptBuilder) XML ¶
func (n *NegotiationAcceptBuilder) XML() *NegotiationAcceptBuilder
XML adds the "text/xml" and "application/xml" as accepted client content types. Returns itself.
func (*NegotiationAcceptBuilder) YAML ¶
func (n *NegotiationAcceptBuilder) YAML() *NegotiationAcceptBuilder
YAML adds the "application/x-yaml" as accepted client content type. Returns itself.
type NegotiationBuilder ¶
type NegotiationBuilder struct { Accept NegotiationAcceptBuilder // contains filtered or unexported fields }
NegotiationBuilder returns from the `Context.Negotitation` and can be used inside chain of handlers to build server-side mime type(s), charset(s) and encoding algorithm(s) that should match with the client's Accept, Accept-Charset and Accept-Encoding headers (by-default). To modify the client's accept use its "Accept" field which it's the `NegotitationAcceptBuilder`.
See the `Negotiate` method too.
func (*NegotiationBuilder) Any ¶
func (n *NegotiationBuilder) Any(v ...interface{}) *NegotiationBuilder
Any registers a wildcard that can match any client's accept content type.
Returns itself for recursive calls.
func (*NegotiationBuilder) Binary ¶
func (n *NegotiationBuilder) Binary(v ...[]byte) *NegotiationBuilder
Binary registers the "application/octet-stream" content type and, optionally, a value that `Context.Negotiate` will render when a client accepts the "application/octet-stream" content type.
Returns itself for recursive calls.
func (*NegotiationBuilder) Build ¶
func (n *NegotiationBuilder) Build() (contentType, charset, encoding string, content interface{})
Build calculates the client's and server's mime type(s), charset(s) and encoding and returns the final content type, charset and encoding that server should render to the client. It does not clear the fields, use the `Clear` method if neeeded.
The returned "content" can be nil if the matched "contentType" does not provide any value, in that case the `Context.Negotiate(v)` must be called with a non-nil value.
func (*NegotiationBuilder) Charset ¶
func (n *NegotiationBuilder) Charset(charset ...string) *NegotiationBuilder
Charset overrides the application's config's charset (which defaults to "utf-8") that a client should match for (through Accept-Charset header or custom through `NegotitationBuilder.Accept.Override().Charset(...)` call). Do not set it if you don't know what you're doing.
Returns itself for recursive calls.
func (*NegotiationBuilder) Clear ¶
func (n *NegotiationBuilder) Clear() *NegotiationBuilder
Clear clears the prioritized mime type(s), charset(s) and any contents relative to those mime type(s). The "Accept" field is stay as it is, use its `Override` method to clear out the client's accepted mime type(s) and charset(s).
func (*NegotiationBuilder) Encoding ¶
func (n *NegotiationBuilder) Encoding(encoding ...string) *NegotiationBuilder
Encoding registers one or more encoding algorithms by name, i.e gzip, deflate. that a client should match for (through Accept-Encoding header).
Only the "gzip" can be handlded automatically as it's the only builtin encoding algorithm to serve resources.
Returns itself for recursive calls.
func (*NegotiationBuilder) EncodingGzip ¶
func (n *NegotiationBuilder) EncodingGzip() *NegotiationBuilder
EncodingGzip registers the "gzip" encoding algorithm that a client should match for (through Accept-Encoding header or call of Accept.Encoding(enc)).
It will make resources to served by "gzip" if Accept-Encoding contains the "gzip" as well.
Returns itself for recursive calls.
func (*NegotiationBuilder) HTML ¶
func (n *NegotiationBuilder) HTML(v ...string) *NegotiationBuilder
HTML registers the "text/html" content type and, optionally, a value that `Context.Negotiate` will render when a client accepts the "text/html" content type.
Returns itself for recursive calls.
func (*NegotiationBuilder) JSON ¶
func (n *NegotiationBuilder) JSON(v ...interface{}) *NegotiationBuilder
JSON registers the "application/json" content type and, optionally, a value that `Context.Negotiate` will render when a client accepts the "application/json" content type.
Returns itself for recursive calls.
func (*NegotiationBuilder) JSONP ¶
func (n *NegotiationBuilder) JSONP(v ...interface{}) *NegotiationBuilder
JSONP registers the "application/javascript" content type and, optionally, a value that `Context.Negotiate` will render when a client accepts the "application/javascript" content type.
Returns itself for recursive calls.
func (*NegotiationBuilder) MIME ¶
func (n *NegotiationBuilder) MIME(mime string, content interface{}) *NegotiationBuilder
MIME registers a mime type and optionally the value that should be rendered through `Context.Negotiate` when this mime type is accepted by client.
Returns itself for recursive calls.
func (*NegotiationBuilder) Markdown ¶
func (n *NegotiationBuilder) Markdown(v ...[]byte) *NegotiationBuilder
Markdown registers the "text/markdown" content type and, optionally, a value that `Context.Negotiate` will render when a client accepts the "text/markdown" content type.
Returns itself for recursive calls.
func (*NegotiationBuilder) Problem ¶
func (n *NegotiationBuilder) Problem(v ...interface{}) *NegotiationBuilder
Problem registers the "application/problem+xml" or "application/problem+xml" content type and, optionally, a value that `Context.Negotiate` will render when a client accepts the "application/problem+json" or the "application/problem+xml" content type.
Returns itself for recursive calls.
func (*NegotiationBuilder) Text ¶
func (n *NegotiationBuilder) Text(v ...string) *NegotiationBuilder
Text registers the "text/plain" content type and, optionally, a value that `Context.Negotiate` will render when a client accepts the "text/plain" content type.
Returns itself for recursive calls.
func (*NegotiationBuilder) XML ¶
func (n *NegotiationBuilder) XML(v ...interface{}) *NegotiationBuilder
XML registers the "text/xml" and "application/xml" content types and, optionally, a value that `Context.Negotiate` will render when a client accepts one of the "text/xml" or "application/xml" content types.
Returns itself for recursive calls.
func (*NegotiationBuilder) YAML ¶
func (n *NegotiationBuilder) YAML(v ...interface{}) *NegotiationBuilder
YAML registers the "application/x-yaml" content type and, optionally, a value that `Context.Negotiate` will render when a client accepts the "application/x-yaml" content type.
Returns itself for recursive calls.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool is the context pool, it's used inside router and the framework by itself.
It's the only one real implementation inside this package because it used widely.
func (*Pool) Attach ¶
Attach changes the pool's return value Context.
The new Context should explicitly define the `Next()` and `Do(context.Handlers)` functions.
func (*Pool) Release ¶
Release puts a Context back to its pull, this function releases its resources. See Acquire.
func (*Pool) ReleaseLight ¶
ReleaseLight will just release the object back to the pool, but the clean method is caller's responsibility now, currently this is only used on `SPABuilder`.
type Problem ¶
type Problem map[string]interface{}
Problem Details for HTTP APIs. Pass a Problem value to `context.Problem` to write an "application/problem+json" response.
Read more at: https://github.com/kataras/iris/wiki/Routing-error-handlers
func NewProblem ¶
func NewProblem() Problem
NewProblem retruns a new Problem. Head over to the `Problem` type godoc for more.
func (Problem) Detail ¶
Detail sets the problem's detail field. Example: "Optional details about the error...".
func (Problem) Error ¶
Error method completes the go error. Returns the "[Status] Title" string form of this Problem. If Problem is not a valid one, it returns "invalid problem".
func (Problem) GetTempKey ¶
GetTempKey returns the temp value based on "key" and removes it.
func (Problem) Instance ¶
Instance sets the problem's instance field. A URI reference that identifies the specific occurrence of the problem. It may or may not yield further information if dereferenced.
func (Problem) MarshalXML ¶
MarshalXML makes this Problem XML-compatible content to render.
func (Problem) Status ¶
Status sets HTTP error code for problem's status field. Example: 404
It is required.
func (Problem) TempKey ¶
TempKey sets a temporary key-value pair, which is being removed on the its first get.
func (Problem) Title ¶
Title sets the problem's title field. Example: "Your request parameters didn't validate." It is set to status Code text if missing, (e.g., "Not Found" for 404, and so on).
func (Problem) Type ¶
Type URI SHOULD resolve to HTML [W3C.REC-html5-20141028] documentation that explains how to resolve the problem. Example: "https://example.net/validation-error"
Empty URI or "about:blank", when used as a problem type, indicates that the problem has no additional semantics beyond that of the HTTP status code. When "about:blank" is used, the title is being automatically set the same as the recommended HTTP status phrase for that code (e.g., "Not Found" for 404, and so on) on `Status` call.
Relative paths are also valid when writing this Problem to an Iris Context.
type ProblemOptions ¶
type ProblemOptions struct { // JSON are the optional JSON renderer options. JSON JSON // RenderXML set to true if want to render as XML doc. // See `XML` option field too. RenderXML bool // XML are the optional XML renderer options. // Affect only when `RenderXML` field is set to true. XML XML // RetryAfter sets the Retry-After response header. // https://tools.ietf.org/html/rfc7231#section-7.1.3 // The value can be one of those: // time.Time // time.Duration for seconds // int64, int, float64 for seconds // string for duration string or for datetime string. // // Examples: // time.Now().Add(5 * time.Minute), // 300 * time.Second, // "5m", // 300 RetryAfter interface{} // A function that, if specified, can dynamically set // retry-after based on the request. Useful for ProblemOptions reusability. // Should return time.Time, time.Duration, int64, int, float64 or string. // // Overrides the RetryAfter field. RetryAfterFunc func(Context) interface{} }
ProblemOptions the optional settings when server replies with a Problem. See `Context.Problem` method and `Problem` type for more details.
func (*ProblemOptions) Apply ¶
func (o *ProblemOptions) Apply(ctx Context)
Apply accepts a Context and applies specific response-time options.
type Referrer ¶
type Referrer struct { Type ReferrerType `json:"type" form:"referrer_type" xml:"Type" yaml:"Type" toml:"Type"` Label string `json:"label" form:"referrer_form" xml:"Label" yaml:"Label" toml:"Label"` URL string `json:"url" form:"referrer_url" xml:"URL" yaml:"URL" toml:"URL"` Subdomain string `json:"subdomain" form:"referrer_subdomain" xml:"Subdomain" yaml:"Subdomain" toml:"Subdomain"` Domain string `json:"domain" form:"referrer_domain" xml:"Domain" yaml:"Domain" toml:"Domain"` Tld string `json:"tld" form:"referrer_tld" xml:"Tld" yaml:"Tld" toml:"Tld"` Path string `json:"path" form:"referrer_path" xml:"Path" yaml:"Path" toml:"Path"` Query string `json:"query" form:"referrer_query" xml:"Query" yaml:"Query" toml:"GoogleType"` GoogleType ReferrerGoogleSearchType `json:"googleType" form:"referrer_google_type" xml:"GoogleType" yaml:"GoogleType" toml:"GoogleType"` }
Referrer contains the extracted information from the `GetReferrer`
The structure contains struct tags for JSON, form, XML, YAML and TOML. Look the `GetReferrer() Referrer` and `goreferrer` external package.
type ReferrerGoogleSearchType ¶
type ReferrerGoogleSearchType = goreferrer.GoogleSearchType
ReferrerGoogleSearchType is the goreferrer enum for a google search type (organic, adwords).
type ReferrerType ¶
type ReferrerType = goreferrer.ReferrerType
ReferrerType is the goreferrer enum for a referrer type (indirect, direct, email, search, social).
type RequestParams ¶
RequestParams is a key string - value string storage which context's request dynamic path params are being kept. Empty if the route is static.
func (RequestParams) Get ¶
func (r RequestParams) Get(key string) string
Get returns a path parameter's value based on its route's dynamic path key.
func (RequestParams) GetDecoded ¶
func (r RequestParams) GetDecoded(key string) string
GetDecoded returns a path parameter's double-url-query-escaped value based on its route's dynamic path key. same as `GetEscape`.
func (*RequestParams) GetEntry ¶
func (r *RequestParams) GetEntry(key string) memstore.Entry
GetEntry will return the parameter's internal store's `Entry` based on its name/key. If not found it will return an emptry `Entry`.
func (*RequestParams) GetEntryAt ¶
func (r *RequestParams) GetEntryAt(index int) memstore.Entry
GetEntryAt will return the parameter's internal store's `Entry` based on the index. If not found it will return an emptry `Entry`.
func (RequestParams) GetEscape ¶
func (r RequestParams) GetEscape(key string) string
GetEscape returns a path parameter's double-url-query-escaped value based on its route's dynamic path key.
func (RequestParams) GetIntUnslashed ¶
func (r RequestParams) GetIntUnslashed(key string) (int, bool)
GetIntUnslashed same as Get but it removes the first slash if found. Usage: Get an id from a wildcard path.
Returns -1 and false if not path parameter with that "key" found.
func (RequestParams) GetTrim ¶
func (r RequestParams) GetTrim(key string) string
GetTrim returns a path parameter's value without trailing spaces based on its route's dynamic path key.
func (*RequestParams) Set ¶
func (r *RequestParams) Set(key, value string)
Set inserts a value to the key-value storage.
See `SetImmutable` and `Get` too.
func (*RequestParams) Visit ¶
func (r *RequestParams) Visit(visitor func(key string, value string))
Visit accepts a visitor which will be filled by the key-value params.
type ResponseRecorder ¶
type ResponseRecorder struct { ResponseWriter // contains filtered or unexported fields }
A ResponseRecorder is used mostly by context's transactions in order to record and change if needed the body, status code and headers.
Developers are not limited to manually ask to record a response. To turn on the recorder from a Handler, rec := context.Recorder()
func AcquireResponseRecorder ¶
func AcquireResponseRecorder() *ResponseRecorder
AcquireResponseRecorder returns a new *AcquireResponseRecorder from the pool. Releasing is done automatically when request and response is done.
func (*ResponseRecorder) BeginRecord ¶
func (w *ResponseRecorder) BeginRecord(underline ResponseWriter)
BeginRecord accepts its parent ResponseWriter and prepares itself, the response recorder, to record and send response to the client.
func (*ResponseRecorder) Body ¶
func (w *ResponseRecorder) Body() []byte
Body returns the body tracked from the writer so far do not use this for edit.
func (*ResponseRecorder) ClearHeaders ¶
func (w *ResponseRecorder) ClearHeaders()
ClearHeaders clears all headers, both temp and underline's response writer.
func (*ResponseRecorder) Clone ¶
func (w *ResponseRecorder) Clone() ResponseWriter
Clone returns a clone of this response writer it copies the header, status code, headers and the beforeFlush finally returns a new ResponseRecorder
func (*ResponseRecorder) EndResponse ¶
func (w *ResponseRecorder) EndResponse()
EndResponse is auto-called when the whole client's request is done, releases the response recorder and its underline ResponseWriter.
func (*ResponseRecorder) Flush ¶
func (w *ResponseRecorder) Flush()
Flush sends any buffered data to the client.
func (*ResponseRecorder) FlushResponse ¶
func (w *ResponseRecorder) FlushResponse()
FlushResponse the full body, headers and status code to the underline response writer called automatically at the end of each request.
func (*ResponseRecorder) Naive ¶
func (w *ResponseRecorder) Naive() http.ResponseWriter
Naive returns the simple, underline and original http.ResponseWriter that backends this response writer.
func (*ResponseRecorder) Push ¶
func (w *ResponseRecorder) Push(target string, opts *http.PushOptions) error
Push initiates an HTTP/2 server push. This constructs a synthetic request using the given target and options, serializes that request into a PUSH_PROMISE frame, then dispatches that request using the server's request handler. If opts is nil, default options are used.
The target must either be an absolute path (like "/path") or an absolute URL that contains a valid host and the same scheme as the parent request. If the target is a path, it will inherit the scheme and host of the parent request.
The HTTP/2 spec disallows recursive pushes and cross-authority pushes. Push may or may not detect these invalid pushes; however, invalid pushes will be detected and canceled by conforming clients.
Handlers that wish to push URL X should call Push before sending any data that may trigger a request for URL X. This avoids a race where the client issues requests for X before receiving the PUSH_PROMISE for X.
Push returns ErrPushNotSupported if the client has disabled push or if push is not supported on the underlying connection.
func (*ResponseRecorder) Reset ¶
func (w *ResponseRecorder) Reset()
Reset resets the response body, headers and the status code header.
func (*ResponseRecorder) ResetBody ¶
func (w *ResponseRecorder) ResetBody()
ResetBody resets the response body.
func (*ResponseRecorder) ResetHeaders ¶
func (w *ResponseRecorder) ResetHeaders()
ResetHeaders sets the headers to the underline's response writer's headers, may empty.
func (*ResponseRecorder) SetBody ¶
func (w *ResponseRecorder) SetBody(b []byte)
SetBody overrides the body and sets it to a slice of bytes value.
func (*ResponseRecorder) SetBodyString ¶
func (w *ResponseRecorder) SetBodyString(s string)
SetBodyString overrides the body and sets it to a string value.
func (*ResponseRecorder) Write ¶
func (w *ResponseRecorder) Write(contents []byte) (int, error)
Write Adds the contents to the body reply, it writes the contents temporarily to a value in order to be flushed at the end of the request, this method give us the opportunity to reset the body if needed.
If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType.
Depending on the HTTP protocol version and the client, calling Write or WriteHeader may prevent future reads on the Request.Body. For HTTP/1.x requests, handlers should read any needed request body data before writing the response. Once the headers have been flushed (due to either an explicit Flusher.Flush call or writing enough data to trigger a flush), the request body may be unavailable. For HTTP/2 requests, the Go HTTP server permits handlers to continue to read the request body while concurrently writing the response. However, such behavior may not be supported by all HTTP/2 clients. Handlers should read before writing if possible to maximize compatibility.
func (*ResponseRecorder) WriteString ¶
func (w *ResponseRecorder) WriteString(s string) (n int, err error)
WriteString writes a simple string to the response.
Returns the number of bytes written and any write error encountered
func (*ResponseRecorder) WriteTo ¶
func (w *ResponseRecorder) WriteTo(res ResponseWriter)
WriteTo writes a response writer (temp: status code, headers and body) to another response writer
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter http.Flusher http.Hijacker http.CloseNotifier http.Pusher // Naive returns the simple, underline and original http.ResponseWriter // that backends this response writer. Naive() http.ResponseWriter // BeginResponse receives an http.ResponseWriter // and initialize or reset the response writer's field's values. BeginResponse(http.ResponseWriter) // EndResponse is the last function which is called right before the server sent the final response. // // Here is the place which we can make the last checks or do a cleanup. EndResponse() // IsHijacked reports whether this response writer's connection is hijacked. IsHijacked() bool // Writef formats according to a format specifier and writes to the response. // // Returns the number of bytes written and any write error encountered. Writef(format string, a ...interface{}) (n int, err error) // WriteString writes a simple string to the response. // // Returns the number of bytes written and any write error encountered. WriteString(s string) (n int, err error) // StatusCode returns the status code header value. StatusCode() int // Written should returns the total length of bytes that were being written to the client. // In addition iris provides some variables to help low-level actions: // NoWritten, means that nothing were written yet and the response writer is still live. // StatusCodeWritten, means that status code was written but no other bytes are written to the client, response writer may closed. // > 0 means that the reply was written and it's the total number of bytes were written. Written() int // SetWritten sets manually a value for written, it can be // NoWritten(-1) or StatusCodeWritten(0), > 0 means body length which is useless here. SetWritten(int) // SetBeforeFlush registers the unique callback which called exactly before the response is flushed to the client. SetBeforeFlush(cb func()) // GetBeforeFlush returns (not execute) the before flush callback, or nil if not set by SetBeforeFlush. GetBeforeFlush() func() // FlushResponse should be called only once before EndResponse. // it tries to send the status code if not sent already // and calls the before flush callback, if any. // // FlushResponse can be called before EndResponse, but it should // be the last call of this response writer. FlushResponse() // clone returns a clone of this response writer // it copies the header, status code, headers and the beforeFlush finally returns a new ResponseRecorder. Clone() ResponseWriter // WiteTo writes a response writer (temp: status code, headers and body) to another response writer WriteTo(ResponseWriter) // Flusher indicates if `Flush` is supported by the client. // // The default HTTP/1.x and HTTP/2 ResponseWriter implementations // support Flusher, but ResponseWriter wrappers may not. Handlers // should always test for this ability at runtime. // // Note that even for ResponseWriters that support Flush, // if the client is connected through an HTTP proxy, // the buffered data may not reach the client until the response // completes. Flusher() (http.Flusher, bool) // CloseNotifier indicates if the protocol supports the underline connection closure notification. CloseNotifier() (http.CloseNotifier, bool) }
ResponseWriter interface is used by the context to serve an HTTP handler to construct an HTTP response.
Note: Only this ResponseWriter is an interface in order to be able for developers to change the response writer of the Context via `context.ResetResponseWriter`. The rest of the response writers implementations (ResponseRecorder & GzipResponseWriter) are coupled to the internal ResponseWriter implementation(*responseWriter).
A ResponseWriter may not be used after the Handler has returned.
func AcquireResponseWriter ¶
func AcquireResponseWriter() ResponseWriter
AcquireResponseWriter returns a new *ResponseWriter from the pool. Releasing is done automatically when request and response is done.
type RouteReadOnly ¶
type RouteReadOnly interface { // Name returns the route's name. Name() string // Method returns the route's method. Method() string // Subdomains returns the route's subdomain. Subdomain() string // Path returns the route's original registered path. Path() string // String returns the form of METHOD, SUBDOMAIN, TMPL PATH. String() string // IsOnline returns true if the route is marked as "online" (state). IsOnline() bool // IsStatic reports whether this route is a static route. // Does not contain dynamic path parameters, // is online and registered on GET HTTP Method. IsStatic() bool // StaticPath returns the static part of the original, registered route path. // if /user/{id} it will return /user // if /user/{id}/friend/{friendid:uint64} it will return /user too // if /assets/{filepath:path} it will return /assets. StaticPath() string // ResolvePath returns the formatted path's %v replaced with the args. ResolvePath(args ...string) string // Tmpl returns the path template, // it contains the parsed template // for the route's path. // May contain zero named parameters. // // Available after the build state, i.e a request handler or Iris Configurator. Tmpl() macro.Template // MainHandlerName returns the first registered handler for the route. MainHandlerName() string // StaticSites if not empty, refers to the system (or virtual if embedded) directory // and sub directories that this "GET" route was registered to serve files and folders // that contain index.html (a site). The index handler may registered by other // route, manually or automatic by the framework, // get the route by `Application#GetRouteByPath(staticSite.RequestPath)`. StaticSites() []StaticSite // GetLastMod returns the date of last modification of the file served by this route. GetLastMod() time.Time // GetChangeFreq returns the the page frequently is likely to change. GetChangeFreq() string // GetPriority returns the priority of this route's URL relative to other URLs on your site. GetPriority() float32 }
RouteReadOnly allows decoupled access to the current route inside the context.
type StaticSite ¶
StaticSite is a structure which is used as field on the `Route` and route registration on the `APIBuilder#HandleDir`. See `GetStaticSites` and `APIBuilder#HandleDir`.
func GetStaticSites ¶
func GetStaticSites(rootDir, rootRequestPath, indexName string) (sites []StaticSite)
GetStaticSites search for a relative filename of "indexName" in "rootDir" and all its subdirectories and returns a list of structures which contains the directory found an "indexName" and the request path that a route should be registered to handle this "indexName". The request path is given by the directory which an index exists on.
type Transaction ¶
type Transaction struct {
// contains filtered or unexported fields
}
Transaction gives the users the opportunity to code their route handlers cleaner and safier it receives a scope which is decided when to send an error to the user, recover from panics stop the execution of the next transactions and so on...
it's default scope is the TransientTransactionScope which is silently skips the current transaction's response if transaction.Complete accepts a non-empty error.
Create and set custom transactions scopes with transaction.SetScope.
For more information please visit the tests.
func (*Transaction) Complete ¶
func (t *Transaction) Complete(err error)
Complete completes the transaction rollback and send an error when the error is not empty. The next steps depends on its Scope.
The error can be a type of context.NewTransactionErrResult().
func (*Transaction) Context ¶
func (t *Transaction) Context() Context
Context returns the current context of the transaction.
func (*Transaction) SetScope ¶
func (t *Transaction) SetScope(scope TransactionScope)
SetScope sets the current transaction's scope iris.RequestTransactionScope || iris.TransientTransactionScope (default).
type TransactionErrResult ¶
type TransactionErrResult struct { StatusCode int // if reason is empty then the already relative registered (custom or not) // error will be executed if the scope allows that. Reason string ContentType string }
TransactionErrResult could be named also something like 'MaybeError', it is useful to send it on transaction.Complete in order to execute a custom error mesasge to the user.
in simple words it's just a 'traveler message' between the transaction and its scope. it is totally optional
func NewTransactionErrResult ¶
func NewTransactionErrResult() TransactionErrResult
NewTransactionErrResult returns a new transaction result with the given error message, it can be empty too, but if not then the transaction's scope is decided what to do with that
func (TransactionErrResult) Error ¶
func (err TransactionErrResult) Error() string
Error returns the reason given by the user or an empty string
func (TransactionErrResult) IsFailure ¶
func (err TransactionErrResult) IsFailure() bool
IsFailure returns true if this is an actual error
type TransactionScope ¶
type TransactionScope interface { // EndTransaction returns if can continue to the next transactions or not (false) // called after Complete, empty or not empty error EndTransaction(maybeErr TransactionErrResult, ctx Context) bool }
TransactionScope is the manager of the transaction's response, can be resseted and skipped from its parent context or execute an error or skip other transactions
type TransactionScopeFunc ¶
type TransactionScopeFunc func(maybeErr TransactionErrResult, ctx Context) bool
TransactionScopeFunc the transaction's scope signature
func (TransactionScopeFunc) EndTransaction ¶
func (tsf TransactionScopeFunc) EndTransaction(maybeErr TransactionErrResult, ctx Context) bool
EndTransaction ends the transaction with a callback to itself, implements the TransactionScope interface
type Unmarshaler ¶
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.
type UnmarshalerFunc ¶
UnmarshalerFunc a shortcut for the Unmarshaler interface
See 'Unmarshaler' and 'BodyDecoder' for more.
func (UnmarshalerFunc) Unmarshal ¶
func (u UnmarshalerFunc) Unmarshal(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.