Documentation ¶
Index ¶
- Constants
- Variables
- func AddCompressHeaders(h http.Header, encoding string)
- func CookieCleanPath(_ *Context, c *http.Cookie, op uint8)
- func CookieIncluded(cookie *http.Cookie, cookieNames []string) bool
- func CookieSecure(ctx *Context, c *http.Cookie, op uint8)
- func DecodeQuery(path string) string
- func DecodeURL(uri string) string
- func DefaultLogger(prefix string) (logger *golog.Logger)
- func FormValueDefault(r *http.Request, name string, def string, postMaxMemory int64, resetBody bool) string
- func GetBody(r *http.Request, resetBody bool) ([]byte, error)
- func GetDomain(hostport string) string
- func GetEncoding(r *http.Request, offers []string) (string, error)
- func GetForm(r *http.Request, postMaxMemory int64, resetBody bool) (form map[string][]string, found bool)
- func GetHost(r *http.Request) string
- func GetScheme(r *http.Request) string
- func GetSubdomainFull(r *http.Request) string
- func HandlerFileLine(h interface{}) (file string, line int)
- func HandlerFileLineRel(h interface{}) (file string, line int)
- func HandlerName(h interface{}) string
- func HandlersNames(handlers ...interface{}) string
- func IgnoreHandlerName(name string) bool
- func IsZeroTime(t time.Time) bool
- func MainHandlerName(handlers ...interface{}) (name string, index int)
- func ParamResolverByTypeAndIndex(typ reflect.Type, paramIndex int) (reflect.Value, bool)
- func RegisterApplication(app Application)
- func SetHandlerName(original string, replacement string)
- func StatusText(code int) string
- func TrimHeaderValue(v string) string
- func WriteJSON(writer io.Writer, v interface{}, options JSON, optimize bool) (int, error)
- func WriteJSONP(writer io.Writer, v interface{}, options JSONP, optimize bool) (int, error)
- func WriteMarkdown(writer io.Writer, markdownB []byte, options Markdown) (int, error)
- func WriteXML(writer io.Writer, v interface{}, options XML, optimize bool) (int, error)
- func XMLMap(elementName string, v Map) xml.Marshaler
- type Application
- type BodyDecoder
- type CompressReader
- type CompressResponseWriter
- func (w *CompressResponseWriter) EndResponse()
- func (w *CompressResponseWriter) Flush()
- func (w *CompressResponseWriter) FlushHeaders()
- func (w *CompressResponseWriter) FlushResponse()
- func (w *CompressResponseWriter) Reset() bool
- func (w *CompressResponseWriter) Write(p []byte) (int, error)
- func (w *CompressResponseWriter) WriteTo(dest io.Writer, p []byte) (int, error)
- type CompressWriter
- type ConfigurationReadOnly
- type ContentNegotiator
- type ContentSelector
- type Context
- func (ctx *Context) AbsoluteURI(s string) string
- func (ctx *Context) AddCookieOptions(options ...CookieOption)
- func (ctx *Context) AddHandler(handlers ...Handler)
- func (ctx *Context) Application() Application
- func (ctx *Context) BeginRequest(w http.ResponseWriter, r *http.Request)
- func (ctx *Context) BeginTransaction(pipe func(t *Transaction))
- func (ctx *Context) Binary(data []byte) (int, error)
- func (ctx *Context) CallFunc(name string, args ...interface{}) ([]reflect.Value, error)
- func (ctx *Context) CheckIfModifiedSince(modtime time.Time) (bool, error)
- func (ctx *Context) ClearCookieOptions()
- func (ctx *Context) ClientSupportsEncoding(encodings ...string) bool
- func (ctx *Context) Clone() *Context
- func (ctx *Context) CompressReader(enable bool) error
- func (ctx *Context) CompressWriter(enable bool) error
- func (ctx *Context) ContentType(cType string)
- func (ctx *Context) Controller() reflect.Value
- func (ctx *Context) Do(handlers Handlers)
- func (ctx *Context) Domain() string
- func (ctx *Context) EndRequest()
- func (ctx *Context) Exec(method string, path string)
- func (ctx *Context) FallbackView(providers ...FallbackViewProvider)
- func (ctx *Context) FindClosest(n int) []string
- func (ctx *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (ctx *Context) FormFiles(key string, before ...func(*Context, *multipart.FileHeader) bool) (files []multipart.File, headers []*multipart.FileHeader, err error)
- func (ctx *Context) FormValue(name string) string
- func (ctx *Context) FormValueDefault(name string, def string) string
- func (ctx *Context) FormValues() map[string][]string
- func (ctx *Context) FullRequestURI() string
- func (ctx *Context) GetBody() ([]byte, error)
- func (ctx *Context) GetContentLength() int64
- func (ctx *Context) GetContentType() string
- func (ctx *Context) GetContentTypeRequested() string
- func (ctx *Context) GetCookie(name string, options ...CookieOption) string
- func (ctx *Context) GetCurrentRoute() RouteReadOnly
- func (ctx *Context) GetErr() error
- func (ctx *Context) GetErrPublic() (bool, error)
- func (ctx *Context) GetFunc(name string) (*Func, bool)
- func (ctx *Context) GetHeader(name string) string
- func (ctx *Context) GetID() interface{}
- func (ctx *Context) GetLocale() Locale
- func (ctx *Context) GetReferrer() Referrer
- func (ctx *Context) GetStatusCode() int
- func (ctx *Context) GetViewData() map[string]interface{}
- func (ctx *Context) HTML(format string, args ...interface{}) (int, error)
- func (ctx *Context) HandlerFileLine() (file string, line int)
- func (ctx *Context) HandlerIndex(n int) (currentIndex int)
- func (ctx *Context) HandlerName() string
- func (ctx *Context) Handlers() Handlers
- func (ctx *Context) Header(name string, value string)
- func (ctx *Context) Host() string
- func (ctx *Context) IsAjax() bool
- func (ctx *Context) IsCanceled() bool
- func (ctx *Context) IsDebug() bool
- func (ctx *Context) IsGRPC() bool
- func (ctx *Context) IsHTTP2() bool
- func (ctx *Context) IsMobile() bool
- func (ctx *Context) IsRecording() (*ResponseRecorder, bool)
- func (ctx *Context) IsRecordingBody() bool
- func (ctx *Context) IsRecovered() (*ErrPanicRecovery, bool)
- func (ctx *Context) IsSSL() bool
- func (ctx *Context) IsScript() bool
- func (ctx *Context) IsStopped() bool
- func (ctx *Context) IsWWW() bool
- func (ctx *Context) JSON(v interface{}, opts ...JSON) (n int, err error)
- func (ctx *Context) JSONP(v interface{}, opts ...JSONP) (int, error)
- func (ctx *Context) Logout(args ...interface{}) error
- func (ctx *Context) Markdown(markdownB []byte, opts ...Markdown) (int, error)
- func (ctx *Context) MaxAge() int64
- func (ctx *Context) Method() string
- func (ctx *Context) MsgPack(v interface{}) (int, error)
- func (ctx *Context) Negotiate(v interface{}) (int, error)
- func (ctx *Context) Negotiation() *NegotiationBuilder
- func (ctx *Context) Next()
- func (ctx *Context) NextHandler() Handler
- func (ctx *Context) NextOr(handlers ...Handler) bool
- func (ctx *Context) NextOrNotFound() bool
- func (ctx *Context) NotFound()
- func (ctx *Context) OnClose(cb Handler)
- func (ctx *Context) OnCloseErr(cb func() error)
- func (ctx *Context) OnConnectionClose(cb Handler) bool
- func (ctx *Context) OnConnectionCloseErr(cb func() error) bool
- func (ctx *Context) Params() *RequestParams
- func (ctx *Context) Path() string
- func (ctx *Context) PostValue(name string) string
- func (ctx *Context) PostValueBool(name string) (bool, error)
- func (ctx *Context) PostValueDefault(name string, def string) string
- func (ctx *Context) PostValueFloat64(name string) (float64, error)
- func (ctx *Context) PostValueFloat64Default(name string, def float64) float64
- func (ctx *Context) PostValueInt(name string) (int, error)
- func (ctx *Context) PostValueInt64(name string) (int64, error)
- func (ctx *Context) PostValueInt64Default(name string, def int64) int64
- func (ctx *Context) PostValueIntDefault(name string, def int) int
- func (ctx *Context) PostValueMany(name string) (string, error)
- func (ctx *Context) PostValueTrim(name string) string
- func (ctx *Context) PostValues(name string) ([]string, error)
- func (ctx *Context) Problem(v interface{}, opts ...ProblemOptions) (int, error)
- func (ctx *Context) Proceed(h Handler) bool
- func (ctx *Context) Protobuf(v proto.Message) (int, error)
- func (ctx *Context) ReadBody(ptr interface{}) error
- func (ctx *Context) ReadForm(formObject interface{}) error
- func (ctx *Context) ReadHeaders(ptr interface{}) error
- func (ctx *Context) ReadJSON(outPtr interface{}, opts ...JSONReader) error
- func (ctx *Context) ReadJSONProtobuf(ptr proto.Message, opts ...ProtoUnmarshalOptions) error
- func (ctx *Context) ReadJSONStream(onDecode func(DecodeFunc) error, opts ...JSONReader) error
- func (ctx *Context) ReadMsgPack(ptr interface{}) error
- func (ctx *Context) ReadParams(ptr interface{}) error
- func (ctx *Context) ReadProtobuf(ptr proto.Message) error
- func (ctx *Context) ReadQuery(ptr interface{}) error
- func (ctx *Context) ReadURL(ptr interface{}) error
- func (ctx *Context) ReadXML(outPtr interface{}) error
- func (ctx *Context) ReadYAML(outPtr interface{}) error
- func (ctx *Context) Record()
- func (ctx *Context) RecordRequestBody(b bool)
- func (ctx *Context) Recorder() *ResponseRecorder
- func (ctx *Context) Redirect(urlToRedirect string, statusHeader ...int)
- func (ctx *Context) ReflectValue() []reflect.Value
- func (ctx *Context) RegisterDependency(v interface{})
- func (ctx *Context) RemoteAddr() string
- func (ctx *Context) RemoveCookie(name string, options ...CookieOption)
- func (ctx *Context) Request() *http.Request
- func (ctx *Context) RequestPath(escape bool) string
- func (ctx *Context) ResetQuery()
- func (ctx *Context) ResetRequest(r *http.Request)
- func (ctx *Context) ResetResponseWriter(newResponseWriter ResponseWriter)
- func (ctx *Context) ResponseWriter() ResponseWriter
- func (ctx *Context) ResumeExecution() bool
- func (ctx *Context) RouteExists(method, path string) bool
- func (ctx *Context) RouteName() string
- func (ctx *Context) SaveFormFile(fh *multipart.FileHeader, dest string) (int64, error)
- func (ctx *Context) Scheme() string
- func (ctx *Context) SendFile(src string, destName string) error
- func (ctx *Context) SendFileWithRate(src, destName string, limit float64, burst int) error
- func (ctx *Context) ServeContent(content io.ReadSeeker, filename string, modtime time.Time)
- func (ctx *Context) ServeContentWithRate(content io.ReadSeeker, filename string, modtime time.Time, limit float64, ...)
- func (ctx *Context) ServeFile(filename string) error
- func (ctx *Context) ServeFileWithRate(filename string, limit float64, burst int) error
- func (ctx *Context) SetCookie(cookie *http.Cookie, options ...CookieOption)
- func (ctx *Context) SetCookieKV(name, value string, options ...CookieOption)
- func (ctx *Context) SetCurrentRoute(route RouteReadOnly)
- func (ctx *Context) SetErr(err error)
- func (ctx *Context) SetErrPrivate(err error)
- func (ctx *Context) SetFunc(name string, fn interface{}, persistenceArgs ...interface{})
- func (ctx *Context) SetHandlers(handlers Handlers)
- func (ctx *Context) SetID(id interface{})
- func (ctx *Context) SetLanguage(langCode string)
- func (ctx *Context) SetLastModified(modtime time.Time)
- func (ctx *Context) SetLogoutFunc(fn interface{}, persistenceArgs ...interface{})
- func (ctx *Context) SetMaxRequestBodySize(limitOverBytes int64)
- func (ctx *Context) SetUser(i interface{}) error
- func (ctx *Context) Skip()
- func (ctx *Context) SkipTransactions()
- func (ctx *Context) StatusCode(statusCode int)
- func (ctx *Context) StopExecution()
- func (ctx *Context) StopWithError(statusCode int, err error)
- func (ctx *Context) StopWithJSON(statusCode int, jsonObject interface{})
- func (ctx *Context) StopWithPlainError(statusCode int, err error)
- func (ctx *Context) StopWithProblem(statusCode int, problem Problem)
- func (ctx *Context) StopWithStatus(statusCode int)
- func (ctx *Context) StopWithText(statusCode int, format string, args ...interface{})
- func (ctx *Context) StreamWriter(writer func(w io.Writer) error) error
- func (ctx *Context) String() string
- func (ctx *Context) Subdomain() (subdomain string)
- func (ctx *Context) SubdomainFull() string
- func (ctx *Context) Text(format string, args ...interface{}) (int, error)
- func (ctx *Context) TextYAML(v interface{}) (int, error)
- func (ctx *Context) Tr(key string, args ...interface{}) string
- func (ctx *Context) TransactionsSkipped() bool
- func (ctx *Context) URLParam(name string) string
- func (ctx *Context) URLParamBool(name string) (bool, error)
- func (ctx *Context) URLParamDefault(name string, def string) string
- func (ctx *Context) URLParamEscape(name string) string
- func (ctx *Context) URLParamExists(name string) bool
- func (ctx *Context) URLParamFloat64(name string) (float64, error)
- func (ctx *Context) URLParamFloat64Default(name string, def float64) float64
- func (ctx *Context) URLParamInt(name string) (int, error)
- func (ctx *Context) URLParamInt32Default(name string, def int32) int32
- func (ctx *Context) URLParamInt64(name string) (int64, error)
- func (ctx *Context) URLParamInt64Default(name string, def int64) int64
- func (ctx *Context) URLParamIntDefault(name string, def int) int
- func (ctx *Context) URLParamSlice(name string) []string
- func (ctx *Context) URLParamTrim(name string) string
- func (ctx *Context) URLParamUint64(name string) uint64
- func (ctx *Context) URLParams() map[string]string
- func (ctx *Context) URLParamsSorted() []memstore.StringEntry
- func (ctx *Context) UnmarshalBody(outPtr interface{}, unmarshaler Unmarshaler) error
- func (ctx *Context) UnregisterDependency(typ reflect.Type) bool
- func (ctx *Context) UploadFormFiles(destDirectory string, before ...func(*Context, *multipart.FileHeader) bool) (uploaded []*multipart.FileHeader, n int64, err error)
- func (ctx *Context) UpsertCookie(cookie *http.Cookie, options ...CookieOption) bool
- func (ctx *Context) User() User
- func (ctx *Context) Values() *memstore.Store
- func (ctx *Context) View(filename string, optionalViewModel ...interface{}) error
- func (ctx *Context) ViewData(key string, value interface{})
- func (ctx *Context) ViewEngine(engine ViewEngine)
- func (ctx *Context) ViewLayout(layoutTmplFile string)
- func (ctx *Context) VisitAllCookies(visitor func(name string, value string))
- func (ctx *Context) Write(rawBody []byte) (int, error)
- func (ctx *Context) WriteNotModified()
- func (ctx *Context) WriteString(body string) (n int, err error)
- func (ctx *Context) WriteWithExpiration(body []byte, modtime time.Time) (int, error)
- func (ctx *Context) Writef(format string, a ...interface{}) (n int, err error)
- func (ctx *Context) XML(v interface{}, opts ...XML) (int, error)
- func (ctx *Context) YAML(v interface{}) (int, error)
- type CookieOption
- func CookieAllowReclaim(cookieNames ...string) CookieOption
- func CookieAllowSubdomains(cookieNames ...string) CookieOption
- func CookieEncoding(encoding SecureCookie, cookieNames ...string) CookieOption
- func CookieExpires(durFromNow time.Duration) CookieOption
- func CookieHTTPOnly(httpOnly bool) CookieOption
- func CookiePath(path string) CookieOption
- func CookieSameSite(sameSite http.SameSite) CookieOption
- type DecodeFunc
- type DependenciesMap
- type ErrPanicRecovery
- type ErrPrivate
- type ErrViewNotExist
- type FallbackView
- type FallbackViewFunc
- type FallbackViewLayout
- type FallbackViewProvider
- type Filter
- type Func
- type FuncMeta
- type GlobalCounter
- type Handler
- type Handlers
- type I18nReadOnly
- type JSON
- type JSONDecoder
- type JSONEncoder
- type JSONP
- type JSONReader
- type Locale
- type Map
- type Markdown
- type N
- type NameExpr
- 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) MsgPack() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Override() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Problem() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Protobuf() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Text() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) TextYAML() *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) MsgPack(v ...interface{}) *NegotiationBuilder
- func (n *NegotiationBuilder) Problem(v ...interface{}) *NegotiationBuilder
- func (n *NegotiationBuilder) Protobuf(v ...interface{}) *NegotiationBuilder
- func (n *NegotiationBuilder) Text(v ...string) *NegotiationBuilder
- func (n *NegotiationBuilder) TextYAML(v ...interface{}) *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) DetailErr(err error) 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 ProtoMarshalOptions
- type ProtoUnmarshalOptions
- 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 RequestParamsReadOnly
- 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) CopyTo(res ResponseWriter)
- func (w *ResponseRecorder) EndResponse()
- func (w *ResponseRecorder) Flush()
- func (w *ResponseRecorder) FlushResponse()
- func (w *ResponseRecorder) Header() http.Header
- func (w *ResponseRecorder) Naive() http.ResponseWriter
- func (w *ResponseRecorder) Push(target string, opts *http.PushOptions) (err error)
- func (w *ResponseRecorder) Reset() bool
- func (w *ResponseRecorder) ResetBody()
- func (w *ResponseRecorder) ResetHeaders()
- func (w *ResponseRecorder) Result() *http.Response
- func (w *ResponseRecorder) SetBody(b []byte)
- func (w *ResponseRecorder) SetBodyString(s string)
- func (w *ResponseRecorder) Write(contents []byte) (int, error)
- type ResponseWriter
- type ResponseWriterBodyReseter
- type ResponseWriterDisabler
- type ResponseWriterReseter
- type ResponseWriterWriteTo
- type RouteReadOnly
- type SecureCookie
- type SimpleUser
- func (u *SimpleUser) GetAuthorization() (string, error)
- func (u *SimpleUser) GetAuthorizedAt() (time.Time, error)
- func (u *SimpleUser) GetEmail() (string, error)
- func (u *SimpleUser) GetField(key string) (interface{}, error)
- func (u *SimpleUser) GetID() (string, error)
- func (u *SimpleUser) GetPassword() (string, error)
- func (u *SimpleUser) GetRaw() (interface{}, error)
- func (u *SimpleUser) GetRoles() ([]string, error)
- func (u *SimpleUser) GetToken() ([]byte, error)
- func (u *SimpleUser) GetUsername() (string, error)
- type Transaction
- type TransactionErrResult
- type TransactionScope
- type TransactionScopeFunc
- type Unmarshaler
- type UnmarshalerFunc
- type User
- type UserGetPassword
- type UserGetUsername
- type UserMap
- func (u UserMap) GetAuthorization() (string, error)
- func (u UserMap) GetAuthorizedAt() (time.Time, error)
- func (u UserMap) GetEmail() (string, error)
- func (u UserMap) GetField(key string) (interface{}, error)
- func (u UserMap) GetID() (string, error)
- func (u UserMap) GetPassword() (string, error)
- func (u UserMap) GetRaw() (interface{}, error)
- func (u UserMap) GetRoles() ([]string, error)
- func (u UserMap) GetToken() ([]byte, error)
- func (u UserMap) GetUsername() (string, error)
- type UserPartial
- func (u *UserPartial) GetAuthorization() (string, error)
- func (u *UserPartial) GetAuthorizedAt() (time.Time, error)
- func (u *UserPartial) GetEmail() (string, error)
- func (u *UserPartial) GetField(key string) (interface{}, error)
- func (u *UserPartial) GetID() (string, error)
- func (u *UserPartial) GetPassword() (string, error)
- func (u *UserPartial) GetRaw() (interface{}, error)
- func (u *UserPartial) GetRoles() ([]string, error)
- func (u *UserPartial) GetToken() ([]byte, error)
- func (u *UserPartial) GetUsername() (string, error)
- type Validator
- type ViewEngine
- type ViewEngineFuncer
- type XML
Constants ¶
const ( GZIP = "gzip" DEFLATE = "deflate" BROTLI = "br" SNAPPY = "snappy" S2 = "s2" )
The available builtin compression algorithms.
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" // ContentWebassemblyHeaderValue header value for web assembly files. ContentWebassemblyHeaderValue = "application/wasm" // 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 = "text/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" // ContentYAMLTextHeaderValue header value for YAML plain text. ContentYAMLTextHeaderValue = "text/yaml" // ContentProtobufHeaderValue header value for Protobuf messages data. ContentProtobufHeaderValue = "application/x-protobuf" // ContentMsgPackHeaderValue header value for MsgPack data. ContentMsgPackHeaderValue = "application/msgpack" // ContentMsgPack2HeaderValue alternative header value for MsgPack data. ContentMsgPack2HeaderValue = "application/x-msgpack" // 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" // ContentGRPCHeaderValue Content-Type header value for gRPC. ContentGRPCHeaderValue = "application/grpc" )
const ( OpCookieGet uint8 = iota OpCookieSet OpCookieDel )
Set of Cookie actions for `CookieOption`.
const ( // NoWritten !=-1 => when nothing written before NoWritten = -1 // StatusCodeWritten != 0 => when only status code written StatusCodeWritten = 0 )
const ( // 4xx StatusPageExpired = 419 StatusBlockedByWindowsParentalControls = 450 StatusInvalidToken = 498 StatusTokenRequired = 499 // 5xx StatusBandwidthLimitExceeded = 509 StatusInvalidSSLCertificate = 526 StatusSiteOverloaded = 529 StatusSiteFrozen = 530 StatusNetworkReadTimeout = 598 )
Unofficial status error codes.
const ( // ControllerContextKey returns the context key from which // the `Context.Controller` method returns the store's value. ControllerContextKey = "iris.controller.reflect_value" )
const DependenciesContextKey = "iris.dependencies"
DependenciesContextKey is the context key for the context's value to keep the serve-time static dependencies raw values.
const IDENTITY = "identity"
IDENTITY no transformation whatsoever.
Variables ¶
var ( // ErrResponseNotCompressed returned from AcquireCompressResponseWriter // when response's Content-Type header is missing due to golang/go/issues/31753 or // when accept-encoding is empty. The caller should fallback to the original response writer. ErrResponseNotCompressed = errors.New("compress: response will not be compressed") // ErrRequestNotCompressed returned from NewCompressReader // when request is not compressed. ErrRequestNotCompressed = errors.New("compress: request is not compressed") // ErrNotSupportedCompression returned from // AcquireCompressResponseWriter, NewCompressWriter and NewCompressReader // when the request's Accept-Encoding was not found in the server's supported // compression algorithms. Check that error with `errors.Is`. ErrNotSupportedCompression = errors.New("compress: unsupported compression") )
var ( // IsErrEmptyJSON reports whether the given "err" is caused by a // Context.ReadJSON call when the request body // didn't start with { or it was totally empty. IsErrEmptyJSON = func(err error) bool { if err == nil { return false } if v, ok := err.(*json.SyntaxError); ok { return v.Offset == 0 && v.Error() == "unexpected end of JSON input" } return strings.Contains(err.Error(), "looking for beginning of value") } // 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`. IsErrPath = schema.IsErrPath // ErrEmptyForm is returned by // - `context#ReadForm` // - `context#ReadQuery` // - `context#ReadBody` // when the request data (form, query and body respectfully) is empty. ErrEmptyForm = errors.New("empty form") // ErrEmptyFormField reports whether a specific field exists but it's empty. // Usage: errors.Is(err, ErrEmptyFormField) // See postValue method. It's only returned on parsed post value methods. ErrEmptyFormField = errors.New("empty form field") // ConnectionCloseErrorSubstr if at least one of the given // substrings are found in a net.OpError:os.SyscallError error type // on `IsErrConnectionReset` then the function will report true. ConnectionCloseErrorSubstr = []string{ "broken pipe", "connection reset by peer", } // IsErrConnectionClosed reports whether the given "err" // is caused because of a broken connection. IsErrConnectionClosed = func(err error) bool { if err == nil { return false } if opErr, ok := err.(*net.OpError); ok { if syscallErr, ok := opErr.Err.(*os.SyscallError); ok { errStr := strings.ToLower(syscallErr.Error()) for _, s := range ConnectionCloseErrorSubstr { if strings.Contains(errStr, s) { return true } } } } return false } )
var ( // CookieExpireDelete may be set on Cookie.Expire for expiring the given cookie. CookieExpireDelete = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) // CookieExpireUnlimited indicates that does expires after 24 years. CookieExpireUnlimited = time.Now().AddDate(24, 10, 10) )
var ( // PackageName is the Iris Go module package name. PackageName = strings.TrimSuffix(reflect.TypeOf(Handlers{}).PkgPath(), "/context") // WorkingDir is the (initial) current directory. WorkingDir, _ = os.Getwd() )
var ( ClientErrorCodes = []int{ http.StatusBadRequest, http.StatusUnauthorized, http.StatusPaymentRequired, http.StatusForbidden, http.StatusNotFound, http.StatusMethodNotAllowed, http.StatusNotAcceptable, http.StatusProxyAuthRequired, http.StatusRequestTimeout, http.StatusConflict, http.StatusGone, http.StatusLengthRequired, http.StatusPreconditionFailed, http.StatusRequestEntityTooLarge, http.StatusRequestURITooLong, http.StatusUnsupportedMediaType, http.StatusRequestedRangeNotSatisfiable, http.StatusExpectationFailed, http.StatusTeapot, http.StatusMisdirectedRequest, http.StatusUnprocessableEntity, http.StatusLocked, http.StatusFailedDependency, http.StatusTooEarly, http.StatusUpgradeRequired, http.StatusPreconditionRequired, http.StatusTooManyRequests, http.StatusRequestHeaderFieldsTooLarge, http.StatusUnavailableForLegalReasons, StatusPageExpired, StatusBlockedByWindowsParentalControls, StatusInvalidToken, StatusTokenRequired, } // ServerErrorCodes holds the 5xx Server errors. ServerErrorCodes = []int{ http.StatusInternalServerError, http.StatusNotImplemented, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout, http.StatusHTTPVersionNotSupported, http.StatusVariantAlsoNegotiates, http.StatusInsufficientStorage, http.StatusLoopDetected, http.StatusNotExtended, http.StatusNetworkAuthenticationRequired, StatusBandwidthLimitExceeded, StatusInvalidSSLCertificate, StatusSiteOverloaded, StatusSiteFrozen, StatusNetworkReadTimeout, } // ClientAndServerErrorCodes is the static list of all client and server error codes. ClientAndServerErrorCodes = append(ClientErrorCodes, ServerErrorCodes...) )
ClientErrorCodes holds the 4xx Client errors.
AllEncodings is a slice of default content encodings. See `AcquireCompressResponseWriter`.
var Counter = NewGlobalCounter() // it's not used anywhere, currently but it's here.
Counter is the shared counter instances between Iris applications of the same process.
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 ErrHijackNotSupported = errors.New("hijack is not supported by this ResponseWriter")
ErrHijackNotSupported is returned by the Hijack method to indicate that Hijack feature is not available.
var ErrInvalidArgs = errors.New("invalid arguments")
ErrInvalidArgs fires when the `Context.CallFunc` is called with invalid number of arguments.
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 ErrNotSupported = errors.New("not supported")
ErrNotSupported is fired when a specific method is not implemented or not supported entirely. Can be used by User implementations when an authentication system does not implement a specific, but required, method of the User interface.
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 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 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.StopWithStatus(maybeErr.StatusCode) } }) 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 = 8760 * time.Hour
SetCookieKVExpiration is 365 days by-default you can change it or simple, use the SetCookie for more control.
See `CookieExpires` and `AddCookieOptions` for more.
var StatusCodeNotSuccessful = func(statusCode int) bool { return statusCode >= 400 }
StatusCodeNotSuccessful defines if a specific "statusCode" is not a valid status code for a successful response. By default if the status code is lower than 400 then it is not a failure one, otherwise it is considered as an error code.
Read more at `iris/Configuration#DisableAutoFireStatusCode` and `iris/core/router/Party#OnAnyErrorCode` for relative information.
Modify this variable when your Iris server or/and client not follows 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 AddCompressHeaders ¶ added in v12.2.0
AddCompressHeaders just adds the headers "Vary" to "Accept-Encoding" and "Content-Encoding" to the given encoding.
func CookieCleanPath ¶
CookieCleanPath is a `CookieOption`. Use it to clear the cookie's Path field, exactly the same as `CookiePath("")`.
func CookieIncluded ¶ added in v12.2.0
CookieIncluded reports whether the "cookie.Name" is in the list of "cookieNames". Notes: If "cookieNames" slice is empty then it returns true, If "cookie.Name" is empty then it returns false.
func CookieSecure ¶ added in v12.2.0
CookieSecure sets the cookie's Secure option if the current request's connection is using TLS. See `CookieHTTPOnly` too.
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 DefaultLogger ¶ added in v12.2.0
DefaultLogger returns a Logger instance for an Iris module. If the program contains at least one registered Iris Application before this call then it will return a child of that Application's Logger otherwise a fresh child of the `golog.Default` will be returned instead.
It should be used when a module has no access to the Application or its Logger.
func FormValueDefault ¶
func FormValueDefault(r *http.Request, name string, def string, postMaxMemory int64, resetBody bool) string
FormValueDefault retruns a single parsed form value.
func GetEncoding ¶ added in v12.2.0
GetEncoding extracts the best available encoding from the request.
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 GetScheme ¶ added in v12.2.0
GetScheme returns the full scheme of the request URL (https://, http:// or ws:// and e.t.c.“).
func GetSubdomainFull ¶ added in v12.2.0
GetSubdomainFull returns the full subdomain level, e.g. [test.user.]mydomain.com.
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 HandlerFileLineRel ¶ added in v12.2.0
HandlerFileLineRel same as `HandlerFileLine` but it returns the path corresponding to its relative based on the package-level "WorkingDir" variable.
func HandlerName ¶
func HandlerName(h interface{}) string
HandlerName returns the handler's function name. See `Context.HandlerName` method to get function name of the current running handler in the chain. See `SetHandlerName` too.
func HandlersNames ¶ added in v12.2.0
func HandlersNames(handlers ...interface{}) string
HandlersNames returns a slice of "handlers" names separated by commas. Can be used for debugging or to determinate if end-developer called the same exactly Use/UseRouter/Done... API methods so framework can give a warning.
func IgnoreHandlerName ¶ added in v12.2.0
IgnoreHandlerName compares a static slice of Iris builtin internal methods that should be ignored from trace. Some internal methods are kept out of this list for actual debugging.
func IsZeroTime ¶
IsZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
func MainHandlerName ¶
MainHandlerName tries to find the main handler that 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 RegisterApplication ¶ added in v12.2.0
func RegisterApplication(app Application)
RegisterApplication registers an application to the global shared storage.
func SetHandlerName ¶ added in v12.2.0
SetHandlerName sets a handler name that could be fetched through `HandlerName`. The "original" should be the Go's original regexp-featured (can be retrieved through a `HandlerName` call) function name. The "replacement" should be the custom, human-text of that function name.
If the name starts with "iris" then it replaces that string with the full Iris module package name, e.g. iris/middleware/logger.(*requestLoggerMiddleware).ServeHTTP-fm to github.com/kataras/iris/v12/middleware/logger.(*requestLoggerMiddleware).ServeHTTP-fm for convenient between Iris versions.
func StatusText ¶ added in v12.2.0
StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.
func TrimHeaderValue ¶ added in v12.2.0
TrimHeaderValue returns the "v[0:first space or semicolon]".
func WriteJSON ¶
WriteJSON marshals the given interface object and writes the JSON response to the 'writer'. Ignores StatusCode and StreamingJSON options.
func WriteJSONP ¶
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 // IsDebug reports whether the application is running // under debug/development mode. // It's just a shortcut of Logger().Level >= golog.DebugLevel. // The same method existss as Context.IsDebug() too. IsDebug() bool // I18nReadOnly returns the i18n's read-only features. I18nReadOnly() I18nReadOnly // Validate validates a value and returns nil if passed or // the failure reason if not. Validate(interface{}) error // Minifier returns the minifier instance. // By default it can minifies: // - text/html // - text/css // - image/svg+xml // - application/text(javascript, ecmascript, json, xml). // Use that instance to add custom Minifiers before server ran. Minifier() *minify.M // 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) // Shutdown gracefully terminates all the application's server hosts and any tunnels. // Returns an error on the first failure, otherwise nil. Shutdown(ctx stdContext.Context) error // 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 handles the response's error response. // If `Configuration.ResetOnFireErrorCode()` is true // and the response writer was a recorder or a gzip writer one // then it will try to reset the headers and the body before calling the // registered (or default) error handler for that error code set by // `ctx.StatusCode` method. 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 // String returns the Application's Name. String() string }
Application is the context's owner. This interface contains the functions that can be used with safety inside a Handler by `context.Application()`.
func GetApplication ¶ added in v12.2.0
func GetApplication(appName string) (Application, bool)
GetApplication returns a registered Application based on its name. If the "appName" is not unique across Applications, then it will return the newest one.
func GetApplications ¶ added in v12.2.0
func GetApplications() []Application
GetApplications returns a slice of all the registered Applications.
func LastApplication ¶ added in v12.2.0
func LastApplication() Application
LastApplication returns the last registered Application. Handlers has access to the current Application, use `Context.Application()` instead.
func MustGetApplication ¶ added in v12.2.0
func MustGetApplication(appName string) Application
MustGetApplication same as `GetApplication` but it panics if "appName" is not a registered Application's name.
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/request-body/read-custom-per-type/main.go
type CompressReader ¶ added in v12.2.0
type CompressReader struct { io.ReadCloser // We need this to reset the body to its original state, if requested. Src io.ReadCloser // Encoding is the compression alogirthm is used to decompress and read the data. Encoding string }
CompressReader is a structure which wraps a compressed reader. It is used for determination across common request body and a compressed one.
func NewCompressReader ¶ added in v12.2.0
func NewCompressReader(src io.Reader, encoding string) (*CompressReader, error)
NewCompressReader returns a new "compressReader" wrapper of "src". It returns `ErrRequestNotCompressed` if client's request data are not compressed or `ErrNotSupportedCompression` if server missing the decompression algorithm. Note: on server-side the request body (src) will be closed automaticaly.
type CompressResponseWriter ¶ added in v12.2.0
type CompressResponseWriter struct { CompressWriter ResponseWriter http.Hijacker Disabled bool Encoding string Level int }
CompressResponseWriter is a compressed data http.ResponseWriter.
func AcquireCompressResponseWriter ¶ added in v12.2.0
func AcquireCompressResponseWriter(w ResponseWriter, r *http.Request, level int) (*CompressResponseWriter, error)
AcquireCompressResponseWriter returns a CompressResponseWriter from the pool. It accepts an Iris response writer, a net/http request value and the level of compression (use -1 for default compression level).
It returns the best candidate among "gzip", "defate", "br", "snappy" and "s2" based on the request's "Accept-Encoding" header value.
func (*CompressResponseWriter) EndResponse ¶ added in v12.2.0
func (w *CompressResponseWriter) EndResponse()
EndResponse reeases the writers.
func (*CompressResponseWriter) Flush ¶ added in v12.2.0
func (w *CompressResponseWriter) Flush()
Flush sends any buffered data to the client. Can be called manually.
func (*CompressResponseWriter) FlushHeaders ¶ added in v12.2.0
func (w *CompressResponseWriter) FlushHeaders()
FlushHeaders deletes the encoding headers if the compressed writer was disabled otherwise removes the content-length so next callers can re-calculate the correct length.
func (*CompressResponseWriter) FlushResponse ¶ added in v12.2.0
func (w *CompressResponseWriter) FlushResponse()
FlushResponse flushes any data, closes the underline compress writer and writes the status code. Called automatically before `EndResponse`.
func (*CompressResponseWriter) Reset ¶ added in v12.2.0
func (w *CompressResponseWriter) Reset() bool
Reset implements the ResponseWriterReseter interface.
type CompressWriter ¶ added in v12.2.0
type CompressWriter interface { io.WriteCloser // All known implementations contain `Flush` and `Reset` methods, // so we wanna declare them upfront. Flush() error Reset(io.Writer) }
CompressWriter is an interface which all compress writers should implement.
func NewCompressWriter ¶ added in v12.2.0
NewCompressWriter returns a CompressWriter of "w" based on the given "encoding".
type ConfigurationReadOnly ¶
type ConfigurationReadOnly interface { // GetVHost returns the non-exported vhost config field. GetVHost() string // GetLogLevel returns the LogLevel field. GetLogLevel() string // GetSocketSharding returns the SocketSharding field. GetSocketSharding() bool // GetKeepAlive returns the KeepAlive field. GetKeepAlive() time.Duration // GetDisablePathCorrection returns the DisablePathCorrection field GetDisablePathCorrection() bool // GetDisablePathCorrectionRedirection returns the DisablePathCorrectionRedirection field. GetDisablePathCorrectionRedirection() bool // GetEnablePathIntelligence returns the EnablePathIntelligence field. GetEnablePathIntelligence() bool // GetEnablePathEscape returns the EnablePathEscape field. GetEnablePathEscape() bool // GetForceLowercaseRouting returns the ForceLowercaseRouting field. GetForceLowercaseRouting() bool // GetFireMethodNotAllowed returns the FireMethodNotAllowed field. GetFireMethodNotAllowed() bool // GetDisableAutoFireStatusCode returns the DisableAutoFireStatusCode field. GetDisableAutoFireStatusCode() bool // ResetOnFireErrorCode retruns the ResetOnFireErrorCode field. GetResetOnFireErrorCode() bool // GetEnableOptimizations returns the EnableOptimizations field. GetEnableOptimizations() bool // GetDisableBodyConsumptionOnUnmarshal returns the DisableBodyConsumptionOnUnmarshal field. GetDisableBodyConsumptionOnUnmarshal() bool // GetFireEmptyFormError returns the FireEmptyFormError field. GetFireEmptyFormError() bool // GetTimeFormat returns the TimeFormat field. GetTimeFormat() string // GetCharset returns the Charset field. GetCharset() string // GetPostMaxMemory returns the PostMaxMemory field. GetPostMaxMemory() int64 // GetTranslateLanguageContextKey returns the LocaleContextKey field. GetLocaleContextKey() string // GetLanguageContextKey returns the LanguageContextKey field. GetLanguageContextKey() string // GetLanguageInputContextKey returns the LanguageInputContextKey field. GetLanguageInputContextKey() string // GetVersionContextKey returns the VersionContextKey field. GetVersionContextKey() string // GetVersionAliasesContextKey returns the VersionAliasesContextKey field. GetVersionAliasesContextKey() string // GetViewEngineContextKey returns the ViewEngineContextKey field. GetViewEngineContextKey() string // GetViewLayoutContextKey returns the ViewLayoutContextKey field. GetViewLayoutContextKey() string // GetViewDataContextKey returns the ViewDataContextKey field. GetViewDataContextKey() string // GetFallbackViewContextKey returns the FallbackViewContextKey field. GetFallbackViewContextKey() string // GetRemoteAddrHeaders returns RemoteAddrHeaders field. GetRemoteAddrHeaders() []string // GetRemoteAddrHeadersForce returns RemoteAddrHeadersForce field. GetRemoteAddrHeadersForce() bool // GetRemoteAddrPrivateSubnets returns the RemoteAddrPrivateSubnets field. GetRemoteAddrPrivateSubnets() []netutil.IPRange // GetSSLProxyHeaders returns the SSLProxyHeaders field. GetSSLProxyHeaders() map[string]string // GetHostProxyHeaders returns the HostProxyHeaders field. GetHostProxyHeaders() map[string]bool // GetOther returns the Other field. 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 struct {
// contains filtered or unexported fields
}
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.
func NewContext ¶
func NewContext(app Application) *Context
NewContext returns a new Context instance.
func (*Context) AbsoluteURI ¶
AbsoluteURI parses the "s" and returns its absolute URI form.
func (*Context) AddCookieOptions ¶ added in v12.2.0
func (ctx *Context) AddCookieOptions(options ...CookieOption)
AddCookieOptions adds cookie options for `SetCookie`, `SetCookieKV, UpsertCookie` and `RemoveCookie` methods for the current request. It can be called from a middleware before cookies sent or received from the next Handler in the chain.
Available builtin Cookie options are:
- CookieAllowReclaim
- CookieAllowSubdomains
- CookieSecure
- CookieHTTPOnly
- CookieSameSite
- CookiePath
- CookieCleanPath
- CookieExpires
- CookieEncoding
Example at: https://github.com/kataras/iris/tree/master/_examples/cookies/securecookie
func (*Context) AddHandler ¶
AddHandler can add handler(s) to the current request in serve-time, these handlers are not persistenced to the router.
Router is calling this function to add the route's handler. If AddHandler called then the handlers will be inserted to the end of the already-defined route's handler.
func (*Context) Application ¶
func (ctx *Context) Application() Application
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.
func (*Context) BeginRequest ¶
func (ctx *Context) BeginRequest(w http.ResponseWriter, r *http.Request)
BeginRequest is executing once for each request it should prepare the (new or acquired from pool) context's fields for the new request. Do NOT call it manually. Framework calls it automatically.
Resets 1. handlers to nil. 2. values to empty. 3. the defer function. 4. response writer to the http.ResponseWriter. 5. request to the *http.Request.
func (*Context) BeginTransaction ¶
func (ctx *Context) BeginTransaction(pipe func(t *Transaction))
BeginTransaction starts a scoped transaction.
Can't say a lot here because it will take more than 200 lines to write about. 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.
See https://github.com/kataras/iris/tree/master/_examples/ for more
func (*Context) CallFunc ¶ added in v12.2.0
CallFunc calls the function registered by the `SetFunc`. The input arguments MUST match the expected ones.
If the registered function was just a handler or a handler which returns an error or a simple function or a simple function which returns an error then this operation will perform without any serious cost, otherwise reflection will be used instead, which may slow down the overall performance.
Retruns ErrNotFound if the function was not registered.
For a more complete solution without limiations navigate through the Iris Dependency Injection feature instead.
func (*Context) CheckIfModifiedSince ¶
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. See `ErrPreconditionFailed` too.
It's mostly used internally, e.g. `context#WriteWithExpiration`.
func (*Context) ClearCookieOptions ¶ added in v12.2.0
func (ctx *Context) ClearCookieOptions()
ClearCookieOptions clears any previously registered cookie options. See `AddCookieOptions` too.
func (*Context) ClientSupportsEncoding ¶ added in v12.2.0
ClientSupportsEncoding reports whether the client expects one of the given "encodings" compression.
Note, this method just reports back the first valid encoding it sees, meaning that request accept-encoding offers don't matter here. See `CompressWriter` too.
func (*Context) Clone ¶ added in v12.2.0
Clone returns a copy of the context that can be safely used outside the request's scope. Note that if the request-response lifecycle terminated or request canceled by the client (can be checked by `ctx.IsCanceled()`) then the response writer is totally useless. The http.Request pointer value is shared.
func (*Context) CompressReader ¶ added in v12.2.0
CompressReader accepts a boolean, which, if set to true it wraps the request body reader with a reader which decompresses request data before read. If the "enable" input argument is false then the request body will reset to the default one.
Useful when incoming request data are compressed. All future calls of `ctx.GetBody/ReadXXX/UnmarshalBody` methods will respect this option.
Usage:
app.Use(func(ctx iris.Context){ err := ctx.CompressReader(true) ctx.Next() })
More:
if cr, ok := ctx.Request().Body.(*CompressReader); ok { cr.Src // the original request body cr.Encoding // the compression algorithm. }
It returns `ErrRequestNotCompressed` if client's request data are not compressed (or empty) or `ErrNotSupportedCompression` if server missing the decompression algorithm.
func (*Context) CompressWriter ¶ added in v12.2.0
CompressWriter enables or disables the compress response writer. if the client expects a valid compression algorithm then this will change the response writer to a compress writer instead. All future write and rich write methods will respect this option. Usage:
app.Use(func(ctx iris.Context){ err := ctx.CompressWriter(true) ctx.Next() })
The recommendation is to compress data as much as possible and therefore to use this field, but some types of resources, such as jpeg images, are already compressed. Sometimes, using additional compression doesn't reduce payload size and can even make the payload longer.
func (*Context) ContentType ¶
ContentType sets the response writer's header "Content-Type" to the 'cType'.
func (*Context) Controller ¶ added in v12.2.0
Controller returns a reflect Value of the custom Controller from which this handler executed. It will return a Kind() == reflect.Invalid if the handler was not executed from within a controller.
func (*Context) Do ¶
Do sets the "handlers" as the chain and executes the first handler, handlers should not be empty.
It's used by the router, developers may use that to replace and execute handlers immediately.
func (*Context) EndRequest ¶
func (ctx *Context) EndRequest()
EndRequest is executing once after a response to the request was sent and this context is useless or released. Do NOT call it manually. Framework calls it automatically.
1. executes the OnClose function (if any). 2. flushes the response writer's result or fire any error handler. 3. releases the response writer.
func (*Context) Exec ¶
Exec calls the framewrok's ServeHTTPC 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.
func (*Context) FallbackView ¶ added in v12.2.0
func (ctx *Context) FallbackView(providers ...FallbackViewProvider)
FallbackView registers one or more fallback views for a template or a template layout. When View cannot find the given filename to execute then this "provider" is responsible to handle the error or render a different view.
Usage:
FallbackView(iris.FallbackView("fallback.html")) FallbackView(iris.FallbackViewLayout("layouts/fallback.html")) OR FallbackView(iris.FallbackViewFunc(ctx iris.Context, err iris.ErrViewNotExist) error { err.Name is the previous template name. err.IsLayout reports whether the failure came from the layout template. err.Data is the template data provided to the previous View call. [...custom logic e.g. ctx.View("fallback", err.Data)] })
func (*Context) FindClosest ¶ added in v12.1.1
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/intelligence/manual
func (*Context) FormFile ¶
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/file-server/upload-file
func (*Context) FormFiles ¶ added in v12.2.0
func (ctx *Context) FormFiles(key string, before ...func(*Context, *multipart.FileHeader) bool) (files []multipart.File, headers []*multipart.FileHeader, err error)
FormFiles same as FormFile but may return multiple file inputs based on a key, e.g. "files[]".
func (*Context) FormValue ¶
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.
func (*Context) FormValueDefault ¶
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.
func (*Context) FormValues ¶
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.
func (*Context) FullRequestURI ¶
FullRequestURI returns the full URI, including the scheme, the host and the relative requested path/resource.
func (*Context) GetBody ¶
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 or by calling the `RecordRequestBody` method.
However, whenever you can use the `ctx.Request().Body` instead.
func (*Context) GetContentLength ¶
GetContentLength returns the request's header value of "Content-Length".
func (*Context) GetContentType ¶
GetContentType returns the response writer's header value of "Content-Type".
func (*Context) GetContentTypeRequested ¶
GetContentTypeRequested returns the request's trim-ed(without the charset and priority values) header value of "Content-Type".
func (*Context) GetCookie ¶
func (ctx *Context) GetCookie(name string, options ...CookieOption) string
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
func (*Context) GetCurrentRoute ¶
func (ctx *Context) GetCurrentRoute() RouteReadOnly
GetCurrentRoute returns the current "read-only" route that was registered to this request's path.
func (*Context) GetErr ¶ added in v12.2.0
GetErr is a helper which retrieves the error value stored by `SetErr`.
Note that, if an error was stored by `SetErrPrivate` then it returns the underline/original error instead of the internal error wrapper.
func (*Context) GetErrPublic ¶ added in v12.2.0
GetErrPublic reports whether the stored error can be displayed to the client without risking to expose security server implementation to the client.
If the error is not nil, it is always the original one.
func (*Context) GetFunc ¶ added in v12.2.0
GetFunc returns the context function declaration which holds some information about the function registered under the given "name" by the `SetFunc` method.
func (*Context) GetID ¶ added in v12.2.0
func (ctx *Context) GetID() interface{}
GetID returns the Request Context's ID. It returns nil if not given by a prior `SetID` call. See `middleware/requestid` too.
func (*Context) GetLocale ¶ added in v12.1.0
GetLocale returns the current request's `Locale` found by i18n middleware. It always fallbacks to the default one. See `Tr` too.
func (*Context) GetReferrer ¶
GetReferrer extracts and returns the information from the "Referer" (or "Referrer") header and url query parameter as specified in https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy.
func (*Context) GetStatusCode ¶
GetStatusCode returns the current status code of the response. Look StatusCode too.
func (*Context) GetViewData ¶
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.view.data")` or `viewData := ctx.Values().Get(ctx.Application().ConfigurationReadOnly().GetViewDataContextKey())`.
func (*Context) HandlerFileLine ¶
HandlerFileLine returns the current running handler's function source file and line information. Useful mostly when debugging.
func (*Context) HandlerIndex ¶
HandlerIndex sets the current index of the current context's handlers chain. If n < 0 or the current handlers length is 0 then it just returns the current handler index without change the current index.
Look Handlers(), Next() and StopExecution() too.
func (*Context) HandlerName ¶
HandlerName returns the current handler's name, helpful for debugging.
func (*Context) Header ¶
Header adds a header to the response, if value is empty it removes the header by its name.
func (*Context) Host ¶
Host returns the host:port part of the request URI, calls the `Request().Host`. To get the subdomain part as well use the `Request().URL.Host` method instead. To get the subdomain only use the `Subdomain` method instead. This method makes use of the `Configuration.HostProxyHeaders` field too.
func (*Context) IsAjax ¶
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/
func (*Context) IsCanceled ¶ added in v12.2.0
IsCanceled reports whether the client canceled the request or the underlying connection has gone. Note that it will always return true when called from a goroutine after the request-response lifecycle.
func (*Context) IsDebug ¶ added in v12.2.0
IsDebug reports whether the application runs with debug log level. It is a shortcut of Application.IsDebug().
func (*Context) IsGRPC ¶ added in v12.2.0
IsGRPC reports whether the request came from a gRPC client.
func (*Context) IsHTTP2 ¶ added in v12.2.0
IsHTTP2 reports whether the protocol version for incoming request was HTTP/2. The client code always uses either HTTP/1.1 or HTTP/2.
See `IsSSL` too.
func (*Context) IsMobile ¶
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.
func (*Context) IsRecording ¶
func (ctx *Context) IsRecording() (*ResponseRecorder, bool)
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.
func (*Context) IsRecordingBody ¶ added in v12.2.0
IsRecordingBody reports whether the request body can be readen multiple times.
func (*Context) IsRecovered ¶ added in v12.2.0
func (ctx *Context) IsRecovered() (*ErrPanicRecovery, bool)
IsRecovered reports whether this handler has been recovered by the Iris recover middleware.
func (*Context) IsSSL ¶ added in v12.2.0
IsSSL reports whether the client is running under HTTPS SSL.
See `IsHTTP2` too.
func (*Context) IsStopped ¶
IsStopped reports whether the current position of the context's handlers is -1, means that the StopExecution() was called at least once.
func (*Context) JSON ¶
JSON marshals the given interface object and writes the JSON response to the client. If the value is a compatible `proto.Message` one then it only uses the options.Proto settings to marshal.
func (*Context) JSONP ¶
JSONP marshals the given interface object and writes the JSON response to the client.
func (*Context) Logout ¶ added in v12.2.0
Logout calls the registered logout function. Returns ErrNotFound if a logout function was not specified by a prior call of `SetLogoutFunc`.
func (*Context) Markdown ¶
Markdown parses the markdown to html and renders its result to the client.
func (*Context) MaxAge ¶
MaxAge returns the "cache-control" request header's value seconds as int64 if header not found or parse failed then it returns -1.
func (*Context) MsgPack ¶ added in v12.2.0
MsgPack parses the "v" of msgpack format and renders its result to the client.
func (*Context) Negotiate ¶
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, Protobuf, MsgPack) 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
func (*Context) Negotiation ¶
func (ctx *Context) Negotiation() *NegotiationBuilder
Negotiation creates once and returns the negotiation builder to build server-side available prioritized content for specific content type(s), charset(s) and encoding algorithm(s).
See `Negotiate` method too.
func (*Context) Next ¶
func (ctx *Context) Next()
Next calls the next handler from the handlers chain, it should be used inside a middleware.
func (*Context) NextHandler ¶
NextHandler returns (it doesn't execute) the next handler from the handlers chain.
Use .Skip() to skip this handler if needed to execute the next of this returning handler.
func (*Context) NextOr ¶
NextOr checks if chain has a next handler, if so then it executes it otherwise it sets a new chain assigned to this Context based on the given handler(s) and executes its first handler.
Returns true if next handler exists and executed, otherwise false.
Note that if no next handler found and handlers are missing then it sends a Status Not Found (404) to the client and it stops the execution.
func (*Context) NextOrNotFound ¶
NextOrNotFound checks if chain has a next handler, if so then it executes it otherwise it sends a Status Not Found (404) to the client and stops the execution.
Returns true if next handler exists and executed, otherwise false.
func (*Context) NotFound ¶
func (ctx *Context) NotFound()
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 iris.Context){ if ctx.GetStatusCode() == 400 { /* custom error code for /users */ }})
func (*Context) OnClose ¶
OnClose registers a callback which will be fired when the underlying connection has gone away(request canceled) on its own goroutine or in the end of the request-response lifecylce on the handler's routine itself (Context access).
See `OnConnectionClose` too.
func (*Context) OnCloseErr ¶ added in v12.2.0
OnCloseErr same as `OnClose` but instead it receives a function which returns an error. If error is not nil, it will be logged as a debug message.
func (*Context) OnConnectionClose ¶
OnConnectionClose registers the "cb" Handler which will be fired on its on goroutine on a cloned Context when the underlying connection has gone away.
The code inside the given callback is running on its own routine, as explained above, therefore the callback should NOT try to access to handler's Context response writer.
This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready.
It depends on the Request's Context.Done() channel.
Finally, it reports whether the protocol supports pipelines (HTTP/1.1 with pipelines disabled is not supported). The "cb" will not fire for sure if the output value is false.
Note that you can register only one callback per route.
See `OnClose` too.
func (*Context) OnConnectionCloseErr ¶ added in v12.2.0
OnConnectionCloseErr same as `OnConnectionClose` but instead it receives a function which returns an error. If error is not nil, it will be logged as a debug message.
func (*Context) Params ¶
func (ctx *Context) Params() *RequestParams
Params returns the current url's named parameters key-value storage. Named path parameters are being saved here. This storage, as the whole context, is per-request lifetime.
func (*Context) Path ¶
Path returns the full request path, escaped if EnablePathEscape config field is true.
func (*Context) PostValue ¶
PostValue returns the last parsed form data from POST, PATCH, or PUT body parameters based on a "name".
See `PostValueMany` too.
func (*Context) PostValueBool ¶
PostValueBool returns the last parsed form data from POST, PATCH, or PUT body parameters based on a "name", as bool. If more than one value was binded to "name", then it returns the last one.
See ErrEmptyForm, ErrNotFound and ErrEmptyFormField respectfully.
func (*Context) PostValueDefault ¶
PostValueDefault returns the last parsed form data from POST, PATCH, or PUT body parameters based on a "name".
If not found then "def" is returned instead.
func (*Context) PostValueFloat64 ¶
PostValueFloat64 returns the last parsed form data from POST, PATCH, or PUT body parameters based on a "name", as float64.
See ErrEmptyForm, ErrNotFound and ErrEmptyFormField respectfully.
func (*Context) PostValueFloat64Default ¶
PostValueFloat64Default returns the last 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".
func (*Context) PostValueInt ¶
PostValueInt returns the last parsed form data from POST, PATCH, or PUT body parameters based on a "name", as int.
See ErrEmptyForm, ErrNotFound and ErrEmptyFormField respectfully.
func (*Context) PostValueInt64 ¶
PostValueInt64 returns the last parsed form data from POST, PATCH, or PUT body parameters based on a "name", as float64.
See ErrEmptyForm, ErrNotFound and ErrEmptyFormField respectfully.
func (*Context) PostValueInt64Default ¶
PostValueInt64Default returns the last 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".
func (*Context) PostValueIntDefault ¶
PostValueIntDefault returns the last parsed form data from POST, PATCH, or PUT body parameters based on a "name", as int.
If not found or parse errors returns the "def".
func (*Context) PostValueMany ¶ added in v12.2.0
PostValueMany is like `PostValues` method, it returns the post data of a given key. In addition to `PostValues` though, the returned value is a single string separated by commas on multiple values.
See ErrEmptyForm, ErrNotFound and ErrEmptyFormField respectfully.
func (*Context) PostValueTrim ¶
PostValueTrim returns the last parsed form data from POST, PATCH, or PUT body parameters based on a "name", without trailing spaces.
func (*Context) PostValues ¶
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.
In addition, it reports whether the form was empty or when the "name" does not exist or whether the available values are empty. It strips any empty key-values from the slice before return.
Look ErrEmptyForm, ErrNotFound and ErrEmptyFormField respectfully. See `PostValueMany` method too.
func (*Context) Problem ¶
func (ctx *Context) Problem(v interface{}, opts ...ProblemOptions) (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
func (*Context) Proceed ¶
Proceed is an alternative way to check if a particular handler has been executed. The given "h" Handler can report a failure with `StopXXX` methods or ignore calling a `Next` (see `iris.ExecutionRules` too).
This is useful only when you run a handler inside another handler. It justs checks for before index and the after index.
A usecase example is when you want to execute a middleware inside controller's `BeginRequest` that calls the `ctx.Next` inside it. The Controller looks the whole flow (BeginRequest, method handler, EndRequest) as one handler, so `ctx.Next` will not be reflected to the method handler if called from the `BeginRequest`.
Although `BeginRequest` should NOT be used to call other handlers, the `BeginRequest` has been introduced to be able to set common data to all method handlers before their execution. Controllers can accept middleware(s) from the MVC's Application's Router as normally.
That said let's see an example of `ctx.Proceed`:
var authMiddleware = basicauth.New(basicauth.Config{ Users: map[string]string{ "admin": "password", }, })
func (c *UsersController) BeginRequest(ctx iris.Context) { if !ctx.Proceed(authMiddleware) { ctx.StopExecution() } }
This Get() will be executed in the same handler as `BeginRequest`, internally controller checks for `ctx.StopExecution`. So it will not be fired if BeginRequest called the `StopExecution`.
func(c *UsersController) Get() []models.User { return c.Service.GetAll() }
Alternative way is `!ctx.IsStopped()` if middleware make use of the `ctx.StopExecution()` on failure.
func (*Context) Protobuf ¶ added in v12.2.0
Protobuf parses the "v" of proto Message and renders its result to the client.
func (*Context) ReadBody ¶ added in v12.2.0
ReadBody binds the request body to the "ptr" depending on the HTTP Method and the Request's Content-Type. If a GET method request then it reads from a form (or URL Query), otherwise it tries to match (depending on the request content-type) the data format e.g. JSON, Protobuf, MsgPack, XML, YAML, MultipartForm and binds the result to the "ptr". As a special case if the "ptr" was a pointer to string or []byte then it will bind it to the request body as it is.
func (*Context) ReadForm ¶
ReadForm binds the request body of a form to the "formObject". It supports any kind of type, including custom structs. It will return nothing if request data are empty. The struct field tag is "form". Note that it will return nil error on empty form data if `Configuration.FireEmptyFormError` is false (as defaulted) in this case the caller should check the pointer to see if something was actually binded.
If a client sent an unknown field, this method will return an error, in order to ignore that error use the `err != nil && !iris.IsErrPath(err)`.
Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-form/main.go
func (*Context) ReadHeaders ¶ added in v12.2.0
ReadHeaders binds request headers to "ptr". The struct field tag is "header".
Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-headers/main.go
func (*Context) ReadJSON ¶
func (ctx *Context) ReadJSON(outPtr interface{}, opts ...JSONReader) error
ReadJSON reads JSON from request's body and binds it to a value of any json-valid type.
Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-json/main.go
func (*Context) ReadJSONProtobuf ¶ added in v12.2.0
func (ctx *Context) ReadJSONProtobuf(ptr proto.Message, opts ...ProtoUnmarshalOptions) error
ReadJSONProtobuf reads a JSON body request into the given "ptr" proto.Message. Look `ReadProtobuf` too.
func (*Context) ReadJSONStream ¶ added in v12.2.0
func (ctx *Context) ReadJSONStream(onDecode func(DecodeFunc) error, opts ...JSONReader) error
ReadJSONStream is an alternative of ReadJSON which can reduce the memory load by reading only one json object every time. It buffers just the content required for a single json object instead of the entire string, and discards that once it reaches an end of value that can be decoded into the provided struct inside the onDecode's DecodeFunc.
It accepts a function which accepts the json Decode function and returns an error. The second variadic argument is optional and can be used to customize the decoder even further.
Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-json-stream/main.go
func (*Context) ReadMsgPack ¶ added in v12.2.0
ReadMsgPack binds the request body of msgpack format to the "ptr" and returns any error.
func (*Context) ReadParams ¶ added in v12.2.0
ReadParams binds URI Dynamic Path Parameters to "ptr". The struct field tag is "param".
Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-params/main.go
func (*Context) ReadProtobuf ¶ added in v12.2.0
ReadProtobuf binds the body to the "ptr" of a proto Message and returns any error. Look `ReadJSONProtobuf` too.
func (*Context) ReadQuery ¶
ReadQuery binds URL Query to "ptr". The struct field tag is "url".
Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-query/main.go
func (*Context) ReadURL ¶ added in v12.2.0
ReadURL is a shortcut of ReadParams and ReadQuery. It binds dynamic path parameters and URL query parameters to the "ptr" pointer struct value. The struct fields may contain "url" or "param" binding tags. If a validator exists then it validates the result too.
func (*Context) ReadXML ¶
ReadXML reads XML from request's body and binds it to a value of any xml-valid type.
Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-xml/main.go
func (*Context) ReadYAML ¶
ReadYAML reads YAML from request's body and binds it to the "outPtr" value.
Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-yaml/main.go
func (*Context) Record ¶
func (ctx *Context) Record()
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.
func (*Context) RecordRequestBody ¶ added in v12.2.0
RecordRequestBody same as the Application's DisableBodyConsumptionOnUnmarshal configuration field but acts only for the current request. It makes the request body readable more than once.
func (*Context) Recorder ¶
func (ctx *Context) Recorder() *ResponseRecorder
Recorder returns the context's ResponseRecorder if not recording then it starts recording and returns the new context's ResponseRecorder
func (*Context) Redirect ¶
Redirect sends a redirect response to the client of an absolute or relative target URL. It accepts 2 input arguments, a string and an optional integer. The first parameter is the target url to redirect. The second one is the HTTP status code should be sent among redirection response, If the second parameter is missing, then it defaults to 302 (StatusFound). It can be set to 301 (Permant redirect), StatusTemporaryRedirect(307) or 303 (StatusSeeOther) if POST method.
func (*Context) ReflectValue ¶ added in v12.1.8
ReflectValue caches and returns a []reflect.Value{reflect.ValueOf(ctx)}. It's just a helper to maintain variable inside the context itself.
func (*Context) RegisterDependency ¶ added in v12.2.0
func (ctx *Context) RegisterDependency(v interface{})
RegisterDependency registers a struct or slice or pointer to struct dependency at request-time for the next handler in the chain. One value per type. Note that it's highly recommended to register your dependencies before server ran through Party.ConfigureContainer or mvc.Application.Register in sake of minimum performance cost.
See `UnregisterDependency` too.
func (*Context) RemoteAddr ¶
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, unless the Configuration.RemoteAddrHeadersForce was set to true which will force this method to return the first IP from RemoteAddrHeaders even if it's part of a private network.
Look `Configuration.RemoteAddrHeaders`,
`Configuration.RemoteAddrHeadersForce`, `Configuration.WithRemoteAddrHeader(...)`, `Configuration.WithoutRemoteAddrHeader(...)` and `Configuration.RemoteAddrPrivateSubnets` for more.
func (*Context) RemoveCookie ¶
func (ctx *Context) RemoveCookie(name string, options ...CookieOption)
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
func (*Context) RequestPath ¶
RequestPath returns the full request path, based on the 'escape'.
func (*Context) ResetQuery ¶ added in v12.2.0
func (ctx *Context) ResetQuery()
ResetQuery clears the GET URL Query request, temporary, cache. Any new URLParamXXX calls will receive the new parsed values.
func (*Context) ResetRequest ¶
ResetRequest sets the Context's Request, It is useful to store the new request created by a std *http.Request#WithContext() into Iris' Context. Use `ResetRequest` when for some reason you want to make a full override of the *http.Request. Note that: when you just want to change one of each fields you can use the Request() which returns a pointer to Request, so the changes will have affect without a full override. Usage: you use a native http handler which uses the standard "context" package to get values instead of the Iris' Context#Values(): r := ctx.Request() stdCtx := context.WithValue(r.Context(), key, val) ctx.ResetRequest(r.WithContext(stdCtx)).
func (*Context) ResetResponseWriter ¶
func (ctx *Context) ResetResponseWriter(newResponseWriter ResponseWriter)
ResetResponseWriter sets a new ResponseWriter implementation to this Context to use as its writer. Note, to change the underline http.ResponseWriter use ctx.ResponseWriter().SetWriter(http.ResponseWriter) instead.
func (*Context) ResponseWriter ¶
func (ctx *Context) ResponseWriter() ResponseWriter
ResponseWriter returns an http.ResponseWriter compatible response writer, as expected.
func (*Context) ResumeExecution ¶ added in v12.2.0
ResumeExecution sets the current handler index to the last index of the executed handler before StopExecution method was fired.
Reports whether it's restored after a StopExecution call.
func (*Context) RouteExists ¶
RouteExists reports whether a particular route exists It will search from the current subdomain of context's host, if not inside the root domain.
func (*Context) RouteName ¶
RouteName returns the route name that this handler is running on. Note that it may return empty on not found handlers.
func (*Context) SaveFormFile ¶ added in v12.2.0
SaveFormFile saves a result of `FormFile` to the "dest" disk full path (directory + filename). See `FormFile` and `UploadFormFiles` too.
func (*Context) Scheme ¶ added in v12.2.0
Scheme returns the full scheme of the request (including :// suffix).
func (*Context) SendFile ¶
SendFile sends a file as an attachment, that is downloaded and saved locally from client. Note that compression can be registered through `ctx.CompressWriter(true)` or `app.Use(iris.Compression)`. Use `ServeFile` if a file should be served as a page asset instead.
func (*Context) SendFileWithRate ¶ added in v12.2.0
SendFileWithRate same as `SendFile` but it can throttle the speed of reading and though writing the file to the client.
func (*Context) ServeContent ¶
ServeContent replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests.
If the response's Content-Type header is not set, ServeContent first tries to deduce the type from name's file extension.
The name is otherwise unused; in particular it can be empty and is never sent in the response.
If modtime is not the zero time or Unix epoch, ServeContent includes it in a Last-Modified header in the response. If the request includes an If-Modified-Since header, ServeContent uses modtime to decide whether the content needs to be sent at all.
The content's Seek method must work: ServeContent uses a seek to the end of the content to determine its size.
If the caller has set w's ETag header formatted per RFC 7232, section 2.3, ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.
Note that *os.File implements the io.ReadSeeker interface. Note that compression can be registered through `ctx.CompressWriter(true)` or `app.Use(iris.Compression)`.
func (*Context) ServeContentWithRate ¶ added in v12.2.0
func (ctx *Context) ServeContentWithRate(content io.ReadSeeker, filename string, modtime time.Time, limit float64, burst int)
ServeContentWithRate same as `ServeContent` but it can throttle the speed of reading and though writing the "content" to the client.
func (*Context) ServeFile ¶
ServeFile replies to the request with the contents of the named file or directory.
If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories. If the provided name is constructed from user input, it should be sanitized before calling `ServeFile`.
Use it when you want to serve assets like css and javascript files. If client should confirm and save the file use the `SendFile` instead. Note that compression can be registered through `ctx.CompressWriter(true)` or `app.Use(iris.Compression)`.
func (*Context) ServeFileWithRate ¶ added in v12.2.0
ServeFileWithRate same as `ServeFile` but it can throttle the speed of reading and though writing the file to the client.
func (*Context) SetCookie ¶
func (ctx *Context) SetCookie(cookie *http.Cookie, options ...CookieOption)
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
func (*Context) SetCookieKV ¶
func (ctx *Context) SetCookieKV(name, value string, options ...CookieOption)
SetCookieKV adds a cookie, requires the name(string) and the value(string).
By default it expires after 365 days and it is added to the root URL path, use the `CookieExpires` and `CookiePath` to modify them. Alternatively: ctx.SetCookie(&http.Cookie{...}) or ctx.AddCookieOptions(...)
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: (note that client should be responsible for that if server sent an empty cookie's path, all browsers are compatible) ctx.SetCookieKV(name, value, iris.CookieCleanPath/iris.CookiePath("")) More:
iris.CookieExpires(time.Duration) iris.CookieHTTPOnly(false)
Examples: https://github.com/kataras/iris/tree/master/_examples/cookies/basic
func (*Context) SetCurrentRoute ¶ added in v12.2.0
func (ctx *Context) SetCurrentRoute(route RouteReadOnly)
SetCurrentRoute sets the route internally, See `GetCurrentRoute()` method too. It's being initialized by the Router. See `Exec` or `SetHandlers/AddHandler` methods to simulate a request.
func (*Context) SetErr ¶ added in v12.2.0
SetErr is just a helper that sets an error value as a context value, it does nothing more. Also, by-default this error's value is written to the client on failures when no registered error handler is available (see `Party.On(Any)ErrorCode`). See `GetErr` to retrieve it back.
To remove an error simply pass nil.
Note that, if you want to stop the chain with an error see the `StopWithError/StopWithPlainError` instead.
func (*Context) SetErrPrivate ¶ added in v12.2.0
SetErrPrivate sets an error that it's only accessible through `GetErr` and it should never be sent to the client.
Same as ctx.SetErr with an error that completes the `ErrPrivate` interface. See `GetErrPublic` too.
func (*Context) SetFunc ¶ added in v12.2.0
SetFunc registers a custom function to this Request. It's a helper to pass dynamic functions across handlers of the same chain. For a more complete solution please use Dependency Injection instead. This is just an easy to way to pass a function to the next handler like ctx.Values().Set/Get does. Sometimes is faster and easier to pass the object as a request value and cast it when you want to use one of its methods instead of using these `SetFunc` and `CallFunc` methods. This implementation is suitable for functions that may change inside the handler chain and the object holding the method is not predictable.
The "name" argument is the custom name of the function, you will use its name to call it later on, e.g. "auth.myfunc".
The second, "fn" argument is the raw function/method you want to pass through the next handler(s) of the chain.
The last variadic input argument is optionally, if set then its arguments are passing into the function's input arguments, they should be always be the first ones to be accepted by the "fn" inputs, e.g. an object, a receiver or a static service.
See its `CallFunc` to call the "fn" on the next handler.
Example at: https://github.com/kataras/iris/tree/master/_examples/routing/writing-a-middleware/share-funcs
func (*Context) SetHandlers ¶
SetHandlers replaces all handlers with the new.
func (*Context) SetID ¶ added in v12.2.0
func (ctx *Context) SetID(id interface{})
SetID sets an ID, any value, to the Request Context. If possible the "id" should implement a `String() string` method so it can be rendered on `Context.String` method.
See `GetID` and `middleware/requestid` too.
func (*Context) SetLanguage ¶ added in v12.2.0
SetLanguage force-sets the language for i18n, can be used inside a middleare. It has the highest priority over the rest and if it is empty then it is ignored, if it set to a static string of "default" or to the default language's code then the rest of the language extractors will not be called at all and the default language will be set instead.
See `i18n.ExtractFunc` for a more organised way of the same feature.
func (*Context) SetLastModified ¶
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.
func (*Context) SetLogoutFunc ¶ added in v12.2.0
func (ctx *Context) SetLogoutFunc(fn interface{}, persistenceArgs ...interface{})
SetLogoutFunc registers a custom logout function that will be available to use inside the next handler(s). The function may be registered multiple times but the last one is the valid. So a logout function may start with basic authentication and other middleware in the chain may change it to a custom sessions logout one. This method uses the `SetFunc` method under the hoods.
See `Logout` method too.
func (*Context) SetMaxRequestBodySize ¶
SetMaxRequestBodySize sets a limit to the request body size should be called before reading the request body from the client.
func (*Context) SetUser ¶ added in v12.2.0
SetUser sets a value as a User for this request. It's used by auth middlewares as a common method to provide user information to the next handlers in the chain.
The "i" input argument can be:
- A value which completes the User interface
- A map[string]interface{}.
- A value which does not complete the whole User interface
- A value which does not complete the User interface at all (only its `User().GetRaw` method is available).
Look the `User` method to retrieve it.
func (*Context) Skip ¶
func (ctx *Context) Skip()
Skip skips/ignores the next handler from the handlers chain, it should be used inside a middleware.
func (*Context) SkipTransactions ¶
func (ctx *Context) SkipTransactions()
SkipTransactions if called then skip the rest of the transactions or all of them if called before the first transaction
func (*Context) StatusCode ¶
StatusCode sets the status code header to the response. Look .GetStatusCode & .FireStatusCode too.
Remember, the last one before .Write matters except recorder and transactions.
func (*Context) StopExecution ¶
func (ctx *Context) StopExecution()
StopExecution stops the handlers chain of this request. Meaning that any following `Next` calls are ignored, as a result the next handlers in the chain will not be fire.
See ResumeExecution too.
func (*Context) StopWithError ¶ added in v12.2.0
StopWithError stops the handlers chain and writes the "statusCode" among with the error "err". It Calls the `SetErr` method so error handlers can access the given error.
If the status code is a failure one then it will also fire the specified error code handler.
If the given "err" is private then the status code's text is rendered instead (unless a registered error handler overrides it).
func (*Context) StopWithJSON ¶ added in v12.2.0
StopWithJSON stops the handlers chain, writes the status code and sends a JSON response.
If the status code is a failure one then it will also fire the specified error code handler.
func (*Context) StopWithPlainError ¶ added in v12.2.0
StopWithPlainError like `StopWithError` but it does NOT write anything to the response writer, it stores the error so any error handler matching the given "statusCode" can handle it by its own.
func (*Context) StopWithProblem ¶ added in v12.2.0
StopWithProblem stops the handlers chain, writes the status code and sends an application/problem+json response. See `iris.NewProblem` to build a "problem" value correctly.
If the status code is a failure one then it will also fire the specified error code handler.
func (*Context) StopWithStatus ¶ added in v12.2.0
StopWithStatus stops the handlers chain and writes the "statusCode".
If the status code is a failure one then it will also fire the specified error code handler.
func (*Context) StopWithText ¶ added in v12.2.0
StopWithText stops the handlers chain and writes the "statusCode" among with a fmt-style text of "format" and optional arguments.
If the status code is a failure one then it will also fire the specified error code handler.
func (*Context) StreamWriter ¶
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`).
func (*Context) String ¶
String returns the string representation of this request.
It returns the Context's ID given by a `SetID`call, followed by the client's IP and the method:uri.
func (*Context) Subdomain ¶
Subdomain returns the first subdomain of this request, e.g. [user.]mydomain.com. See `SubdomainFull` too.
func (*Context) SubdomainFull ¶ added in v12.2.0
SubdomainFull returns the full subdomain level, e.g. [test.user.]mydomain.com. Note that HostProxyHeaders are being respected here.
func (*Context) TextYAML ¶ added in v12.2.0
TextYAML marshals the "v" using the yaml marshaler and renders to the client.
func (*Context) Tr ¶ added in v12.1.0
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
func (*Context) TransactionsSkipped ¶
TransactionsSkipped returns true if the transactions skipped or canceled at all.
func (*Context) URLParamBool ¶
URLParamBool returns the url query parameter as boolean value from a request, returns an error if parse failed.
func (*Context) URLParamDefault ¶
URLParamDefault returns the get parameter from a request, if not found then "def" is returned.
func (*Context) URLParamEscape ¶
URLParamEscape returns the escaped url query parameter from a request.
func (*Context) URLParamExists ¶
URLParamExists returns true if the url parameter exists, otherwise false.
func (*Context) URLParamFloat64 ¶
URLParamFloat64 returns the url query parameter as float64 value from a request, returns an error and -1 if parse failed.
func (*Context) URLParamFloat64Default ¶
URLParamFloat64Default returns the url query parameter as float64 value from a request, if not found or parse failed then "def" is returned.
func (*Context) URLParamInt ¶
URLParamInt returns the url query parameter as int value from a request, returns -1 and an error if parse failed or not found.
func (*Context) URLParamInt32Default ¶
URLParamInt32Default returns the url query parameter as int32 value from a request, if not found or parse failed then "def" is returned.
func (*Context) URLParamInt64 ¶
URLParamInt64 returns the url query parameter as int64 value from a request, returns -1 and an error if parse failed or not found.
func (*Context) URLParamInt64Default ¶
URLParamInt64Default returns the url query parameter as int64 value from a request, if not found or parse failed then "def" is returned.
func (*Context) URLParamIntDefault ¶
URLParamIntDefault returns the url query parameter as int value from a request, if not found or parse failed then "def" is returned.
func (*Context) URLParamSlice ¶ added in v12.2.0
URLParamSlice a shortcut of ctx.Request().URL.Query()[name]. Like `URLParam` but it returns all values instead of a single string separated by commas. Returns the values of a url query of the given "name" as string slice, e.g. ?name=john&name=doe&name=kataras will return [ john doe kataras].
See `URLParamsSorted` for sorted values.
func (*Context) URLParamTrim ¶
URLParamTrim returns the url query parameter with trailing white spaces removed from a request.
func (*Context) URLParamUint64 ¶ added in v12.2.0
URLParamUint64 returns the url query parameter as uint64 value from a request. Returns 0 on parse errors or when the URL parameter does not exist in the Query.
func (*Context) URLParams ¶
URLParams returns a map of URL Query parameters. If the value of a URL parameter is a slice, then it is joined as one separated by comma. It returns an empty map on empty URL query.
See URLParamsSorted too.
func (*Context) URLParamsSorted ¶ added in v12.2.0
func (ctx *Context) URLParamsSorted() []memstore.StringEntry
URLParamsSorted returns a sorted (by key) slice of key-value entries of the URL Query parameters.
func (*Context) UnmarshalBody ¶
func (ctx *Context) UnmarshalBody(outPtr interface{}, unmarshaler Unmarshaler) 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.
func (*Context) UnregisterDependency ¶ added in v12.2.0
UnregisterDependency removes a dependency based on its type. Reports whether a dependency with that type was found and removed successfully.
func (*Context) UploadFormFiles ¶
func (ctx *Context) UploadFormFiles(destDirectory string, before ...func(*Context, *multipart.FileHeader) bool) (uploaded []*multipart.FileHeader, n int64, err 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 or cancel 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 or use the `SaveFormFile` method, the below is for generic usage.
The default form's memory maximum size is 32MB, it can be changed by the `WithPostMaxMemory` configurator or by `SetMaxRequestBodySize` or by the `LimitRequestBodySize` middleware (depends the use case).
See `FormFile` and `FormFiles` to a more controlled way to receive a file.
Example: https://github.com/kataras/iris/tree/master/_examples/file-server/upload-files
func (*Context) UpsertCookie ¶ added in v12.2.0
func (ctx *Context) UpsertCookie(cookie *http.Cookie, options ...CookieOption) bool
UpsertCookie adds a cookie to the response like `SetCookie` does but it will also perform a replacement of the cookie if already set by a previous `SetCookie` call. It reports whether the cookie is new (true) or an existing one was updated (false).
func (*Context) User ¶ added in v12.2.0
User returns the registered User of this request. To get the original value (even if a value set by SetUser does not implement the User interface) use its GetRaw method. / See `SetUser` too.
func (*Context) Values ¶
Values returns the current "user" storage. Named path parameters and any optional data can be saved here. This storage, as the whole context, is per-request lifetime.
You can use this function to Set and Get local values that can be used to share information between handlers and middleware.
func (*Context) View ¶
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". If "optionalViewModel" exists, even if it's nil, overrides any previous `ViewData` calls. If second argument is missing then binds the data through previous `ViewData` calls (e.g. middleware).
Look .ViewData and .ViewLayout too.
Examples: https://github.com/kataras/iris/tree/master/_examples/view
func (*Context) ViewData ¶
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 iris.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/
func (*Context) ViewEngine ¶ added in v12.2.0
func (ctx *Context) ViewEngine(engine ViewEngine)
ViewEngine registers a view engine for the current chain of handlers. It overrides any previously registered engines, including the application's root ones. Note that, because performance is everything, the "engine" MUST be already ready-to-use, meaning that its `Load` method should be called once before this method call.
To register a view engine per-group of groups too see `Party.RegisterView` instead.
func (*Context) ViewLayout ¶
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 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/
func (*Context) VisitAllCookies ¶
VisitAllCookies takes a visitor function which is called on each (request's) cookies' name and value.
func (*Context) Write ¶
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.
func (*Context) WriteNotModified ¶
func (ctx *Context) WriteNotModified()
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.
func (*Context) WriteString ¶
WriteString writes a simple string to the response.
Returns the number of bytes written and any write error encountered.
func (*Context) WriteWithExpiration ¶
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.
func (*Context) Writef ¶
Writef formats according to a format specifier and writes to the response.
Returns the number of bytes written and any write error encountered.
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 to-be-sent cookie.
The "op" is the operation code, 0 is GET, 1 is SET and 2 is REMOVE.
func CookieAllowReclaim ¶ added in v12.2.0
func CookieAllowReclaim(cookieNames ...string) CookieOption
CookieAllowReclaim accepts the Context itself. If set it will add the cookie to (on `CookieSet`, `CookieSetKV`, `CookieUpsert`) or remove the cookie from (on `CookieRemove`) the Request object too.
func CookieAllowSubdomains ¶ added in v12.2.0
func CookieAllowSubdomains(cookieNames ...string) CookieOption
CookieAllowSubdomains set to the Cookie Options in order to allow subdomains to have access to the cookies. It sets the cookie's Domain field (if was empty) and it also sets the cookie's SameSite to lax mode too.
func CookieEncoding ¶ added in v12.2.0
func CookieEncoding(encoding SecureCookie, cookieNames ...string) CookieOption
CookieEncoding accepts a value which implements `Encode` and `Decode` methods. It calls its `Encode` on `Context.SetCookie, UpsertCookie, and SetCookieKV` methods. And on `Context.GetCookie` method it calls its `Decode`. If "cookieNames" slice is not empty then only cookies with that `Name` will be encoded on set and decoded on get, that way you can encrypt specific cookie names (like the session id) and let the rest of the cookies "insecure".
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`. See `CookieSecure` too.
func CookiePath ¶
func CookiePath(path string) CookieOption
CookiePath is a `CookieOption`. Use it to change the cookie's Path field.
func CookieSameSite ¶ added in v12.2.0
func CookieSameSite(sameSite http.SameSite) CookieOption
CookieSameSite sets a same-site rule for cookies to set. SameSite allows a server to define a cookie attribute making it impossible for the browser to send this cookie along with cross-site requests. The main goal is to mitigate the risk of cross-origin information leakage, and provide some protection against cross-site request forgery attacks.
See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.
type DecodeFunc ¶ added in v12.2.0
type DecodeFunc func(outPtr interface{}) error
DecodeFunc is a generic type of decoder function. When the returned error is not nil the decode operation is terminated and the error is received by the ReadJSONStream method, otherwise it continues to read the next available object. Look the `Context.ReadJSONStream` method.
type DependenciesMap ¶ added in v12.2.0
DependenciesMap is the type which context serve-time struct dependencies are stored with.
type ErrPanicRecovery ¶ added in v12.2.0
type ErrPanicRecovery struct { ErrPrivate Cause interface{} Callers []string // file:line callers. Stack []byte // the full debug stack. RegisteredHandlers []string // file:line of all registered handlers. CurrentHandler string // the handler panic came from. }
ErrPanicRecovery may be returned from `Context` actions of a `Handler` which recovers from a manual panic.
func IsErrPanicRecovery ¶ added in v12.2.0
func IsErrPanicRecovery(err error) (*ErrPanicRecovery, bool)
IsErrPanicRecovery reports whether the given "err" is a type of ErrPanicRecovery.
func (*ErrPanicRecovery) Error ¶ added in v12.2.0
func (e *ErrPanicRecovery) Error() string
Error implements the Go standard error type.
func (*ErrPanicRecovery) Is ¶ added in v12.2.0
func (e *ErrPanicRecovery) Is(err error) bool
Is completes the internal errors.Is interface.
type ErrPrivate ¶ added in v12.2.0
type ErrPrivate interface { error IrisPrivateError() }
ErrPrivate if provided then the error saved in context should NOT be visible to the client no matter what.
func PrivateError ¶ added in v12.2.0
func PrivateError(err error) ErrPrivate
PrivateError accepts an error and returns a wrapped private one.
type ErrViewNotExist ¶ added in v12.2.0
ErrViewNotExist it's an error. It reports whether a template was not found in the parsed templates tree.
func (ErrViewNotExist) Error ¶ added in v12.2.0
func (e ErrViewNotExist) Error() string
Error completes the `error` interface.
type FallbackView ¶ added in v12.2.0
type FallbackView string
FallbackView is a helper to register a single template filename as a fallback when the provided tempate filename was not found.
func (FallbackView) FallbackView ¶ added in v12.2.0
func (f FallbackView) FallbackView(ctx *Context, err ErrViewNotExist) error
FallbackView completes the FallbackViewProvider interface.
type FallbackViewFunc ¶ added in v12.2.0
type FallbackViewFunc func(ctx *Context, err ErrViewNotExist) error
FallbackViewFunc is a function that can be registered to handle view fallbacks. It accepts the Context and a special error which contains information about the previous template error. It implements the FallbackViewProvider interface.
See `Context.View` method.
func (FallbackViewFunc) FallbackView ¶ added in v12.2.0
func (fn FallbackViewFunc) FallbackView(ctx *Context, err ErrViewNotExist) error
FallbackView completes the FallbackViewProvider interface.
type FallbackViewLayout ¶ added in v12.2.0
type FallbackViewLayout string
FallbackViewLayout is a helper to register a single template filename as a fallback layout when the provided layout filename was not found.
func (FallbackViewLayout) FallbackView ¶ added in v12.2.0
func (f FallbackViewLayout) FallbackView(ctx *Context, err ErrViewNotExist) error
FallbackView completes the FallbackViewProvider interface.
type FallbackViewProvider ¶ added in v12.2.0
type FallbackViewProvider interface { FallbackView(ctx *Context, err ErrViewNotExist) error } /* Notes(@kataras): If ever requested, this fallback logic (of ctx, error) can go to all necessary methods. I've designed with a bit more complexity here instead of a simple filename fallback in order to give the freedom to the developer to do whatever he/she wants with that template/layout not exists error, e.g. have a list of fallbacks views to loop through until succeed or fire a different error than the default. We also provide some helpers for common fallback actions (FallbackView, FallbackViewLayout). This naming was chosen in order to be easy to follow up with the previous view-relative context features. Also note that here we catch a specific error, we want the developer to be aware of the rest template errors (e.g. when a template having parsing issues). */
FallbackViewProvider is an interface which can be registered to the `Party.FallbackView` or `Context.FallbackView` methods to handle fallback views. See FallbackView, FallbackViewLayout and FallbackViewFunc.
type Filter ¶
Filter is just a type of func(Context) bool which reports whether an action must be performed based on the incoming request.
See `NewConditionalHandler` for more.
type Func ¶ added in v12.2.0
type Func struct { RegisterName string // the name of which this function is registered, for information only. Raw interface{} // the Raw function, can be used for custom casting. PersistenceArgs []interface{} // the persistence input arguments given on registration. // Available after the first call. Meta *FuncMeta // contains filtered or unexported fields }
Func represents a function registered by the Context. See its `buildMeta` and `call` internal methods.
type FuncMeta ¶ added in v12.2.0
type FuncMeta struct { Handler Handler // when it's just a handler. HandlerWithErr func(*Context) error // when it's just a handler which returns an error. RawFunc func() // when it's just a func. RawFuncWithErr func() error // when it's just a func which returns an error. RawFuncArgs func(...interface{}) RawFuncArgsWithErr func(...interface{}) error Value reflect.Value Type reflect.Type ExpectedArgumentsLength int PersistenceInputs []reflect.Value AcceptsContext bool // the Context, if exists should be always first argument. ReturnsError bool // when the function's last output argument is error. }
FuncMeta holds the necessary information about a registered context function. Built once by the Func.
type GlobalCounter ¶ added in v12.2.0
type GlobalCounter struct { Max uint64 // contains filtered or unexported fields }
GlobalCounter is a counter which atomically increments until Max.
func NewGlobalCounter ¶ added in v12.2.0
func NewGlobalCounter() *GlobalCounter
NewGlobalCounter returns a fresh instance of a global counter. End developers can use it as a helper for their applications.
func (*GlobalCounter) Get ¶ added in v12.2.0
func (c *GlobalCounter) Get() uint64
Get returns the current counter without incrementing.
func (*GlobalCounter) Increment ¶ added in v12.2.0
func (c *GlobalCounter) Increment() (newValue uint64)
Increment increments the Value. The value cannot exceed the Max one. It uses Compare and Swap with the atomic package.
Returns the new number value.
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.
func JoinHandlers ¶ added in v12.2.0
JoinHandlers returns a copy of "h1" and "h2" Handlers slice joined as one slice of Handlers.
func UpsertHandlers ¶ added in v12.2.0
UpsertHandlers like `JoinHandlers` but it does NOT copies the handlers entries and it does remove duplicates.
type I18nReadOnly ¶ added in v12.1.0
type I18nReadOnly interface { Tags() []language.Tag GetLocale(ctx *Context) Locale Tr(lang string, key string, args ...interface{}) string TrContext(ctx *Context, key 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 ASCII bool // if true writes with unicode to ASCII content. Secure bool // if true then it prepends a "while(1);" when Go slice (to JSON Array) value. // proto.Message specific marshal options. Proto ProtoMarshalOptions }
JSON contains the options for the JSON (Context's) Renderer.
type JSONDecoder ¶
type JSONDecoder interface { }
type JSONEncoder ¶
type JSONReader ¶ added in v12.2.0
type JSONReader struct { // DisallowUnknownFields causes the json decoder to return an error when the destination // is a struct and the input contains object keys which do not match any // non-ignored, exported fields in the destination. DisallowUnknownFields bool // If set to true then a bit faster json decoder is used instead, // note that if this is true then it overrides // the Application's EnableOptimizations configuration field. Optimize bool // This field only applies to the ReadJSONStream. // The Optimize field has no effect when this is true. // If set to true the request body stream MUST start with a `[` // and end with `]` literals, example: // [ // {"username":"john"}, // {"username": "makis"}, // {"username": "george"} // ] // Defaults to false: decodes a json object one by one, example: // {"username":"john"} // {"username": "makis"} // {"username": "george"} ArrayStream bool }
JSONReader holds the JSON decode options of the `Context.ReadJSON, ReadBody` methods.
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 on the given "key". GetMessage(key string, args ...interface{}) string }
Locale is the interface which returns from a `Localizer.GetLocale` method. It serves the translations 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{}
Protobuf interface{}
MsgPack 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 NameExpr ¶ added in v12.2.0
type NameExpr struct {
// contains filtered or unexported fields
}
NameExpr regex or literal comparison through `MatchString`.
func (*NameExpr) MatchString ¶ added in v12.2.0
MatchString reports whether "s" is literal of "literal" or it matches the regex expression at "regex".
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 "text/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) MsgPack ¶ added in v12.2.0
func (n *NegotiationAcceptBuilder) MsgPack() *NegotiationAcceptBuilder
MsgPack adds the "application/msgpack" and "application/x-msgpack" as accepted client content types. 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) Protobuf ¶ added in v12.2.0
func (n *NegotiationAcceptBuilder) Protobuf() *NegotiationAcceptBuilder
Protobuf adds the "application/x-protobuf" as accepted client content type. Returns itself.
func (*NegotiationAcceptBuilder) Text ¶
func (n *NegotiationAcceptBuilder) Text() *NegotiationAcceptBuilder
Text adds the "text/plain" as accepted client content type. Returns itself.
func (*NegotiationAcceptBuilder) TextYAML ¶ added in v12.2.0
func (n *NegotiationAcceptBuilder) TextYAML() *NegotiationAcceptBuilder
TextYAML adds the "text/yaml" 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, br, snappy, s2. that a client should match for (through Accept-Encoding header).
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 "text/javascript" content type and, optionally, a value that `Context.Negotiate` will render when a client accepts the "javascript/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) MsgPack ¶ added in v12.2.0
func (n *NegotiationBuilder) MsgPack(v ...interface{}) *NegotiationBuilder
MsgPack registers the "application/x-msgpack" and "application/msgpack" content types and, optionally, a value that `Context.Negotiate` will render when a client accepts one of the "application/x-msgpack" or "application/msgpack" content types.
Returns itself for recursive calls.
func (*NegotiationBuilder) Problem ¶
func (n *NegotiationBuilder) Problem(v ...interface{}) *NegotiationBuilder
Problem registers the "application/problem+json" 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) Protobuf ¶ added in v12.2.0
func (n *NegotiationBuilder) Protobuf(v ...interface{}) *NegotiationBuilder
Protobuf registers the "application/x-protobuf" content type and, optionally, a value that `Context.Negotiate` will render when a client accepts the "application/x-protobuf" 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) TextYAML ¶ added in v12.2.0
func (n *NegotiationBuilder) TextYAML(v ...interface{}) *NegotiationBuilder
TextYAML registers the "text/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.
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.
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 and "title" was not set-ed, 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 ProtoMarshalOptions ¶ added in v12.2.0
type ProtoMarshalOptions = protojson.MarshalOptions
ProtoMarshalOptions is a type alias for protojson.MarshalOptions.
type ProtoUnmarshalOptions ¶ added in v12.2.0
type ProtoUnmarshalOptions = protojson.UnmarshalOptions
ProtoUnmarshalOptions is a type alias for protojson.UnmarshalOptions.
type Referrer ¶
type Referrer struct { // The raw refer(r)er URL. Raw string `json:"raw" form:"raw" xml:"Raw" yaml:"Raw" toml:"Raw"` 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 parameter value. See `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 RequestParamsReadOnly ¶
type RequestParamsReadOnly interface { Get(key string) string GetEntryAt(index int) memstore.Entry Visit(visitor func(key string, value string)) GetTrim(key string) string GetEscape(key string) string GetDecoded(key string) string } // Note: currently unused.
RequestParamsReadOnly is the read-only access type of RequestParams.
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) CopyTo ¶ added in v12.2.0
func (w *ResponseRecorder) CopyTo(res ResponseWriter)
CopyTo writes a response writer (temp: status code, headers and body) to another response writer
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) Header ¶ added in v12.2.0
func (w *ResponseRecorder) Header() http.Header
Header returns the temporary header map that, on flush response, will be sent by the underline's ResponseWriter's WriteHeader method.
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) (err 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() bool
Reset clears headers, sets the status code to 200 and clears the cached body.
Implements the `ResponseWriterReseter`.
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) Result ¶ added in v12.2.0
func (w *ResponseRecorder) Result() *http.Response
Result returns the response generated by the handler. It does set all provided headers.
Result must only be called after the handler has finished running.
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.
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter // Naive returns the simple, underline and original http.ResponseWriter // that backends this response writer. Naive() http.ResponseWriter // SetWriter sets the underline http.ResponseWriter // that this responseWriter should write on. SetWriter(underline 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 // 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 // CopyTo writes a response writer (temp: status code, headers and body) to another response writer CopyTo(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) // Flush sends any buffered data to the client. Flush() // required by compress writer. }
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 & CompressResponseWriter) 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 ResponseWriterBodyReseter ¶ added in v12.2.0
type ResponseWriterBodyReseter interface {
// ResetBody should reset the body and reports back if it could reset successfully.
ResetBody()
}
ResponseWriterBodyReseter can be implemented by response writers that supports response body overriding (e.g. recorder and compressed).
type ResponseWriterDisabler ¶ added in v12.2.0
type ResponseWriterDisabler interface {
// Disable should disable this type of response writer and fallback to the default one.
Disable()
}
ResponseWriterDisabler can be implemented by response writers that can be disabled and restored to their previous state (e.g. compressed).
type ResponseWriterReseter ¶ added in v12.2.0
type ResponseWriterReseter interface { // Reset should reset the whole response and reports // whether it could reset successfully. Reset() bool }
ResponseWriterReseter can be implemented by response writers that can clear the whole response so a new handler can write into this from the beginning. E.g. recorder, compressed (full) and common writer (status code and headers).
type ResponseWriterWriteTo ¶ added in v12.2.0
ResponseWriterWriteTo can be implemented by response writers that needs a special encoding before writing to their buffers. E.g. a custom recorder that wraps a custom compressed one.
Not used by the framework itself.
type RouteReadOnly ¶
type RouteReadOnly interface { // Name returns the route's name. Name() string // StatusErrorCode returns 0 for common resource routes // or the error code that an http error handler registered on. StatusErrorCode() int // 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 // Trace should writes debug route info to the "w". // Should be called after Build. Trace(w io.Writer, stoppedIndex int) // 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 // MainHandlerIndex returns the first registered handler's index for the route. MainHandlerIndex() int // Property returns a specific property based on its "key" // of this route's Party owner. Property(key string) (interface{}, bool) // 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 SecureCookie ¶ added in v12.2.0
type SecureCookie interface { // Encode 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 `Decode` too. Encode(cookieName string, cookieValue interface{}) (string, error) // Decode 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 `Encode` too. Decode(cookieName string, cookieValue string, cookieValuePtr interface{}) error }
SecureCookie should encodes and decodes authenticated and optionally encrypted cookie values. See `CookieEncoding` package-level function.
type SimpleUser ¶ added in v12.2.0
type SimpleUser struct { Authorization string `json:"authorization,omitempty" db:"authorization"` AuthorizedAt time.Time `json:"authorized_at,omitempty" db:"authorized_at"` ID string `json:"id,omitempty" db:"id"` Username string `json:"username,omitempty" db:"username"` Password string `json:"password,omitempty" db:"password"` Email string `json:"email,omitempty" db:"email"` Roles []string `json:"roles,omitempty" db:"roles"` Token json.RawMessage `json:"token,omitempty" db:"token"` Fields Map `json:"fields,omitempty" db:"fields"` }
SimpleUser is a simple implementation of the User interface.
func (*SimpleUser) GetAuthorization ¶ added in v12.2.0
func (u *SimpleUser) GetAuthorization() (string, error)
GetAuthorization returns the authorization method, e.g. Basic Authentication.
func (*SimpleUser) GetAuthorizedAt ¶ added in v12.2.0
func (u *SimpleUser) GetAuthorizedAt() (time.Time, error)
GetAuthorizedAt returns the exact time the client has been authorized for the "first" time.
func (*SimpleUser) GetEmail ¶ added in v12.2.0
func (u *SimpleUser) GetEmail() (string, error)
GetEmail returns the e-mail of (string,error) User.
func (*SimpleUser) GetField ¶ added in v12.2.0
func (u *SimpleUser) GetField(key string) (interface{}, error)
GetField optionally returns a dynamic field from the `Fields` field based on its key.
func (*SimpleUser) GetID ¶ added in v12.2.0
func (u *SimpleUser) GetID() (string, error)
GetID returns the ID of the User.
func (*SimpleUser) GetPassword ¶ added in v12.2.0
func (u *SimpleUser) GetPassword() (string, error)
GetPassword returns the raw password of the User.
func (*SimpleUser) GetRaw ¶ added in v12.2.0
func (u *SimpleUser) GetRaw() (interface{}, error)
GetRaw returns itself.
func (*SimpleUser) GetRoles ¶ added in v12.2.0
func (u *SimpleUser) GetRoles() ([]string, error)
GetRoles returns the specific user's roles. Returns with `ErrNotSupported` if the Roles field is not initialized.
func (*SimpleUser) GetToken ¶ added in v12.2.0
func (u *SimpleUser) GetToken() ([]byte, error)
GetToken returns the token associated with this User. It may return empty if the User is not featured with a Token.
The implementation can change that behavior. Returns with `ErrNotSupported` if the Token field is empty.
func (*SimpleUser) GetUsername ¶ added in v12.2.0
func (u *SimpleUser) GetUsername() (string, error)
GetUsername returns the name of the User.
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.
type User ¶ added in v12.2.0
type User interface { // GetRaw should return the raw instance of the user, if supported. GetRaw() (interface{}, error) // GetAuthorization should return the authorization method, // e.g. Basic Authentication. GetAuthorization() (string, error) // GetAuthorizedAt should return the exact time the // client has been authorized for the "first" time. GetAuthorizedAt() (time.Time, error) // GetID should return the ID of the User. GetID() (string, error) // GetUsername should return the name of the User. GetUsername() (string, error) // GetPassword should return the encoded or raw password // (depends on the implementation) of the User. GetPassword() (string, error) // GetEmail should return the e-mail of the User. GetEmail() (string, error) // GetRoles should optionally return the specific user's roles. // Returns `ErrNotSupported` if this method is not // implemented by the User implementation. GetRoles() ([]string, error) // GetToken should optionally return a token used // to authorize this User. GetToken() ([]byte, error) // GetField should optionally return a dynamic field // based on its key. Useful for custom user fields. // Keep in mind that these fields are encoded as a separate JSON key. GetField(key string) (interface{}, error) } /* Notes: We could use a structure of User wrapper and separate interfaces for each of the methods so they return ErrNotSupported if the implementation is missing it, so the `Features` field and HasUserFeature can be omitted and add a Raw() interface{} to return the underline User implementation too. The advandages of the above idea is that we don't have to add new methods for each of the builtin features and we can keep the (assumed) struct small. But we dont as it has many disadvantages, unless is requested. ^ UPDATE: this is done through UserPartial. The disadvantage of the current implementation is that the developer MUST complete the whole interface in order to be a valid User and if we add new methods in the future their implementation will break (unless they have a static interface implementation check as we have on SimpleUser). We kind of by-pass this disadvantage by providing a SimpleUser which can be embedded (as pointer) to the end-developer's custom implementations. */
User is a generic view of an authorized client. See `Context.User` and `SetUser` methods for more.
The informational methods starts with a "Get" prefix in order to allow the implementation to contain exported fields such as `Username` so they can be JSON encoded when necessary.
The caller is free to cast this with the implementation directly when special features are offered by the authorization system.
To make optional some of the fields you can just embed the User interface and implement whatever methods you want to support.
There are three builtin implementations of the User interface: - SimpleUser - UserMap (a wrapper by SetUser) - UserPartial (a wrapper by SetUser)
type UserGetPassword ¶ added in v12.2.0
type UserGetPassword interface {
GetPassword() string
}
UserGetPassword interface which requires a single method to complete a User on Context.SetUser.
type UserGetUsername ¶ added in v12.2.0
type UserGetUsername interface {
GetUsername() string
}
UserGetUsername interface which requires a single method to complete a User on Context.SetUser.
type UserMap ¶ added in v12.2.0
type UserMap Map
UserMap can be used to convert a common map[string]interface{} to a User. Usage:
user := map[string]interface{}{ "username": "kataras", "age" : 27, }
ctx.SetUser(user) OR user := UserStruct{....} ctx.SetUser(user) [...] username, err := ctx.User().GetUsername() field,err := ctx.User().GetField("age") age := field.(int) OR cast it: user := ctx.User().(UserMap) username := user["username"].(string) age := user["age"].(int)
func (UserMap) GetAuthorization ¶ added in v12.2.0
GetAuthorization returns the authorization or Authorization value of the map.
func (UserMap) GetAuthorizedAt ¶ added in v12.2.0
GetAuthorizedAt returns the authorized_at or Authorized_At value of the map.
func (UserMap) GetField ¶ added in v12.2.0
GetField returns the raw map's value based on its "key". It's not kind of useful here as you can just use the map.
func (UserMap) GetPassword ¶ added in v12.2.0
GetPassword returns the password or Password value of the map.
func (UserMap) GetUsername ¶ added in v12.2.0
GetUsername returns the username or Username value of the map.
type UserPartial ¶ added in v12.2.0
type UserPartial struct { Raw interface{} `json:"raw"` UserGetUsername `json:",omitempty"` UserGetPassword `json:",omitempty"` // contains filtered or unexported fields }
UserPartial is a User. It's a helper which wraps a struct value that may or may not complete the whole User interface. See Context.SetUser.
func (*UserPartial) GetAuthorization ¶ added in v12.2.0
func (u *UserPartial) GetAuthorization() (string, error)
GetAuthorization should return the authorization method, e.g. Basic Authentication.
func (*UserPartial) GetAuthorizedAt ¶ added in v12.2.0
func (u *UserPartial) GetAuthorizedAt() (time.Time, error)
GetAuthorizedAt should return the exact time the client has been authorized for the "first" time.
func (*UserPartial) GetEmail ¶ added in v12.2.0
func (u *UserPartial) GetEmail() (string, error)
GetEmail should return the e-mail of the User.
func (*UserPartial) GetField ¶ added in v12.2.0
func (u *UserPartial) GetField(key string) (interface{}, error)
GetField should optionally return a dynamic field based on its key. Useful for custom user fields. Keep in mind that these fields are encoded as a separate JSON key.
func (*UserPartial) GetID ¶ added in v12.2.0
func (u *UserPartial) GetID() (string, error)
GetID should return the ID of the User.
func (*UserPartial) GetPassword ¶ added in v12.2.0
func (u *UserPartial) GetPassword() (string, error)
GetPassword should return the encoded or raw password (depends on the implementation) of the User.
func (*UserPartial) GetRaw ¶ added in v12.2.0
func (u *UserPartial) GetRaw() (interface{}, error)
GetRaw returns the original raw instance of the user.
func (*UserPartial) GetRoles ¶ added in v12.2.0
func (u *UserPartial) GetRoles() ([]string, error)
GetRoles should optionally return the specific user's roles. Returns `ErrNotSupported` if this method is not implemented by the User implementation.
func (*UserPartial) GetToken ¶ added in v12.2.0
func (u *UserPartial) GetToken() ([]byte, error)
GetToken should optionally return a token used to authorize this User.
func (*UserPartial) GetUsername ¶ added in v12.2.0
func (u *UserPartial) GetUsername() (string, error)
GetUsername should return the name of the User.
type Validator ¶ added in v12.2.0
type Validator interface {
Struct(interface{}) error
}
Validator is the validator for request body on Context methods such as ReadJSON, ReadMsgPack, ReadXML, ReadYAML, ReadForm, ReadQuery, ReadBody and e.t.c.
type ViewEngine ¶ added in v12.2.0
type ViewEngine interface { // Name returns the name of the engine. Name() string // Load should load the templates from the given FileSystem. Load() error // ExecuteWriter should execute a template by its filename with an optional layout and bindingData. ExecuteWriter(w io.Writer, filename string, layout string, bindingData interface{}) error // Ext should return the final file extension (including the dot) // which this view engine is responsible to render. // If the filename extension on ExecuteWriter is empty then this is appended. Ext() string }
ViewEngine is the interface which all view engines should be implemented in order to be registered inside iris.
type ViewEngineFuncer ¶ added in v12.2.0
type ViewEngineFuncer interface { // AddFunc should adds a function to the template's function map. AddFunc(funcName string, funcBody interface{}) }
ViewEngineFuncer is an addition of a view engine, if a view engine implements that interface then iris can add some closed-relative iris functions like {{ url }}, {{ urlpath }} and {{ tr }}.