Documentation
¶
Overview ¶
This file exists for its name.
It holds Context.Writef, and it is named so that it sorts before every file of this package that declares a generic *Context method: today those are context_bind.go, context_bind_update.go, context_request.go and page.go, and the first of them, context_bind.go, is the one that matters. The Go type checker orders a named type's methods by the file they are declared in, and file names are sorted, so this file's name decides that Writef comes first.
Why that matters: go vet's printf analyzer records "Writef is a printf wrapper" as a fact keyed by objectpath, and objectpath addresses a method by its index in the type's method list. On go1.27.0 a generic method declared before Writef makes that index disagree between the package that writes the fact and the package that reads it back, so the fact lands on some other method. Two things then go wrong at once, both confirmed from a scratch module that imports Iris:
- ctx.Writef("%d", "x") is not reported to any user of the framework, although it is a real bug;
- whichever unrelated *Context method happens to occupy the shifted slot is treated as a printf function, so a plain call like ctx.QueryInt("limit", iris.QueryRequired()) is reported as "call has arguments but no formatting directives".
With Writef declared ahead of every generic method the two indexes agree again and both diagnostics come out right. So: do not move this declaration back into context_response.go, and do not rename this file to anything that sorts after context_bind.go. Either one silently removes format checking of ctx.Writef from every program that imports Iris, and hands an unrelated method a false positive its author cannot explain. A minimal reproduction is three files with no Iris in them: a type with a generic method, a Writef, and a consumer package.
The upstream bug is golang/go#81306 (export data loses method order). Go 1.27.1 still has it; the fix is backported to Go 1.27.2. Once go.mod requires 1.27.2, Writef can move back and this file and its test can go.
This file holds the Context's typed binding methods: the generic-method counterparts of the former rest package's ctx-first generic functions. Their error responses render through the RestErrorRenderer seam (see rest_error_renderer.go): the canonical renderer lives in rest/errors and installs itself at package-init time.
Package context implements the per-request Context of the Iris web framework.
Most code reaches it through the iris.Context alias rather than importing this package directly, but the methods, the options and the request-scoped helpers are all documented here.
Lifecycle and Pooling ¶
A Context is taken from a sync.Pool when the request arrives and returned to it when the handler chain ends. Its fields are cleared on release, so a reference kept past the handler's return points at whatever request came next. Do not store one, do not close over one in a goroutine, and do not use one from two goroutines at once.
When work must outlive the request, take a copy first:
cloned := ctx.Clone()
go func() {
if cloned.IsCanceled() {
return
}
// ...
}()
Context.OnConnectionClose registers a callback for client disconnects and hands it a snapshot taken at registration time, for the same reason.
Reading Requests ¶
Path parameters come from Context.Params, query values from Context.Query, and bodies from the Read family: Context.ReadJSON, ReadForm, ReadQuery, ReadXML, ReadYAML, ReadMsgPack and Context.ReadBody, which picks a decoder from the request's content type.
Three options in ContextOptions shape all of them. PostMaxMemory bounds multipart form parsing and defaults to 32MB. BodyMaxMemory caps the total bytes any body reader will accept and answers ErrRequestEntityTooLarge past the limit; it is unlimited until you set it. RequestValidator runs after every successful decode.
Writing Responses ¶
Context.JSON, JSONP, XML, YAML, Markdown, Protobuf, MsgPack and Context.Negotiate write the response; Context.SetHeader, Context.AddHeader and the cookie helpers shape it. The package-level WriteJSON and its siblings are variables, so an application can replace the encoder without changing a handler.
An error raised while writing goes to ContextOptions.ErrorHandler rather than being returned to the caller, unless DisableErrorHandler is set.
Security Considerations ¶
- SafeFilename is the sanitizer behind Context.UploadFormFiles. It rejects traversal, escapes out of the destination directory through a symlink, and reserved Windows device names such as NUL and COM1, which are refused on every platform so that an upload set does not vary by host. Call it yourself before Context.SaveFormFile, which writes the name you give it verbatim.
- IsValidJSONPCallback gates Context.JSONP. A callback that is not a plain JavaScript identifier reference, or that runs past 128 bytes, fails with ErrInvalidJSONPCallback before anything is written.
- Context.RemoteAddr filters proxy headers against the configured private subnets and trusts none of them until ContextOptions.RemoteAddrHeaders names one. Context.Addr returns the client's own unfiltered claim and must not reach an authorization or rate-limiting decision.
- Context.SetHeader replaces, which is what a single-valued header such as Access-Control-Allow-Origin needs. Context.AddHeader appends, for a list-valued one such as Vary.
- MakeDisposition encodes a Content-Disposition filename so that a non-ASCII name cannot break out of the header.
- A User carries the credentials it authenticated with. Never write one to the response; see Context.User.
Customizing ¶
Context.Options returns this request's ContextOptions for a middleware to adjust; Context.OptionsReadOnly is the read path. To carry your own type through handlers instead of *Context, wrap it with NewContextWrapper or NewContextWrapperWithPool.
Index ¶
- Constants
- Variables
- func ContentTypeNoSniff(ct *ContentType)
- func ContentTypeOnce(ct *ContentType)
- func CookieCleanPath(_ *Context, c *http.Cookie, op uint8)
- func CookieIncluded(cookie *http.Cookie, cookieNames []string) bool
- func CookiePartitioned(_ *Context, c *http.Cookie, op uint8)
- func CookieSecure(ctx *Context, c *http.Cookie, op uint8)
- func CookieSecureForce(ctx *Context, c *http.Cookie, op uint8)
- func CountToInt64[N CountType](n N) int64
- func DecodeQuery(path string) string
- func DecodeURL(uri string) string
- func DefaultLogger(prefix string) (logger *golog.Logger)
- func FlushResponseWriter(w http.ResponseWriter) error
- func FormValueDefault(r *http.Request, name string, def string, postMaxMemory int64) string
- func GetForm(r *http.Request, postMaxMemory int64) (form map[string][]string, found bool)
- func GetHost(r *http.Request) string
- func GetHostname(r *http.Request) string
- func GetScheme(r *http.Request) string
- func HandlerExists(handlers Handlers, nameOrFunc any) bool
- func HandlerFileLine(fn any) (file string, line int)
- func HandlerInfo(h Handler) *funcer.Func[Handler]
- func HandlerName(fn any) string
- func IgnoreHandlerName(name string) bool
- func IsErrCanceled(err error) bool
- func IsNoOpFS(fileSystem fs.FS) bool
- func IsValidJSONPCallback(callback string) bool
- func IsZeroTime(t time.Time) bool
- func ListFileNames(fileSystem http.FileSystem, name string) ([]string, error)
- func MakeDisposition(filename string) string
- func NegotiateAcceptHeader(in []string, offers []string, bestOffer string) string
- func OnApplicationRegistered(listeners ...func(app Application))
- func PrivateErrorf(err error) error
- func RegisterApplication(app Application)
- func ReleaseResponseWriter(w *DefaultResponseWriter)
- func SafeFilename(prefixDir string, name string) (string, string, bool, error)
- func SetCompressHeaders(h http.Header, encoding string)
- func SetHandlerName(original string, replacement string)
- func SetRestErrorRenderer(r RestErrorRenderer)
- func StatusText(code int) string
- func TrimHeaderValue(v string) string
- func TrimParamFilePart(ctx *Context)
- func UnwrapResponseWriter(w http.ResponseWriter) http.ResponseWriter
- func XMLMap(elementName string, v Map) xml.Marshaler
- type Application
- type BodyDecoder
- type BodyDecoderWithContext
- type Component
- type ContentNegotiator
- type ContentSelector
- type ContentType
- type ContentTypeOption
- type Context
- func (ctx *Context) AbsoluteURI(s string) string
- func (ctx *Context) AddCookie(name, value string, options ...CookieOption)
- func (ctx *Context) AddCookieOptions(options ...CookieOption)
- func (ctx *Context) AddHandler(handlers ...Handler)
- func (ctx *Context) AddHeader(name string, value string)
- func (ctx *Context) Addr() string
- func (ctx *Context) Application() Application
- func (ctx *Context) Binary(data []byte) error
- func (ctx *Context) BindJSON[Request any]() (Request, bool)
- func (ctx *Context) BindJSONList[Request any]() ([]Request, bool)
- func (ctx *Context) BindJSONOneOrMany[Request any]() (*Request, []Request, bool)
- func (ctx *Context) BindJSONOptional[Request any]() (Request, bool)
- func (ctx *Context) BindPagination[Filter any](opts ...PaginationOption) (PageOptions, Filter, bool)
- func (ctx *Context) BindParam[T any](name string) (T, bool)
- func (ctx *Context) BindParams[Struct any]() (Struct, bool)
- func (ctx *Context) BindUpdate[T any]() (T, []string, bool)
- func (ctx *Context) Body() ([]byte, error)
- func (ctx *Context) BodyLength() (int64, error)
- func (ctx *Context) Charset() string
- 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) ContentLength() int64
- func (ctx *Context) ContentType() ContentType
- func (ctx *Context) Cookie(name string, options ...CookieOption) (*http.Cookie, error)
- func (ctx *Context) CookieValue(name string, options ...CookieOption) string
- func (ctx *Context) Count[N CountType](rowsAffected N, err error) bool
- func (ctx *Context) Created(resp any, err error) bool
- func (ctx *Context) CurrentRoute() RouteReadOnly
- func (ctx *Context) Deadline() (deadline time.Time, ok bool)
- func (ctx *Context) DisableResponseBuffering() error
- func (ctx *Context) Do(handlers Handlers)
- func (ctx *Context) Domain() string
- func (ctx *Context) Done() <-chan struct{}
- func (ctx *Context) DumpRequest(includeBody bool) ([]byte, error)
- func (ctx *Context) Err() error
- func (ctx *Context) ErrPublic() (bool, error)
- func (ctx *Context) EscapedPath() string
- func (ctx *Context) FindClosest(n int) []string
- func (ctx *Context) Form() encoding.StringSliceEntries
- 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) FullRequestURI() string
- func (ctx *Context) GetErr() error
- func (ctx *Context) GetStatusCode() int
- func (ctx *Context) HTML(body string) error
- func (ctx *Context) HandleError(err error) bool
- 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) string
- func (ctx *Context) Host() string
- func (ctx *Context) Hostname() string
- func (ctx *Context) ID() any
- 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) IsLocal() bool
- func (ctx *Context) IsMediaType(mediaTypes ...string) bool
- func (ctx *Context) IsMobile() 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 any, opts ...JSON) error
- func (ctx *Context) JSONOrError(resp any) bool
- func (ctx *Context) JSONP(v any, opts ...JSONP) (err error)
- func (ctx *Context) LastPathParameter() (lastParameter macro.TemplateParam)
- func (ctx *Context) List(items any, err error, tolerate ...error) bool
- func (ctx *Context) Logout() error
- func (ctx *Context) Markdown(markdownB []byte, opts ...Markdown) (err error)
- func (ctx *Context) MaxAge() int64
- func (ctx *Context) MediaType() string
- func (ctx *Context) Method() string
- func (ctx *Context) MsgPack(v any) error
- func (ctx *Context) Negotiate(v any) error
- func (ctx *Context) Negotiation() *NegotiationBuilder
- func (ctx *Context) Next()
- func (ctx *Context) NextHandler() Handler
- func (ctx *Context) NoContent(modified bool, err error) bool
- func (ctx *Context) NotFound()
- func (ctx *Context) OK(resp any, err error) bool
- func (ctx *Context) OnConnectionClose(cb Handler) bool
- func (ctx *Context) OnRelease(fn func())
- func (ctx *Context) Options() *ContextOptions
- func (ctx *Context) OptionsReadOnly() *ContextOptions
- func (ctx *Context) Paginated[Filter any, Item any, TotalCount CountType](collect ItemsCollectorFunc[Filter, Item, TotalCount], opts ...PaginationOption) bool
- func (ctx *Context) Params() *encoding.PathParams
- func (ctx *Context) Path() string
- func (ctx *Context) PostForm() encoding.StringSliceEntries
- func (ctx *Context) Proceed(handlers ...Handler) bool
- func (ctx *Context) Protobuf(v proto.Message) error
- func (ctx *Context) ProtobufJSON(m proto.Message, opts ...protojson.MarshalOptions) error
- func (ctx *Context) Query() encoding.StringSliceEntries
- func (ctx *Context) QueryBool(key string, opts ...QueryOption) (bool, bool)
- func (ctx *Context) QueryDate(key string, opts ...QueryOption) (types.SimpleDate, bool)
- func (ctx *Context) QueryInt(key string, opts ...QueryOption) (int, bool)
- func (ctx *Context) ReadBody(ptr any) error
- func (ctx *Context) ReadForm(formObject any) error
- func (ctx *Context) ReadHeader(ptr any) error
- func (ctx *Context) ReadJSON(outPtr any, opts ...JSONReader) error
- func (ctx *Context) ReadJSONStream(onDecode func(DecodeFunc) error, opts ...JSONReader) error
- func (ctx *Context) ReadMsgPack(ptr any) error
- func (ctx *Context) ReadMultipartRelated() (MultipartRelated, error)
- func (ctx *Context) ReadParams(ptr any) error
- func (ctx *Context) ReadProtobuf(ptr proto.Message) error
- func (ctx *Context) ReadProtobufJSON(ptr proto.Message, opts ...protojson.UnmarshalOptions) error
- func (ctx *Context) ReadQuery(ptr any) error
- func (ctx *Context) ReadURL(ptr any) error
- func (ctx *Context) ReadValues(ptr any) error
- func (ctx *Context) ReadXML(outPtr any) error
- func (ctx *Context) ReadYAML(outPtr any) error
- func (ctx *Context) Redirect(urlToRedirect string, statusHeader ...int)
- func (ctx *Context) RemoteAddr() string
- func (ctx *Context) RemoveCookie(name string, options ...CookieOption)
- func (ctx *Context) Render(r Renderer) error
- func (ctx *Context) RenderComponent(component Component) error
- func (ctx *Context) RenderResponse(statusCode int, r ResponseRenderer) error
- func (ctx *Context) Request() *http.Request
- func (ctx *Context) RequestValue[Request any]() (Request, bool)
- func (ctx *Context) ResponseContentType() ContentType
- func (ctx *Context) ResponseHeader(name string) string
- func (ctx *Context) ResponseMediaType() string
- func (ctx *Context) ResponseWriter() ResponseWriter
- func (ctx *Context) ResumeExecution() bool
- func (ctx *Context) RunReleaseHooks()
- 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) SetContentType(rawContentType string, opts ...ContentTypeOption) error
- func (ctx *Context) SetCookie(cookie *http.Cookie, options ...CookieOption)
- func (ctx *Context) SetCurrentRoute(route RouteReadOnly)
- func (ctx *Context) SetErr(err error)
- func (ctx *Context) SetErrPrivate(err error)
- func (ctx *Context) SetHandlers(handlers Handlers)
- func (ctx *Context) SetHeader(name string, value string)
- func (ctx *Context) SetID(id any)
- func (ctx *Context) SetLastModified(modtime time.Time)
- func (ctx *Context) SetLogoutFunc(fn LogoutHandler)
- func (ctx *Context) SetRequest(r *http.Request)
- func (ctx *Context) SetResponseWriter(newResponseWriter ResponseWriter)
- func (ctx *Context) SetUser(i any) error
- func (ctx *Context) ShuttingDown() <-chan struct{}
- func (ctx *Context) Skip()
- func (ctx *Context) StatusCode(statusCode int)
- func (ctx *Context) StdContext() context.Context
- func (ctx *Context) StopExecution()
- func (ctx *Context) StopWithError(statusCode int, err error)
- func (ctx *Context) StopWithJSON(statusCode int, jsonObject any) error
- func (ctx *Context) StopWithPlainError(statusCode int, err error)
- func (ctx *Context) StopWithStatus(statusCode int)
- func (ctx *Context) StopWithText(statusCode int, text string)
- 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) Text(text string) error
- func (ctx *Context) TextYAML(v any) error
- func (ctx *Context) UnmarshalBody(outPtr any, unmarshaler Unmarshaler) error
- func (ctx *Context) UploadFormFiles(destDirectory string, before ...func(*Context, *multipart.FileHeader) bool) (uploaded []*multipart.FileHeader, n int64, err error)
- func (ctx *Context) User() User
- func (ctx *Context) Value(key any) any
- func (ctx *Context) ValueAs[T any](key string) (value T, gotValue bool)
- func (ctx *Context) Values() *encoding.ContextValues
- func (ctx *Context) WithoutCancel() context.Context
- 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 ...any) (n int, err error)
- func (ctx *Context) XML(v any, opts ...XML) (err error)
- func (ctx *Context) YAML(v any) error
- type ContextOptions
- func (o *ContextOptions) Clone() *ContextOptions
- func (o *ContextOptions) CopyFrom(from *ContextOptions)
- func (o *ContextOptions) CopyTo(to *ContextOptions)
- func (o *ContextOptions) Equal(other *ContextOptions) bool
- func (o *ContextOptions) FillZero(from ContextOptions)
- func (opts *ContextOptions) Get(objectKey string) any
- func (opts *ContextOptions) HandleError(ctx *Context, err error)
- func (opts *ContextOptions) MimeToContentType(mime string) string
- func (opts *ContextOptions) Set(objectKey string, objectValue any)
- func (opts *ContextOptions) Validate(ptr any) error
- type ContextPool
- type ContextSetter
- type ContextSetterPtr
- type ContextWrapper
- func (w *ContextWrapper[T]) Filter(handler func(T) bool) Filter
- func (w *ContextWrapper[T]) Handler(handler func(T)) Handler
- func (w *ContextWrapper[T]) HandlerReturnDuration(handler func(T) time.Duration) func(*Context) time.Duration
- func (w *ContextWrapper[T]) HandlerReturnError(handler func(T) error) func(*Context) error
- func (w *ContextWrapper[T]) Handlers(handlers ...func(T)) Handlers
- func (w *ContextWrapper[T]) Pool() ContextPool[T]
- type CookieOption
- func CookieAllowReclaim(cookieNames ...string) CookieOption
- func CookieAllowSubdomains(cookieNames ...string) CookieOption
- func CookieDomain(domain string) CookieOption
- func CookieEncoding(encoding SecureCookie, cookieNames ...string) CookieOption
- func CookieExpires(durFromNow time.Duration) CookieOption
- func CookieHTTPOnly(httpOnly bool) CookieOption
- func CookieOverride(cookie *http.Cookie) CookieOption
- func CookiePath(path string) CookieOption
- func CookieSameSite(sameSite http.SameSite) CookieOption
- type CountResponse
- type CountType
- type DecodeFunc
- type DefaultResponseWriter
- func (w *DefaultResponseWriter) Clone() ResponseWriter
- func (w *DefaultResponseWriter) Flush()
- func (w *DefaultResponseWriter) FlushError() error
- func (w *DefaultResponseWriter) Flusher() (http.Flusher, bool)
- func (w *DefaultResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (w *DefaultResponseWriter) IsHijacked() bool
- func (w *DefaultResponseWriter) StatusCode() int
- func (w *DefaultResponseWriter) Unwrap() http.ResponseWriter
- func (w *DefaultResponseWriter) Write(contents []byte) (int, error)
- func (w *DefaultResponseWriter) WriteHeader(statusCode int)
- func (w *DefaultResponseWriter) Written() int
- type ErrPanicRecovery
- type ErrPrivate
- type ErrorHandler
- type Filter
- type Handler
- func FromStd(handler any) Handler
- func FromStdWithNext(h func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) Handler
- func JoinHandlersAsMiddleware(handlers ...Handler) Handler
- func JoinHandlersAsOneHandler(handlers ...Handler) Handler
- func NewConditionalHandler(filter Filter, handlers ...Handler) Handler
- func TryFromStd(handler any) (Handler, error)
- type HandlerList
- type Handlers
- type IDPayload
- type IDType
- type ItemsCollectorFunc
- type JSON
- type JSONP
- type JSONReader
- type ListFilter
- type LogoutHandler
- type Map
- type Markdown
- type MultipartRelated
- type MultipartRelatedContent
- type N
- type NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Binary() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Charset(charset ...string) *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Encoding(encoding ...string) *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) EncodingGzip() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) HTML() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) JSON() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) JSONP() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) MIME(mimeType ...string) *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Markdown() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) MsgPack() *NegotiationAcceptBuilder
- func (n *NegotiationAcceptBuilder) Override() *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 ...any) *NegotiationBuilder
- func (n *NegotiationBuilder) Binary(v ...[]byte) *NegotiationBuilder
- func (n *NegotiationBuilder) Build() (mediaType, charset, encoding string, content any)
- 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 ...any) *NegotiationBuilder
- func (n *NegotiationBuilder) JSONP(v ...any) *NegotiationBuilder
- func (n *NegotiationBuilder) MIME(mime string, content any) *NegotiationBuilder
- func (n *NegotiationBuilder) Markdown(v ...[]byte) *NegotiationBuilder
- func (n *NegotiationBuilder) MsgPack(v ...any) *NegotiationBuilder
- func (n *NegotiationBuilder) Protobuf(v ...any) *NegotiationBuilder
- func (n *NegotiationBuilder) Text(v ...string) *NegotiationBuilder
- func (n *NegotiationBuilder) TextYAML(v ...any) *NegotiationBuilder
- func (n *NegotiationBuilder) XML(v ...any) *NegotiationBuilder
- func (n *NegotiationBuilder) YAML(v ...any) *NegotiationBuilder
- type Page
- type PageOptions
- type PaginationOption
- type Pool
- type QueryOption
- type Renderer
- type ResponseRenderer
- type ResponseWriter
- type ResponseWriterBodyResetter
- type ResponseWriterDisabler
- type ResponseWriterFlushError
- type ResponseWriterHeaderFlusher
- type ResponseWriterResetter
- type ResponseWriterWriteTo
- type RestErrorRenderer
- type RouteReadOnly
- type Router
- 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) (any, error)
- func (u *SimpleUser) GetID() (string, error)
- func (u *SimpleUser) GetPassword() (string, error)
- func (u *SimpleUser) GetRaw() (any, error)
- func (u *SimpleUser) GetRoles() ([]string, error)
- func (u *SimpleUser) GetToken() ([]byte, error)
- func (u *SimpleUser) GetUsername() (string, error)
- 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) (any, error)
- func (u UserMap) GetID() (string, error)
- func (u UserMap) GetPassword() (string, error)
- func (u UserMap) GetRaw() (any, 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) (any, error)
- func (u *UserPartial) GetID() (string, error)
- func (u *UserPartial) GetPassword() (string, error)
- func (u *UserPartial) GetRaw() (any, error)
- func (u *UserPartial) GetRoles() ([]string, error)
- func (u *UserPartial) GetToken() ([]byte, error)
- func (u *UserPartial) GetUsername() (string, error)
- type Validatable
- type Validator
- type XML
Constants ¶
const ( OpCookieGet uint8 = iota OpCookieSet OpCookieDel )
Set of Cookie actions for `CookieOption`.
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" // ContentMultipartRelatedHeaderValue header value for multipart related data. ContentMultipartRelatedHeaderValue = "multipart/related" // ContentGRPCHeaderValue Content-Type header value for gRPC. ContentGRPCHeaderValue = "application/grpc" )
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 ( // 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 CSRFTokenFormKey = "csrf.token"
CSRFTokenFormKey the CSRF token key of the form data.
See ReadForm method for more.
const (
// DefaultTimeFormat is the default time format.
DefaultTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
)
const MaxContentTypeParams = 32
MaxContentTypeParams is the highest number of parameters ParseContentType keeps from a single Content-Type header. Anything beyond it is discarded.
The header is client-supplied and net/http accepts it up to MaxHeaderBytes (1MB by default), so without a cap a request of ";a=1;b=1;..." would have every read of Context.ContentType build a map of hundreds of thousands of attacker-chosen keys. No real content type carries more than a handful.
const RequestValueContextKey = "iris.rest.request"
RequestValueContextKey is the key used to store the request value in the Iris Context.
const UpdateColumnsQueryKey = "columns"
UpdateColumnsQueryKey is the URL query key BindUpdate reads the list of columns to update from: PUT/PATCH /resource/{id}?columns=a&columns=b.
const UserContextKey = "iris.user"
UserContextKey is the context key for the context's value to keep the authorized user information.
Variables ¶
var ( // ErrNoContentType is returned when the Content-Type is required but not provided. // It is used in the ParseContentType function. ErrNoContentType = fmt.Errorf("content-type is required but was not provided") // ErrNoContentTypeMediaType is returned when the media-type is required but not provided. // It is used in the ParseContentType function. ErrNoContentTypeMediaType = fmt.Errorf("media-type is required but was not provided") )
var ( // DefaultCharset is the default charset to use if none is provided. DefaultCharset = "utf-8" // MediaTypesRequiringCharset is a list of media types that typically require a charset parameter. MediaTypesRequiringCharset = map[string]struct{}{ "text/html": {}, "text/css": {}, "text/plain": {}, "text/xml": {}, "text/javascript": {}, "application/xml": {}, "application/problem+xml": {}, "application/x-yaml": {}, "application/xhtml+xml": {}, "application/atom+xml": {}, "application/rss+xml": {}, "application/soap+xml": {}, "application/svg+xml": {}, "application/x-www-form-urlencoded": {}, } )
var ( // ValidFilenameRegexp is used to validate the user input by using a regular expression. // See `Context.UploadFormFiles` method. ValidFilenameRegexp = regexp.MustCompile(`^[a-zA-Z0-9_\-\.]+$`) // ValidExtensionRegexp acts as an allowlist of valid extensions. It's optional. Defaults to nil (all file extensions are allowed to be uploaded). // See `Context.UploadFormFiles` method. ValidExtensionRegexp *regexp.Regexp )
var ( // IsErrEmptyJSON reports whether the given "err" says the request or // response body carried no JSON value at all (empty or truncated-empty). // The checks are structural — sentinel and typed errors, never error // text, which Go no longer guarantees to be stable. IsErrEmptyJSON = func(err error) bool { if err == nil { return false } if errors.Is(err, ErrEmptyJSON) { return true } if syn, ok := errors.AsType[*jsontext.SyntacticError](err); ok { return syn.ByteOffset == 0 && errors.Is(err, io.ErrUnexpectedEOF) } if errors.Is(err, io.EOF) { return true } if v, ok := errors.AsType[*json.SyntaxError](err); ok { return v.Offset == 0 } return false } // 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 // IsErrPathCSRFToken reports whether "err", or an error it wraps, is a // schema.MultiError that carries an unknown key error on "csrf.token". // See [Context.ReadForm] for more. IsErrPathCSRFToken = func(err error) bool { if err == nil { return false } if m, ok := errors.AsType[schema.MultiError](err); ok { if csrfErr, hasCSRFToken := m[CSRFTokenFormKey]; hasCSRFToken { _, is := csrfErr.(schema.UnknownKeyError) return is } } return false } // 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. // It is kept for backwards compatibility only: no method of this package // returns or wraps it anymore, so an errors.Is check against it never reports true. 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 `IsErrConnectionClosed` 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.Unix(0, 0) // 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 ( MarshalDurationAsNanos = jsonutil.MarshalDurationAsNanos UnmarshalDurationFromNanos = jsonutil.UnmarshalDurationFromNanos )
MarshalDurationAsNanos and UnmarshalDurationFromNanos preserve the old encoding/json representation of time.Duration — a plain int64 nanosecond count; see the jsonutil package, the single source of the framework's JSON policy. They are re-exported here so custom encoders can compose them without a second import.
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.
var ConcatHandlerLists = funcer.ConcatLists[Handler]
ConcatHandlerLists returns a new HandlerList which contains all the handlers of the given lists.
var DefaultCookieExpiration = 8760 * time.Hour
DefaultCookieExpiration is the lifetime Context.AddCookie gives a cookie when no CookieExpires option is passed: 365 days. Change it once for the whole process with iris.Patches().Context().SetDefaultCookieExpiration.
var DefaultJSONOptions = JSON{}
DefaultJSONOptions is the optional settings that are being used inside `Context.JSON`.
var DefaultJSONPOptions = JSONP{}
DefaultJSONPOptions is the optional settings that are being used inside `ctx.JSONP`.
var DefaultJSONReader = JSONReader{}
DefaultJSONReader is the default JSONReader configuration for the `Context.ReadJSON, ReadBody` methods.
var DefaultMarkdownOptions = Markdown{}
DefaultMarkdownOptions is the optional settings that are being used from `WriteMarkdown` and `ctx.Markdown`.
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 ErrEmptyJSON = fmt.Errorf("iris: read json: empty request body: %w", io.EOF)
ErrEmptyJSON is returned by the JSON body readers when the request carries no JSON value at all (an empty or whitespace-only body, or no body at all). It wraps io.EOF, so pre-existing errors.Is(err, io.EOF) checks keep matching.
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 ErrInvalidFileSystemRootName = errors.New("invalid root name")
ErrInvalidFileSystemRootName is returned by ListFileNames when the given root name escapes the file system, either by traversal or by naming an absolute operating-system path.
var ErrInvalidJSONPCallback = errors.New("invalid jsonp callback")
ErrInvalidJSONPCallback is returned by `WriteJSONP` when the JSONP callback is not a valid JavaScript identifier reference.
The callback is written into a "text/javascript" response verbatim, and the canonical way to populate it is from the request itself:
ctx.JSONP(v, iris.JSONP{Callback: ctx.Query().Get("callback")})
so an unvalidated callback is attacker-authored script served from the application's own origin.
var ErrJSONArrayExpected = errors.New("iris: read json stream: expected a JSON array")
ErrJSONArrayExpected is returned by ReadJSONStream with JSONReader.ArrayStream set when the body does not start with a JSON array.
var ErrNoOpFS = errors.New("no file system is configured")
ErrNoOpFS is returned by the no-operation file system's Open method. Use IsNoOpFS to test for the file system itself.
var ErrNotFound = errors.New("not found")
ErrNotFound is a generic error to use when something was not found.
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 ErrReadRequestBody = errors.New("failed to read request body")
ErrReadRequestBody is returned when the request body cannot be read.
var ErrRequestEntityTooLarge = errors.New("request entity too large")
ErrRequestEntityTooLarge is returned when the request body size is bigger than the limit.
var ErrSortNotAllowed = pagination.ErrSortNotAllowed
ErrSortNotAllowed is the error ListFilter.SortColumn wraps when the client asked to sort by a column the endpoint does not offer.
var FormatTime = func(ctx *Context, t time.Time) string {
return t.Format(ctx.OptionsReadOnly().TimeFormat)
}
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 ParseTime = func(ctx *Context, text string) (t time.Time, err error) { t, err = time.Parse(ctx.OptionsReadOnly().TimeFormat, 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 ReadJSON = func(ctx *Context, outPtr any, options *JSONReader) error { if ctx.request.Body == nil { return ErrEmptyJSON } dec := jsontext.NewDecoder(ctx.limitBody(ctx.request.Body)) if dec.PeekKind() == 0 { _, err := dec.ReadValue() if err == nil { err = io.ErrUnexpectedEOF } if errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) { return ErrEmptyJSON } return err } return jsonv2.UnmarshalDecode(dec, outPtr, options.unmarshalOptions()...) }
ReadJSON reads JSON from the request's body and binds it to a value of any json-valid type. Can be modified in order to change the default behavior of the `Context.ReadJSON, ReadBody` methods.
var ResolveFS = func(fsOrDir any) fs.FS { if fsOrDir == nil { return noOpFS{} } switch v := fsOrDir.(type) { case string: if v == "" { return noOpFS{} } return os.DirFS(v) case fs.FS: return v case http.FileSystem: return &httpFS{v} default: panic(fmt.Errorf(`unexpected "fsOrDir" argument type of %T (string or fs.FS or embed.FS or http.FileSystem)`, v)) } }
ResolveFS accepts a single input argument of any type and tries to cast it to fs.FS.
It affects the view engine's filesystem resolver.
This package-level variable can be modified on initialization.
var ResolveHTTPFS = func(fileSystemOrDirectory any) http.FileSystem { var fileSystem http.FileSystem switch v := fileSystemOrDirectory.(type) { case string: fileSystem = http.Dir(v) case http.FileSystem: fileSystem = v case embed.FS: direEtries, err := v.ReadDir(".") if err != nil { panic(err) } if len(direEtries) == 0 { panic("no directories found under the embedded file system") } subfs, err := fs.Sub(v, direEtries[0].Name()) if err != nil { panic(err) } fileSystem = http.FS(subfs) case fs.FS: fileSystem = http.FS(v) default: panic(fmt.Sprintf(`unexpected "fileSystemOrDirectory" argument type of %T (string or http.FileSystem or embed.FS or fs.FS)`, v)) } return fileSystem }
ResolveHTTPFS accepts a single input argument of any type and tries to cast it to http.FileSystem.
It affects the file server controller's `New` and `Handler` functions (the controller/fileserver package).
This package-level variable can be modified on initialization.
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.
Modify this variable when your Iris server or/and client not follows the RFC: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
var WriteJSON = func(ctx *Context, v any, options *JSON) error { opts := jsonutil.DefaultMarshalOptionsSlice if options.EscapeHTML || options.Indent != "" || len(options.MarshalOptions) > 0 { extended := make([]jsonv2.Options, 0, 4+len(options.MarshalOptions)) extended = append(extended, jsonutil.DefaultMarshalOptions) if options.EscapeHTML { extended = append(extended, jsontext.EscapeForHTML(true)) } if options.Indent != "" { extended = append(extended, jsontext.Multiline(true), jsontext.WithIndent(options.Indent)) } opts = append(extended, options.MarshalOptions...) } buf := jsonutil.AcquireBuffer() defer jsonutil.ReleaseBuffer(buf) if err := jsonv2.MarshalWrite(buf, v, opts...); err != nil { return err } buf.WriteByte('\n') result := buf.Bytes() if options.EscapeNonASCII { result = escapeNonASCII(result) } if prefix := options.Prefix; prefix != "" { if _, err := ctx.Write(stringToBytes(prefix)); err != nil { return err } } if options.ArrayPrefix && len(result) > 0 && result[0] == '[' { if _, err := ctx.Write(jsonArrayPrefix); err != nil { return err } } _, err := ctx.Write(result) return err }
WriteJSON marshals the given interface object and writes the JSON response to the 'writer'.
The value is marshaled into a pooled buffer first and written as one piece: streaming into the live response writer would emit a partial body when the marshaler fails halfway, corrupting the error response that follows.
var WriteJSONP = func(ctx *Context, v any, options *JSONP) error { callback := options.Callback if callback != "" && !IsValidJSONPCallback(callback) { return fmt.Errorf("%w: %q", ErrInvalidJSONPCallback, callback) } opts := []jsonv2.Options{jsonutil.DefaultMarshalOptions, jsontext.EscapeForHTML(true), jsontext.EscapeForJS(true)} if options.Indent != "" { opts = append(opts, jsontext.Multiline(true), jsontext.WithIndent(options.Indent)) } buf := jsonutil.AcquireBuffer() defer jsonutil.ReleaseBuffer(buf) if callback != "" { buf.WriteString(callback) buf.WriteByte('(') } if err := jsonv2.MarshalWrite(buf, v, opts...); err != nil { return err } buf.WriteByte('\n') if callback != "" { buf.Write(finishCallbackB) } _, err := ctx.Write(buf.Bytes()) return err }
WriteJSONP marshals the given interface object and writes the JSONP response to the writer.
The whole response (callback, payload, closing) is assembled in a pooled buffer and written as one piece, so a marshal failure leaves nothing on the wire; writing "callback(" first left a dangling script prefix in front of the error response that followed.
It returns `ErrInvalidJSONPCallback` when the callback is not a valid JavaScript identifier reference.
var WriteMarkdown = func(ctx *Context, markdownB []byte, options *Markdown) error { out := markdown.NormalizeNewlines(markdownB) renderer := html.NewRenderer(options.RenderOptions) doc := markdown.Parse(out, nil) out = markdown.Render(doc, renderer) if options.Sanitize { out = sanitizer.SanitizeBytes(out) } _, err := ctx.Write(out) return err }
WriteMarkdown parses the markdown to html and writes these contents to the writer.
var WriteXML = func(ctx *Context, v any, options *XML) error { if prefix := options.Prefix; prefix != "" { _, err := ctx.Write(stringToBytes(prefix)) if err != nil { return err } } encoder := xml.NewEncoder(ctx.writer) encoder.Indent("", options.Indent) if err := encoder.Encode(v); err != nil { return err } return encoder.Flush() }
WriteXML marshals the given interface object and writes the XML response to the writer.
var WriteYAML = func(ctx *Context, v any, indentSpace int) error { encoder := yaml.NewEncoder(ctx.writer) encoder.SetIndent(indentSpace) if err := encoder.Encode(v); err != nil { return err } return encoder.Close() }
WriteYAML sends YAML response to the client.
Functions ¶
func ContentTypeNoSniff ¶
func ContentTypeNoSniff(ct *ContentType)
ContentTypeNoSniff sets the X-Content-Type-Options header to nosniff.
func ContentTypeOnce ¶
func ContentTypeOnce(ct *ContentType)
ContentTypeOnce sets the Content-Type header only once.
func CookieCleanPath ¶
CookieCleanPath is a `CookieOption`. Use it to clear the cookie's Path field, exactly the same as `CookiePath("")`.
func CookieIncluded ¶
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 CookiePartitioned ¶
CookiePartitioned is a `CookieOption`. It enables the "Partitioned" cookie attribute. Read more at: https://github.com/golang/go/issues/62490#issuecomment-2127685955 and https://developers.google.com/privacy-sandbox/cookies.
func CookieSecure ¶
CookieSecure is a `CookieOption`. It sets the cookie's Secure option on set operation if the current request's connection is using TLS. See `CookieHTTPOnly` too.
func CookieSecureForce ¶
CookieSecureForce is a `CookieOption`. It sets the cookie's Secure option to true every time.
func CountToInt64 ¶
func CountToInt64[N CountType](n N) int64
CountToInt64 forwards to pagination.CountToInt64.
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 ¶
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 FlushResponseWriter ¶
func FlushResponseWriter(w http.ResponseWriter) error
FlushResponseWriter flushes w and reports whether the flush reached the transport, preferring a FlushError method over http.Flusher and unwrapping until it finds one. It is what ResponseWriter implementations that wrap another writer should delegate to.
func FormValueDefault ¶
FormValueDefault retruns a single parsed form value.
func GetForm ¶
GetForm returns the request form (url queries, post or multipart) values. It parses the form once.
A url-encoded body is read only for POST, PUT and PATCH, because that is what net/http's ParseForm does. On Go 1.27 the url-encoded body of a QUERY request (RFC 10008) is therefore not part of the form; send QUERY bodies as JSON and read them with ReadJSON or ReadBody. Multipart bodies are parsed for any method.
func GetHostname ¶
GetHostname returns the hostname part of the current URI.
func GetScheme ¶
GetScheme returns the full scheme of the request URL (https://, http:// or ws:// and e.t.c.).
func HandlerExists ¶
HandlerExists reports whether a handler with the given name or function exists in the "handlers" slice.
func HandlerFileLine ¶
HandlerFileLine returns the handler's file and line information. See `Context.HandlerFileLine` method to get the file, line of the current running handler in the chain.
func HandlerInfo ¶
HandlerInfo returns the file and line information of a handler.
func HandlerName ¶
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 IgnoreHandlerName ¶
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 IsErrCanceled ¶
IsErrCanceled reports whether the "err" is caused by a cancellation or timeout.
func IsValidJSONPCallback ¶
IsValidJSONPCallback reports whether the given JSONP callback is safe to write into a JavaScript response body. See `ErrInvalidJSONPCallback`.
func IsZeroTime ¶
IsZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
func ListFileNames ¶
func ListFileNames(fileSystem http.FileSystem, name string) ([]string, error)
ListFileNames accepts a "http.FileSystem" and a root name and returns the list containing its file names.
The name is cleaned and must stay inside the file system. That check is worth keeping even though http.Dir defends itself, because the file system may be an embed.FS, a go-bindata bundle or any other implementation that does not.
func MakeDisposition ¶
MakeDisposition generates an HTTP Content-Disposition field-value. Similar solution followed by: Spring(Java), Symfony(PHP) and Ruby on Rails frameworks too.
Fixes CVE-2020-5398. Reported by motoyasu-saburi.
func NegotiateAcceptHeader ¶
NegotiateAcceptHeader returns the best match from the "in" slice of Accept* headers based on the "offers". If no match is found it returns the "bestOffer", or "identity" when the "bestOffer" is empty. It returns an empty string when the best matching offer was explicitly rejected by the client with a q=0 quality factor.
func OnApplicationRegistered ¶
func OnApplicationRegistered(listeners ...func(app Application))
OnApplicationRegistered adds a function which fires when a new application is registered.
func PrivateErrorf ¶
PrivateErrorf accepts an error and returns a wrapped one which includes the "err" and an empty private error, by using fmt.Errorf, so the actual error message does contain the "err" message but this final, wrapped, error can be marked as an `ErrPrivate` one.
See rest/errors#UnwrapAll and rest/errors#err for more.
func RegisterApplication ¶
func RegisterApplication(app Application)
RegisterApplication registers an application to the global shared storage.
func ReleaseResponseWriter ¶
func ReleaseResponseWriter(w *DefaultResponseWriter)
ReleaseResponseWriter resets the response writer and returns it back to the pool.
func SafeFilename ¶
SafeFilename returns a safe filename based on the given name.
- Using filepath.Base and filepath.ToSlash: This ensures that only the base file name is used, without any directory components, and converts all separators to slashes. This is a good practice to prevent directory traversal.
- Regular Expression for Filenames: The ValidFilenameRegexp ensures that filenames are restricted to a safe character set. This helps prevent the use of special characters that could lead to path traversal or other types of injection attacks.
- Extension Validation: If you have a ValidExtensionRegexp, it would further ensure that the file has an expected and safe extension, which is another good practice.
- Canonical Path Check: By evaluating symlinks and ensuring that the destination path starts with the canonical destination directory, you’re adding.
It returns the destination path (the canonical prefix directory joined with the safe filename, or an empty string when prefixDir is empty), the safe filename, a boolean indicating whether the filename is safe, and an error if any. When the name is rejected - or the prefix directory cannot be resolved - the first two results are the unmodified prefixDir and name.
func SetCompressHeaders ¶
SetCompressHeaders sets the necessary headers for the compression.
func SetHandlerName ¶
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 for convenient between Iris versions, see middleware/accesslog init function for example.
func SetRestErrorRenderer ¶
func SetRestErrorRenderer(r RestErrorRenderer)
SetRestErrorRenderer sets the renderer used by the Context's typed binding/response methods to render their error responses. It's called by the rest/errors package at init time; a nil value is ignored.
func StatusText ¶
StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.
func TrimHeaderValue ¶
TrimHeaderValue returns the "v[0:first space or semicolon]".
func TrimParamFilePart ¶
func TrimParamFilePart(ctx *Context)
TrimParamFilePart is a middleware which replaces all route dynamic path parameters with values that do not contain any part after the last dot (.) character.
Example Code:
package main
import (
"github.com/kataras/iris/v14"
)
func main() {
app := iris.New()
app.Get("/{uid:string regexp(^[0-9]{1,20}.html$)}", iris.TrimParamFilePart, handler)
// TrimParamFilePart can be registered as a middleware to a Router (group of routes) as well.
app.Listen(":8080")
}
func handler(ctx iris.Context) {
//
// The above line is useless now that we've registered the TrimParamFilePart middleware:
// uid := ctx.Params().GetTrimFileInt("uid")
//
uid := ctx.Params().GetUint64("uid")
ctx.Writef("Param value: %d\n", uid)
}
func UnwrapResponseWriter ¶
func UnwrapResponseWriter(w http.ResponseWriter) http.ResponseWriter
UnwrapResponseWriter unwraps all the wrappers and returns the simple, underlying and original http.ResponseWriter.
Types ¶
type Application ¶
type Application interface {
Router
// 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 exists as Context.IsDebug() too.
IsDebug() bool
// ListRoutesReadOnly returns a read-only version of the registered routes.
ListRoutesReadOnly() []RouteReadOnly
// ContextPool returns the Iris sync.Pool which holds the contexts values.
// Iris automatically releases the request context, so you don't have to use it.
// It's only useful to manually release the context on cases that connection
// is hijacked by a third-party middleware and the http handler return too fast.
ContextPool() *Pool
// ContextOptions returns the context's configuration.
ContextOptions() *ContextOptions
// RegisterOnBuild registers callback functions to be executed before or/and after the application is built.
// The callbacks are executed after the application's internal state is constructed but before the server is started.
RegisterOnBuild(beforeBuild, afterBuild func() error)
// HandleRequest 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.
HandleRequest(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.
// Every closer runs even if one of them fails, the returned error joins all the
// failures (match individual ones with errors.Is/errors.As), otherwise nil.
Shutdown(ctx stdContext.Context) error
// 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 ¶
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 ¶
func GetApplications() []Application
GetApplications returns a slice of all the registered Applications.
func LastApplication ¶
func LastApplication() Application
LastApplication returns the last registered Application. Handlers has access to the current Application, use `Context.Application()` instead.
func MustGetApplication ¶
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.
type BodyDecoderWithContext ¶
BodyDecoderWithContext same as BodyDecoder but it can accept a standard context, which is binded to the HTTP request's context.
type Component ¶
Component is the interface which all components must implement. A component is a struct which can be rendered to a writer. It's being used by the `Context.RenderComponent` method. An example of compatible Component is a templ.Component.
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) 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 ¶
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 ContentType ¶
type ContentType struct {
MediaType string // The MIME type of the resource or the data.
Charset string // The character encoding standard.
Boundary string // The boundary parameter for multipart entities.
Version int // The version parameter for the content type.
Params map[string]string // Any other parameters in the Content-Type. May be nil if there are none.
// raw string
NoSniff bool // Whether to set the X-Content-Type-Options header to nosniff, it's used by setters methods and it's not part of the content-type literal.
Once bool // Whether to set the Content-Type header only once, it's used by setters methods and it's not part of the content-type literal.
}
ContentType represents the structured parts of the Content-Type header.
func ParseContentType ¶
func ParseContentType(contentType string) (ContentType, error)
ParseContentType takes a Content-Type string and returns a ContentType struct.
The media type, the parameter names and the charset are lowercased, as those are case-insensitive. Every other parameter value is kept verbatim, because values such as a multipart boundary are matched literally against the body.
func (ContentType) String ¶
func (ct ContentType) String() string
String returns the raw Content-Type header value. It will be constructed from the MediaType, Charset, Boundary, and Params fields. The constructed value will be in the format "media-type; charset=charset; boundary=boundary; version=1; key=value", e.g. application/json; charset=utf-8; version=2. The media-type is required, and the charset and boundary are optional. The key-value pairs are the other parameters in the Content-Type. The key-value pairs are separated by a semicolon. The key and value are separated by an equal sign. Only the media type, the parameter names and the charset are lowercased; parameter values such as the multipart boundary are kept verbatim.
type ContentTypeOption ¶
type ContentTypeOption func(*ContentType)
ContentTypeOption is a function that modifies a ContentType. It is used on `SetContentType` method.
Available options: - ContentTypeCharset - ContentTypeNoSniff - ContentTypeOnce
func ContentTypeCharset ¶
func ContentTypeCharset(charset string) ContentTypeOption
ContentTypeCharset sets the charset parameter of the Content-Type.
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context is the middle-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.
Context implements the standard library's context.Context, so a handler can pass it directly to code that takes one. Do that only for calls that finish before the handler returns: the Context is pooled and reused across requests, so a consumer that keeps it longer (an HTTP client's transport, a spawned goroutine, a database driver) ends up reading a released Context's state. For those, pass StdContext, or WithoutCancel for work that must survive the request's cancellation.
Corresponding source code files:
- context.go
- context_request.go
- context_response.go
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) AddCookie ¶
func (ctx *Context) AddCookie(name, value string, options ...CookieOption)
AddCookie adds a cookie, requires the name(string) and the value(string). It goes through Context.SetCookie, so a second AddCookie with the same name, path and domain replaces the first one instead of adding a second line.
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.AddCookie(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.AddCookie(name, value, iris.CookieCleanPath/iris.CookiePath("")) More:
iris.CookieExpires(time.Duration) iris.CookieHTTPOnly(false)
func (*Context) AddCookieOptions ¶
func (ctx *Context) AddCookieOptions(options ...CookieOption)
AddCookieOptions adds cookie options for `SetCookie`, `AddCookie` 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:
- CookieOverride
- CookieDomain
- CookieAllowReclaim
- CookieAllowSubdomains
- CookieSecure
- CookieHTTPOnly
- CookieSameSite
- CookiePath
- CookieCleanPath
- CookieExpires
- CookieEncoding
func (*Context) AddHandler ¶
AddHandler appends handler(s) to this request's chain at serve-time. The handlers run after the ones already registered on the route and are not persisted back to the router: the next request starts from the route's own chain again.
See SetHandlers to replace the chain instead, and NewConditionalHandler to insert handlers in the middle of it.
func (*Context) AddHeader ¶
AddHeader adds a header value to the response, keeping any value already set for that name: calling it twice with the same name emits the header twice. That is what a list-valued header such as Vary or Link needs, and what a single-valued one does not; use `SetHeader` for those. An empty value is ignored.
func (*Context) Addr ¶
Addr returns the remote address of the client. Its different from `RemoteAddr` because it doesn't try to parse the real client's request IP as a public one, so this can return a valid value even if the client is a local one.
SECURITY WARNING: never use this for access control, rate limiting or any other authorization decision.
When Options.RemoteAddrHeaders is configured, this returns the FIRST entry of the first matching header - the left-most hop, which is entirely written by the client. Any caller can send "X-Forwarded-For: 10.0.0.1" and be seen as that address. Unlike `RemoteAddr`, no private-subnet filtering is applied and RemoteAddrHeadersForce is not consulted.
Use `RemoteAddr` for anything that makes a decision about the request, and only enable RemoteAddrHeaders when running behind a trusted proxy that overwrites those headers.
Addr exists for logging and diagnostics, where seeing the client's own claim (including a private-network address) is the point.
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) Binary ¶
Binary writes out the raw bytes as binary data. It returns any write error; see `Write` for the byte count.
func (*Context) BindJSON ¶
BindJSON reads a JSON payload and returns it as a generic type Request. It also returns a boolean value indicating whether the read was successful or not. If the read fails, it sends an appropriate error response to the client. If the Request type implements the Validatable interface, its Validate method runs after decoding and a non-nil result rejects the request.
func (*Context) BindJSONList ¶
BindJSONList reads the request body from the context and attempts to unmarshal it into either a single object or an array of objects of type Request. It returns a slice of objects of type Request and a boolean indicating whether the unmarshalling was successful. If the unmarshalling fails, it handles the JSON error and returns nil values along with a boolean indicating failure. If the body contains a single object, it is converted into a slice of objects.
func (*Context) BindJSONOneOrMany ¶
BindJSONOneOrMany reads the request body from the context and attempts to unmarshal it into either a single object or an array of objects of type Request. It returns a pointer to the single object, a slice of objects, and a boolean indicating whether the unmarshalling was successful. If the unmarshalling fails, it handles the JSON error and returns nil values along with a boolean indicating failure.
Returns: - A pointer to a single object of type Request if the body contains a single object. - A slice of objects of type Request if the body contains an array of objects. - A boolean indicating whether the unmarshalling was successful.
func (*Context) BindJSONOptional ¶
BindJSONOptional reads a JSON payload like BindJSON but treats an empty request body as success: it returns the zero value of Request with true and skips validation. Use it when the request body is optional.
func (*Context) BindPagination ¶
func (ctx *Context) BindPagination[Filter any](opts ...PaginationOption) (PageOptions, Filter, bool)
BindPagination reads the PageOptions from the URL Query and any filter options of generic Filter type from the request body.
The options police the sort request the filter carries, see AllowSort and DenySort. A rejected sort answers 400 Bad Request and BindPagination reports false.
func (*Context) BindParam ¶
BindParam returns a single path parameter of type T.
It returns false if the parameter is not found or if the parameter is not of the expected type. It sends a 404 Not Found or 400 Bad Request error to the client.
func (*Context) BindParams ¶
BindParams returns the path parameters bound to a struct of type Struct (field tag `param`) via `ctx.ReadParams`.
It returns false and sends a client error if the path parameters binder failed.
func (*Context) BindUpdate ¶
BindUpdate decodes the JSON body into T and reads the "columns" query key, the list of columns the client wants updated.
The columns arrive either as a repeated key (?columns=a&columns=b) or as one comma-separated value (?columns=a,b); values are trimmed, empties dropped and duplicates removed, keeping the client's order. No columns at all means a full update and returns a nil slice.
A full update decodes exactly as BindJSON does: the app-level request validator runs and so does T's own Validate method. A partial update runs the request validator but skips T's Validate: the body is incomplete by design, every member the client did not name stays at its zero value, and a whole-value check would reject the request for members that are not even being written (a one-column body failing on "measurement unit is required" is the shape of that bug). Whatever a partial write still has to enforce belongs to the caller, which knows the columns.
Every column is checked against the JSON member names of T (the json tag name, or the Go field name when there is no tag) and an unknown one answers 400 naming the column and the allowed names. Without that check a typo updates nothing and the client is told the request succeeded. The comparison is exact where the body decoder is case-insensitive: a column reaches an UPDATE statement, so the endpoint must receive the spelling it declared and not a normalised guess. A T that is not a struct (a map, say) has no member names to check against and every column is accepted.
It returns false when a response was already written, exactly like BindJSON.
Usage:
func(ctx iris.Context) {
input, columns, ok := ctx.BindUpdate[UpdateUser]()
if !ok {
return
}
updated, err := svc.UpdateUser(ctx, id, input, columns...)
ctx.NoContent(updated, err)
}
func (*Context) Body ¶
Body reads the request body and returns its content as a byte slice.
When ContextOptions.BodyMaxMemory is set, reading a body larger than the limit returns ErrRequestEntityTooLarge. A request without a body (nil, which the net/http server never produces but hand-built requests do) returns ErrReadRequestBody.
func (*Context) BodyLength ¶
BodyLength returns the request body length in bytes. When the content-length is known it is reported as-is, without touching the body (if the content-length is missing http sets the body to http.NoBody, so it returns 0). When the content-length is unknown (-1, e.g. a chunked request) the body is DRAINED in order to measure it, therefore a later `Body`/`ReadJSON` call reads nothing unless the request body was recorded first (see the middleware/recorder package).
Returns ErrReadRequestBody if the body is nil or if an error occurs while reading it.
func (*Context) Charset ¶
Charset returns the charset of the request's Content-Type header. If the Content-Type header parsing failed or provided but charset parameter is empty it returns an empty string.
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) 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", "HEAD" or "QUERY" 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 ¶
func (ctx *Context) ClearCookieOptions()
ClearCookieOptions clears any previously registered cookie options. See `AddCookieOptions` too.
func (*Context) ClientSupportsEncoding ¶
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 the `middleware/compress` middleware to actually compress the response.
func (*Context) Clone ¶
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 request is copied through http.Request.Clone, keeping the same standard context, therefore modifying the clone's URL or Header does not affect the original request; the request's Body reader is still shared between the two.
func (*Context) ContentLength ¶
ContentLength returns the request's body length in bytes, or -1 when it is unknown (a chunked request, for example).
Note(@kataras): this reads Request.ContentLength rather than re-parsing the header. ctx.Header joins duplicate headers with ", ", so a client sending two Content-Length headers produced a value like "10, 10" that ParseInt rejected, and the method silently answered 0 - the exact case a size guard needs to catch. net/http has already validated and reconciled the framing by the time a handler runs.
func (*Context) ContentType ¶
func (ctx *Context) ContentType() ContentType
ContentType returns the request's Content-Type header.
func (*Context) Cookie ¶
Cookie returns the request cookie including any context's cookie options (stored or given by this method).
func (*Context) CookieValue ¶
func (ctx *Context) CookieValue(name string, options ...CookieOption) string
CookieValue 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.Cookie("name")
func (*Context) Count ¶
Count handles a count response and error from a service call and sends a JSON `CountResponse` to the client. If the error is not nil, it sends an appropriate error response to the client. A zero count is a valid 200 answer, `{"count":0}`; a negative count renders as zero. (304 Not Modified is a conditional-request status and net/http refuses to send a body with it.) It returns a boolean value indicating whether the handle was successful or not.
func (*Context) Created ¶
Created handles a generic response and error from a service call and sends a 201 JSON response to the client. If the error is not nil, it renders it through the error renderer and returns false.
A bare identifier is wrapped as an IDPayload: a string, int, int64 or uint64 value renders as {"id": value} and a uuid.UUID as {"id": "..."} (its string form). Any other value, a struct, a map or a slice, renders as it is; a []string is a JSON array of strings, not a list of id payloads. A nil "resp" writes no body.
It returns a boolean value indicating whether the handle was successful or not.
Usage:
func(ctx iris.Context) {
id, err := svc.CreateUser(ctx, input)
ctx.Created(id, err) // 201 {"id": ...}
}
func (*Context) CurrentRoute ¶
func (ctx *Context) CurrentRoute() RouteReadOnly
CurrentRoute returns the current "read-only" route that was registered to this request's path.
func (*Context) Deadline ¶
Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.
Shortcut of Request().Context().Deadline(). A released Context reports no deadline, see Done.
func (*Context) DisableResponseBuffering ¶
DisableResponseBuffering removes every response-writer wrapper that buffers or transforms the body, restoring a chain that reaches the client on every flush.
It is what lets a streaming route survive middleware that is correct for an ordinary response and wrong for a stream. middleware/compress buffers into a compressor; middleware/recorder buffers into a bytes.Buffer, and accesslog installs a recorder whenever it reads the response body, which the builder enables by default. Neither forwards anything on a flush, so the handler streams into a buffer and the client sees one lump when the handler returns, or nothing at all.
Call it before the first write. Wrappers cooperate through ResponseWriterDisabler, so one that does not implement it - a third-party writer, say - stops the walk and is named in the returned error instead of silently swallowing the stream.
The sse package calls this for you.
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) Done ¶
func (ctx *Context) Done() <-chan struct{}
Done returns a channel that's closed when work done on behalf of this context should be canceled. Done may return nil if this context can never be canceled. Successive calls to Done return the same value. The close of the Done channel may happen asynchronously, after the cancel function returns.
WithCancel arranges for Done to be closed when cancel is called; WithDeadline arranges for Done to be closed when the deadline expires; WithTimeout arranges for Done to be closed when the timeout elapses.
Done is provided for use in select statements:
// Stream generates values with DoSomething and sends them to out
// until DoSomething returns an error or ctx.Done is closed.
func Stream(ctx context.Context, out chan<- Value) error {
for {
v, err := DoSomething(ctx)
if err != nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case out <- v:
}
}
}
See https://blog.golang.org/pipelines for more examples of how to use a Done channel for cancellation.
Shortcut of Request().Context().Done().
Once the router has released this Context to its pool (the handler chain returned), it behaves as a canceled standard context: Done is closed, Err returns context.Canceled and Value only consults the request-scoped Values store, which is empty by then. This keeps code that holds on to the Context past the handler's return from dereferencing the request it no longer owns. pgx is one such holder: when the acquirer gives up mid-dial, jackc/puddle finishes dialing with the acquirer's context for Value lookups, and the Go resolver's context.WithDeadline then calls Value on it. The pooled Context may already serve another request by then, so this is a safety net, not a contract: pass StdContext() or WithoutCancel() to anything that may outlive the handler.
func (*Context) DumpRequest ¶
DumpRequest returns the given request in its HTTP/1.x wire representation. It should only be used by servers to debug client requests. If "includeBody" is true the request body is drained, if it's already drained it cannot be captured (unless the middleware/recorder package's RecordRequestBody(ctx) was called previously), so store the dump request in a middleware before the main handler.
It just calls the standard httputil.DumpRequest function.
func (*Context) Err ¶
Err reports why the request's context was canceled, if it was.
If Done is not yet closed, Err returns nil. If Done is closed, Err returns a non-nil error explaining why: Canceled if the context was canceled or DeadlineExceeded if the context's deadline passed. After Err returns a non-nil error, successive calls to Err return the same error.
Shortcut of Request().Context().Err(). A released Context returns context.Canceled, see Done.
func (*Context) ErrPublic ¶
ErrPublic 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) EscapedPath ¶
EscapedPath returns the request path in its percent-encoded form, as the client sent it: "/a%20b" stays "/a%20b". See `Path` for the decoded form.
func (*Context) FindClosest ¶
FindClosest returns a list of "n" paths close to this request based on subdomain and request path.
Order may change.
func (*Context) Form ¶
func (ctx *Context) Form() encoding.StringSliceEntries
Form returns the parsed form data, including both the URL field's query parameters and the PATCH, POST, or PUT form (and multipart) data.
func (*Context) FormFile ¶
FormFile returns the first uploaded file that received from the client.
The form's memory maximum size defaults to 32MB. Change it through Options.Context.PostMaxMemory, or bound the whole body with Options.Context.BodyMaxMemory.
The returned header's Filename is the client's, unsanitized. Run it through SafeFilename before it reaches the filesystem, or use Context.UploadFormFiles, which does that for you.
Example: https://github.com/kataras/iris/tree/main/_examples/04-request/uploads
func (*Context) FormFiles ¶
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) FullRequestURI ¶
FullRequestURI returns the full URI, including the scheme, the host and the relative requested path/resource.
func (*Context) GetErr ¶
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) GetStatusCode ¶
GetStatusCode returns the current status code of the response. Look StatusCode too.
func (*Context) HTML ¶
HTML writes out a string as text/html.
The body is written exactly as given. Nothing here escapes it, so interpolating a request value into the string is a cross-site scripting hole. Render through the view middleware, which escapes by default, or build the markup with html/template.
It returns any write error; see `WriteString` for the byte count.
func (*Context) HandleError ¶
HandleError renders "err" through the error renderer (see rest/errors.HandleError) and reports whether it did, so a step that has an error but nothing to render on success is one guarded line:
func(ctx iris.Context) {
if ctx.HandleError(svc.DeactivatePlans(ctx, id)) {
return
}
// [... the next step]
}
A nil error writes nothing and reports false, so the handler continues. An unrecognized error renders as 500; the mappings are the application's, declared through rest/errors.Options.
It is the error half that OK, Created, NoContent, List, Count and Paginated each run before rendering their success body, on its own for the steps that have no such body.
func (*Context) HandlerFileLine ¶
HandlerFileLine returns the current running handler's function source file and line information. Useful mostly when debugging. It returns an empty file and a zero line if the execution has stopped or no handler is running.
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. It returns an empty string if the execution has stopped or no handler is running.
func (*Context) Header ¶
Header returns the REQUEST header's value based on its name, i.e. a header the client sent. Headers this handler set on the response are read back through Context.ResponseHeader.
apiKey := ctx.Header("X-API-Key") // request (what the client sent)
cached := ctx.ResponseHeader("X-Cache") // response (what this handler set)
When the client repeats a header, its values are returned joined by comma and space, unlike http.Header.Get which returns only the first. Code that compares the result against a secret therefore rejects a request carrying two copies of the header rather than honoring the first.
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 respects the `HostProxyHeaders` setting.
func (*Context) Hostname ¶
Hostname returns the hostname part of the request URI. This method respects the `HostProxyHeaders` setting.
func (*Context) ID ¶
ID returns the Request Context's ID. It returns nil if not given by a prior `SetID` call. See `middleware/requestid` 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 ¶
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 ¶
IsDebug reports whether the application runs with debug log level. It is a shortcut of Application.IsDebug().
func (*Context) IsHTTP2 ¶
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) IsMediaType ¶
IsMediaType reports whether the request's or response's Content-Type header contains at least one provided media type.
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) IsRecovered ¶
func (ctx *Context) IsRecovered() (*ErrPanicRecovery, bool)
IsRecovered reports whether this handler has been recovered by the Iris recover middleware.
func (*Context) IsSSL ¶
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 "v" value to JSON and writes the response to the client.
It reports any JSON parser or write errors back to the caller. Set Options.Context.ErrorHandler (or iris.WithErrorHandler for a per-request override) to replace the default 500 error response.
The behavior of every `Context.JSON` call can be customized by replacing the package-level `WriteJSON` function on program initialization.
func (*Context) JSONOrError ¶
JSONOrError sends "resp" as a JSON response to the client and, when encoding or writing it fails, renders that failure through the error renderer as a server error (see rest/errors.HandleResponseJSONError). It returns a boolean value indicating whether the handle was successful or not. If it's not successful, an error is written to the client and the caller should stop the execution flow with a `return` statement.
It is the response half of OK, Created, Count and Paginated; use it when the status code or the value needs preparing first.
Usage:
func(ctx iris.Context) {
ctx.StatusCode(iris.StatusAccepted)
if !ctx.JSONOrError(job) {
return
}
// [... do other jobs here, e.g. run a go routine]
}
func (*Context) JSONP ¶
JSONP marshals the given "v" value to JSON and sends the response to the client.
It reports any JSON parser or write errors back to the caller. Set Options.Context.ErrorHandler (or iris.WithErrorHandler for a per-request override) to replace the default 500 error response.
func (*Context) LastPathParameter ¶
func (ctx *Context) LastPathParameter() (lastParameter macro.TemplateParam)
LastPathParameter returns the last path parameter of the current route.
func (*Context) List ¶
List renders "items" as a 200 JSON array. A nil or empty slice renders [] and never null, so a client can always iterate the answer.
An error that matches one of "tolerate" (errors.Is) also renders [] with 200: a repository's not-found for an empty set is not a failure of the list endpoint. Any other error goes through the error renderer and List returns false, so the caller stops the handler with a `return`.
A non-slice, non-array "items" is a programmer error and panics naming the type.
Usage:
func(ctx iris.Context) {
users, err := svc.ListUsers(ctx)
ctx.List(users, err, sql.ErrNoRows)
}
func (*Context) Markdown ¶
Markdown parses the markdown to html and renders its result to the client.
It reports any Markdown parser or write errors back to the caller. Set Options.Context.ErrorHandler (or iris.WithErrorHandler for a per-request override) to replace the default 500 error response.
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) MediaType ¶
MediaType returns the media type of the request's Content-Type header. If the Content-Type header does not contain a mime type, returns an empty string.
func (*Context) MsgPack ¶
MsgPack marshals the given "v" value of msgpack format and writes its result to the client.
It reports any message pack or write errors back to the caller. Set Options.Context.ErrorHandler (or iris.WithErrorHandler for a per-request override) to replace the default 500 error response.
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.Negotiation()` 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/tree/main/_examples/05-response/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) NoContent ¶
NoContent handles an error from a service call and sends an empty response to the client. If the error is not nil, it renders it through the error renderer and returns false.
A true "modified" sends 204 No Content: the delete or the update changed something. A false one sends 304 Not Modified, with no body: the call succeeded but nothing changed. Both report true.
It returns a boolean value indicating whether the handle was successful or not.
Usage:
func(ctx iris.Context) {
deleted, err := svc.DeleteUser(ctx, id)
ctx.NoContent(deleted, err) // 204, 304, or the mapped error.
}
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.Router("/users") users.Done(func(ctx iris.Context){ if ctx.GetStatusCode() == 400 { /* custom error code for /users */ }})
func (*Context) OK ¶
OK handles a generic response and error from a service call and sends a JSON response to the client. If the error is not nil, it renders it through the error renderer (see rest/errors.HandleError) and returns false. It leaves the status code untouched (defaults to 200 OK). A nil "resp" writes no body. It returns a boolean value indicating whether the handle was successful or not.
Usage:
func(ctx iris.Context) {
users, err := svc.ListUsers(ctx)
ctx.OK(users, err)
}
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.
The Context handed to "cb" is a snapshot taken at the moment OnConnectionClose is called, not at the moment the connection goes away. Values and params set by handlers that run later in the chain are therefore not visible to the callback; read what the callback needs before registering it, or pass it through the closure.
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.
func (*Context) OnRelease ¶
func (ctx *Context) OnRelease(fn func())
OnRelease registers fn to run once the handler chain has returned, right before the response writer and this Context go back to their pools. It runs on the request's own goroutine, so it may touch the Context, and it is the last point at which the response writer is still this request's.
It exists for goroutines that write to the response after the handler has moved on - a heartbeat, a ticker that drains a batch - and would otherwise find the writer gone or, worse, serving the next request: the Context is recycled inside ServeHTTP, before net/http cancels the request context, so waiting on Request().Context().Done() is not enough. Stop such a goroutine here and wait for it.
Hooks run in reverse registration order, like defer. They are dropped once run, so nothing carries over to the next request served by the same pooled Context. Keep them short: the connection is held until they return. A hook may register another, which runs in the same call; a hook must not register itself again, because RunReleaseHooks makes a bounded number of passes and drops what is left.
It is unrelated to OnConnectionClose, which fires on a separate goroutine when the client goes away, possibly long before the handler chain returns.
func (*Context) Options ¶
func (ctx *Context) Options() *ContextOptions
Options returns the context (request and response) options, can be edited.
func (*Context) OptionsReadOnly ¶
func (ctx *Context) OptionsReadOnly() *ContextOptions
OptionsReadOnly returns the context (request and response) options, read-only, the caller should not modify the contents because it may be alter the original instance of default options, Use the `Options` method for read and write access instead. This method is mostly used internally by the Framework.
func (*Context) Paginated ¶
func (ctx *Context) Paginated[Filter any, Item any, TotalCount CountType](collect ItemsCollectorFunc[Filter, Item, TotalCount], opts ...PaginationOption) bool
Paginated is a helper method that reads pagination options from the request context, calls the given collect function to collect items and returns them in a paginated response. It returns a boolean value indicating whether the handle was successful or not. If it's not successful, an error is written to the client and the caller should stop the handler's execution flow with a `return` statement.
Usage:
ctx.Paginated(func(_ context.Context, pageOpts iris.PageOptions, filter food.Filter) ([]food.Food, int64, error) {
items, totalCount, err := api.foodService.ListFoodsPaginated(ctx, pageOpts, filter, customerID)
return items, totalCount, err
}, iris.AllowSort("name", "created_at"))
func (*Context) Params ¶
func (ctx *Context) Params() *encoding.PathParams
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 request path in its decoded form (URL.Path): "/a%20b" reads "/a b". See `EscapedPath` for the percent-encoded form the client sent.
func (*Context) PostForm ¶
func (ctx *Context) PostForm() encoding.StringSliceEntries
PostForm returns the parsed form data from PATCH, POST or PUT body parameters.
func (*Context) Protobuf ¶
Protobuf marshals the given "v" value of proto Message and writes its result to the client.
It reports any protobuf parser or write errors back to the caller. Set Options.Context.ErrorHandler (or iris.WithErrorHandler for a per-request override) to replace the default 500 error response.
func (*Context) ProtobufJSON ¶
ProtobufJSON marshals the given "m" value of proto Message to JSON and writes the response to the client. It reports any JSON parser or write errors back to the caller.
func (*Context) Query ¶
func (ctx *Context) Query() encoding.StringSliceEntries
Query returns the request's URL query as typed accessors: Get, GetInt, GetBool, GetSlice and the rest of encoding.StringSliceEntries. Values are split on ContextOptions.URLParamSeparator and parsed once per request; the entries are cached on the Context for its lifetime.
For the raw url.Values use ctx.Request().URL.Query().
func (*Context) QueryBool ¶
func (ctx *Context) QueryBool(key string, opts ...QueryOption) (bool, bool)
QueryBool returns the value of a URL query key parsed as a bool. It accepts what strconv.ParseBool accepts plus yes/no/on/off, case-insensitively.
A present but unparsable value is always a 400 Bad Request naming the key, never a silent false. See QueryDate for the options and the second result.
func (*Context) QueryDate ¶
func (ctx *Context) QueryDate(key string, opts ...QueryOption) (types.SimpleDate, bool)
QueryDate returns the value of a URL query key parsed as a types.SimpleDate ("2006-01-02", or "2006-1-2").
A present but unparsable value is always a 400 Bad Request naming the key and the shape expected: a garbage parameter must not read as a silent zero, which every hand-written date filter does today and answers 200 with the wrong rows. The second result reports whether the caller may continue; false means a response was already written.
The key may name several alternatives separated by a space, tried in order, so an endpoint that answers to more than one spelling states them once:
date, ok := ctx.QueryDate("date day from")
A URL query key cannot contain a space, so a key without one is a single key and reads exactly as before.
func (*Context) QueryInt ¶
func (ctx *Context) QueryInt(key string, opts ...QueryOption) (int, bool)
QueryInt returns the value of a URL query key parsed as an int.
A present but unparsable value is always a 400 Bad Request naming the key, never a silent zero. See QueryDate for the options and the second result.
func (*Context) ReadBody ¶
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". If tag is missing it tries to bind using the field's name. To ignore a specific field from binding use tag value "-". 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)`.
ReadForm drops only the unknown key error for "csrf.token" (CSRFTokenFormKey), the hidden field CSRF protection usually adds to a form, and returns every other decode error as a schema.MultiError without that entry. The decoder splits keys on dots, so to bind the token give the struct a field tagged `form:"csrf"` whose type has a field tagged `form:"token"`.
Example: https://github.com/kataras/iris/blob/main/_examples/04-request/query-and-forms/main.go
func (*Context) ReadHeader ¶
ReadHeader binds request header to "ptr". The struct field tag is "header".
func (*Context) ReadJSON ¶
func (ctx *Context) ReadJSON(outPtr any, opts ...JSONReader) error
ReadJSON reads JSON from request's body and binds it to a value of any json-valid type.
The read is bounded by Options.Context.BodyMaxMemory when you have set it, and a body past that limit fails with ErrRequestEntityTooLarge, which the error map renders as 413. Without it the body is read in full, so set it or register the bodylimit middleware before accepting untrusted input.
After a successful decode, Options.Context.RequestValidator runs if one is registered. Pass a JSONReader to change decoder behavior for this call, for example DisallowUnknownFields.
Example: https://github.com/kataras/iris/blob/main/_examples/04-request/read-json-validate/main.go
func (*Context) ReadJSONStream ¶
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.
func (*Context) ReadMsgPack ¶
ReadMsgPack binds the request body of msgpack format to the "ptr" and returns any error.
func (*Context) ReadMultipartRelated ¶
func (ctx *Context) ReadMultipartRelated() (MultipartRelated, error)
ReadMultipartRelated returns a structure which contain information about each part (id, headers, body).
Read more at: https://www.ietf.org/rfc/rfc2387.txt.
Example request (2387/5.2 Text/X-Okie): Content-Type: Multipart/Related; boundary=example-2; start="<950118.AEBH@XIson.com>" type="Text/x-Okie"
--example-2 Content-Type: Text/x-Okie; charset=iso-8859-1; declaration="<950118.AEB0@XIson.com>" Content-ID: <950118.AEBH@XIson.com> Content-Description: Document
{doc} This picture was taken by an automatic camera mounted ... {image file=cid:950118.AECB@XIson.com} {para} Now this is an enlargement of the area ... {image file=cid:950118:AFDH@XIson.com} {/doc} --example-2 Content-Type: image/jpeg Content-ID: <950118.AFDH@XIson.com> Content-Transfer-Encoding: BASE64 Content-Description: Picture A
[encoded jpeg image] --example-2 Content-Type: image/jpeg Content-ID: <950118.AECB@XIson.com> Content-Transfer-Encoding: BASE64 Content-Description: Picture B
[encoded jpeg image] --example-2--
func (*Context) ReadParams ¶
ReadParams binds URL Dynamic Path Parameters to "ptr". The struct field tag is "param".
func (*Context) ReadProtobuf ¶
ReadProtobuf binds the body to the "ptr" of a proto Message and returns any error. Look `ReadProtobufJSON` too.
func (*Context) ReadProtobufJSON ¶
ReadProtobufJSON reads a JSON body request into the given "ptr" proto.Message. Look `ReadProtobuf` too.
func (*Context) ReadQuery ¶
ReadQuery binds URL Query to "ptr". The struct field tag is "url". If tag is missing it tries to bind using the field's name. To ignore a specific field from binding use tag value "-".
func (*Context) ReadURL ¶
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) ReadValues ¶
ReadValues binds this context's values to "ptr". The struct field tag is "context".
func (*Context) ReadXML ¶
ReadXML reads XML from request's body and binds it to a value of any xml-valid type.
func (*Context) ReadYAML ¶
ReadYAML reads YAML from request's body and binds it to the "outPtr" value.
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 (permanent redirect), StatusTemporaryRedirect(307) or 303 (StatusSeeOther) if POST method.
Redirect calls StopExecution, so the handlers after this one in the chain do not run.
SECURITY: the target is written to the Location header as given. Redirecting to a URL that came from the request, a "?next=" query value being the usual case, lets a caller send your users to any site they choose while the link still reads as yours. Match untrusted targets against an allowlist, or accept only a path:
next := ctx.Query().Get("next")
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") {
next = "/"
}
ctx.Redirect(next)
func (*Context) RemoteAddr ¶
RemoteAddr returns the client's IP address.
SECURITY WARNING: This method trusts headers configured in RemoteAddrHeaders. Only enable RemoteAddrHeaders when running behind a trusted proxy.
Configuration:
- RemoteAddrHeaders: Headers to check for client IP (default: empty)
- RemoteAddrPrivateSubnets: Private IP ranges to skip
- RemoteAddrHeadersForce: Force using headers even for private IPs
Best Practices:
- Never trust client IPs for security decisions without additional validation
- Use rate limiting by IP with caution (can be bypassed)
- Log IPs for audit purposes but don't rely solely on them.
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("the_cookie_name", iris.CookieCleanPath)
If you intend to remove a cookie with a specific domain and value, please ensure to pass these values explicitly:
ctx.RemoveCookie("the_cookie_name", iris.CookieDomain("example.com"), iris.CookiePath("/"))
OR use a Cookie value instead:
ctx.RemoveCookie("the_cookie_name", iris.CookieOverride(&http.Cookie{Domain: "example.com", Path: "/"}))
func (*Context) Render ¶
Render writes the response headers and calls the given renderer "r" to render data.
See `RenderResponse` and `RenderComponent` too.
func (*Context) RenderComponent ¶
RenderComponent renders a component to the client. It sets the "Content-Type" header to "text/html; charset=utf-8". It reports any component render errors back to the caller. Set Options.Context.ErrorHandler (or iris.WithErrorHandler for a per-request override) to replace the default 500 error response.
See `RenderResponse` and `Render` too.
func (*Context) RenderResponse ¶
func (ctx *Context) RenderResponse(statusCode int, r ResponseRenderer) error
RenderResponse writes the given status code and calls the given renderer "r" to render data. On 1xx, 204 and 304 responses only the content type is written, without a body. This method can be used while migrating from other frameworks.
See `RenderComponent` and `Render` too.
func (*Context) RequestValue ¶
RequestValue returns any cached value of the "iris.rest.request" key from the Iris Context.
func (*Context) ResponseContentType ¶
func (ctx *Context) ResponseContentType() ContentType
ResponseContentType returns the response writer's header value of "Content-Type". The request's content type is read through Context.ContentType instead.
func (*Context) ResponseHeader ¶
ResponseHeader returns the response writer's header value of the given "name", i.e. a header this handler has already set through SetHeader. If more than one header value found, it returns them joined by comma and space.
The request's headers are read through Context.Header instead:
apiKey := ctx.Header("X-API-Key") // request (what the client sent)
cached := ctx.ResponseHeader("X-Cache") // response (what this handler set)
func (*Context) ResponseMediaType ¶
ResponseMediaType returns the media type of the response writer's header value of "Content-Type". The request's media type is read through Context.MediaType instead.
func (*Context) ResponseWriter ¶
func (ctx *Context) ResponseWriter() ResponseWriter
ResponseWriter returns an http.ResponseWriter compatible response writer, as expected.
func (*Context) ResumeExecution ¶
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) RunReleaseHooks ¶
func (ctx *Context) RunReleaseHooks()
RunReleaseHooks runs and drops the OnRelease callbacks, most recent first. A hook registered by a running hook runs in the same call, so a stream that closes a coalescer at release can register the coalescer's own cleanup. The number of passes is bounded (see maxReleaseHookPasses); a hook that keeps registering itself is dropped after that, with a debug log line.
The router calls it after the handler chain has returned and before it releases the response writer and the Context; a host that acquires Contexts from the Pool itself must do the same, or a hook registered by one request runs for the next one. It is a no-op on a Context that Pool.ForceRelease has already recycled, because ForceRelease drops the hooks.
func (*Context) SaveFormFile ¶
SaveFormFile saves a result of `FormFile` to the "dest" disk full path (directory + filename).
SECURITY: "dest" is passed to os.Create as given. Building it from the client's FileHeader.Filename writes wherever that name points, so run the name through SafeFilename first:
destPath, _, ok, err := context.SafeFilename(uploadDir, fh.Filename)
if err != nil || !ok {
return // the name was rejected.
}
n, err := ctx.SaveFormFile(fh, destPath)
Context.UploadFormFiles does this for you.
See `FormFile` and `UploadFormFiles` too.
func (*Context) SendFile ¶
SendFile sends a file as an attachment, that is downloaded and saved locally from client.
"src" is the path on the server, "destName" the name the client is told to save it as; an empty destName falls back to filepath.Base(src). The name goes through MakeDisposition, which encodes it per RFC 6266 so that a non-ASCII or quote-bearing name cannot break out of the Content-Disposition header.
SECURITY: "src" is not sanitized. Joining a request value into it serves any file the process can read. Use SafeFilename, or serve through the fileserver controller, which confines reads to one root.
See `SendFileWithRate` to throttle the transfer.
func (*Context) SendFileWithRate ¶
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.
func (*Context) ServeContentWithRate ¶
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.
func (*Context) ServeFileWithRate ¶
ServeFileWithRate same as `ServeFile` but it can throttle the speed of reading and though writing the file to the client.
func (*Context) SetContentType ¶
func (ctx *Context) SetContentType(rawContentType string, opts ...ContentTypeOption) error
SetContentType sets the Content-Type header of the response. If a previous call of SetContentType with the Once option was made, it will not be set again. If options are provided and the rawContentType is not a valid Content-Type header value, an error is returned; without options the value is written as-is, the rawContentType is used to determine the charset parameter too and the returned error is always nil.
See `ContentTypeOption` for available options.
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". Options registered for the whole request through Context.AddCookieOptions apply as well, and the ones passed here run last.
SetCookie replaces, like Context.SetHeader: if the response already carries a Set-Cookie line with the same name, path and domain, that line is replaced in place; a cookie with a different path or domain is added as a new line.
The cookie is written as given: unlike Context.AddCookie, SetCookie sets no defaults. Set the security attributes yourself on anything that identifies a session:
ctx.SetCookie(&http.Cookie{
Name: "session",
Value: id,
Path: "/",
HttpOnly: true, // not readable from JavaScript
Secure: true, // HTTPS only
SameSite: http.SameSiteLaxMode, // not sent on cross-site POSTs
})
See Context.RemoveCookie to delete one, and note that it must be given the same Path and Domain or the browser keeps the original.
func (*Context) SetCurrentRoute ¶
func (ctx *Context) SetCurrentRoute(route RouteReadOnly)
SetCurrentRoute sets the route internally, See `CurrentRoute()` method too. It's being initialized by the Router, do not call it. See the `SetHandlers` and `AddHandler` methods to simulate a request.
func (*Context) SetErr ¶
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 `Router.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 ¶
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 `ErrPublic` too.
func (*Context) SetHandlers ¶
SetHandlers replaces all handlers with the new.
func (*Context) SetHeader ¶
SetHeader sets a header on the response, replacing any value already set for that name. If value is empty it removes the header.
A middleware registered twice (say on UseRouter and again on a router) therefore cannot emit a duplicate single-valued header such as Access-Control-Allow-Origin, which browsers reject outright.
See `AddHeader` for list-valued headers such as Vary.
func (*Context) SetID ¶
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 `ID` and `middleware/requestid` too.
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 ¶
func (ctx *Context) SetLogoutFunc(fn LogoutHandler)
SetLogoutFunc registers a custom logout handler 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.
See `Logout` method too.
func (*Context) SetRequest ¶
SetRequest sets the Context's Request, It is useful to store the new request created by a std *http.Request#WithContext() into Iris' Context. Use `SetRequest` 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.SetRequest(r.WithContext(stdCtx)).
func (*Context) SetResponseWriter ¶
func (ctx *Context) SetResponseWriter(newResponseWriter ResponseWriter)
SetResponseWriter 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) SetUser ¶
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]any.
- 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) ShuttingDown ¶
func (ctx *Context) ShuttingDown() <-chan struct{}
ShuttingDown returns a channel that is closed when the server begins a graceful shutdown.
It is deliberately a separate signal from cancellation. A draining stream still needs to write its terminal frame, so the request context stays live; select on both.
for {
select {
case <-ctx.ShuttingDown():
return // the server is going away: finish cleanly.
case <-ctx.Done():
return // the client is gone.
case ev := <-events:
// ...
}
}
Without it a handler blocked in a stream loop is never told that the process is stopping: net/http cancels a request context on client disconnect, on an HTTP/2 stream reset and when ServeHTTP returns, and shutdown is none of those. http.Server.Shutdown then waits for a handler that cannot know it should stop.
It returns a nil channel, which blocks forever, when the request did not come from a server that Iris started. That is the correct answer for a handler running under httptest or under another host: there is no shutdown to observe.
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) StatusCode ¶
StatusCode sets the status code header to the response. Look .GetStatusCode too, and `Application#HandleNoRoute`, `Application#HandleNoMethod` for handling the 404 and 405 failure codes.
Note that you must set status code before write response body (except when recorder is used).
func (*Context) StdContext ¶
StdContext returns the request's standard library context: the one net/http created for this request, carrying its deadline and its cancellation on client disconnect or request completion.
Pass this, not the Iris Context itself, to any API that takes a context.Context and may hold on to it past the handler's return: HTTP clients (the transport keeps the context for cancel propagation after the response is delivered), database drivers, spawned goroutines. The Iris Context also implements context.Context, but it is pooled and reused across requests; a consumer that touches it after the handler returned races with the pool's release of it. The returned standard context is safe to keep.
For work that must survive the request's cancellation, use WithoutCancel instead.
Shortcut of Request().Context().
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 ¶
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). An error is private when it is an ErrPrivate or wraps one anywhere in its chain: PrivateError(err), PrivateErrorf(err) (rest/errors.Private) and a private error wrapped again with fmt.Errorf("...: %w", err) all count.
func (*Context) StopWithJSON ¶
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.
When a body has already been written the status went out with it, so StopWithJSON only stops the chain and returns nil: appending a JSON document to a committed body would corrupt the response the client is reading.
func (*Context) StopWithPlainError ¶
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) StopWithStatus ¶
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 ¶
StopWithText stops the handlers chain and writes the "statusCode" among with a text.
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.
The writer is called repeatedly until it returns an error. io.EOF is the sentinel for normal completion: there is no other way to end the loop, so a writer that has nothing more to send returns it and StreamWriter passes it back unchanged. Any other error ends the stream and is returned as-is, and a client that disconnects ends it with the request context's error.
This function may be used in the following cases:
- if response body is too big (more than bodylimit.New(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`).
For Server-Sent Events prefer the sse package. This is a poll loop, which suits a writer that blocks until it has something (a ticker, a queue read), and fits badly when events arrive from a producer goroutine: sse.Stream is a push API, and it also handles the response-writer buffering, write deadlines, heartbeats and framing that an event stream needs.
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.
The address and the URI are client-controlled, so newlines and other control characters are stripped: this value is written to logs, where an unescaped newline would let a caller forge log entries.
func (*Context) Text ¶
Text writes out a string as plain text. It returns any write error; see `WriteString` for the byte count.
func (*Context) TextYAML ¶
TextYAML calls the Context.YAML method but with the text/yaml content type instead.
func (*Context) UnmarshalBody ¶
func (ctx *Context) UnmarshalBody(outPtr any, 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) UploadFormFiles ¶
func (ctx *Context) UploadFormFiles(destDirectory string, before ...func(*Context, *multipart.FileHeader) bool) (uploaded []*multipart.FileHeader, n int64, err error)
UploadFormFiles uploads files to the specified directory.
Every filename goes through SafeFilename first. A name that does not survive it is SKIPPED, not saved, and no error is reported for it: compare the returned "uploaded" slice against the files you expected when that matters. The rules are:
- The name must match ValidFilenameRegexp (alphanumeric plus ._-), so a name carrying a path separator, a space or a colon is out.
- Directory traversal is stripped, and the destination directory is resolved through its symlinks before the join, so neither "../" nor a symlinked upload directory escapes it.
- A name that is only dots (".", "..") is rejected.
- Reserved Windows device names are rejected (CON, PRN, AUX, NUL, COM0-9, LPT0-9, with or without an extension). This applies on every platform, so an upload set behaves the same whatever the server runs on.
What it does NOT do, and you may still want:
- Cap the upload size. PostMaxMemory bounds multipart parsing (32MB by default), BodyMaxMemory bounds the whole body, and the bodylimit middleware bounds it per route.
- Rate-limit the endpoint, scan the content, or check that the bytes match the extension. A name ending in .jpg proves nothing about the file.
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 `PostMaxMemory` setting or by the `bodylimit` 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/main/_examples/04-request/uploads
func (*Context) User ¶
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.
SECURITY: do not write the returned value to the response. A User carries the credentials it authenticated with: SimpleUser has a Password and a Token field, and a value wrapped by SetUser is serialized whole. Either way ctx.JSON(ctx.User()) returns those to the caller. Pick the fields you mean to expose:
u := ctx.User()
id, _ := u.GetID()
username, _ := u.GetUsername()
ctx.JSON(iris.Map{"id": id, "username": username})
See `SetUser` too.
func (*Context) Value ¶
Value returns the value associated with this context for key, or nil if no value is associated with key. Successive calls to Value with the same key returns the same result.
For a string key it first looks the key up in the Context.Values() store and returns that entry when it exists, otherwise it falls back to Request().Context().Value(key).
func (*Context) ValueAs ¶
ValueAs returns any cached value of the given key from the Iris Context, type-asserted to T. It reports whether the value was found and of type T.
func (*Context) Values ¶
func (ctx *Context) Values() *encoding.ContextValues
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) WithoutCancel ¶
WithoutCancel returns a standard context derived from the request's context that is never canceled when the client disconnects or the request finishes, while its values are preserved (standard context.WithoutCancel semantics). Use it for must-finish work spawned from a handler:
go persist(ctx.WithoutCancel(), record)
Do not retain the Iris Context itself past the handler: it is pooled and reused across requests; the returned standard context is safe to keep.
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.
It reports any write errors back to the caller, Application.SetContentErrorHandler does NOT apply here as this is a lower-level method which must be remain as it is.
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 and the content length headers are removed before the response sent, and that the "Last-Modified" one is removed as well when an "ETag" is present (RFC 7232 section 4.1). The "ETag" itself is kept.
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.
func (*Context) XML ¶
XML marshals the given interface object and writes the XML response to the client. To render maps as XML see the `XMLMap` package-level function.
It reports any XML parser or write errors back to the caller. Set Options.Context.ErrorHandler (or iris.WithErrorHandler for a per-request override) to replace the default 500 error response.
func (*Context) YAML ¶
YAML marshals the given "v" value using the yaml marshaler and writes the result to the client.
It reports any YAML parser or write errors back to the caller. Set Options.Context.ErrorHandler (or iris.WithErrorHandler for a per-request override) to replace the default 500 error response.
type ContextOptions ¶
type ContextOptions struct {
// URLParamSeparator sets the separator used to split the multi-value entries of
// Context.Query, Context.Form and Context.PostForm (e.g. Query().GetSlice).
// If not set, parameters with comma-separated values are treated as a single value.
// Defaults to Comma (",").
URLParamSeparator string `ini:"url_param_separator" json:"url_param_separator,omitempty" yaml:"URLParamSeparator" toml:"URLParamSeparator"`
// FireEmptyFormError, when true, causes `context.ReadForm/ReadQuery/ReadBody` to return `iris.ErrEmptyForm` on empty form data.
// Defaults to false.
FireEmptyFormError bool `ini:"fire_empty_form_error" json:"fire_empty_form_error,omitzero" yaml:"FireEmptyFormError" toml:"FireEmptyFormError"`
// TimeFormat specifies the time format for datetime parsing.
// Defaults to "Mon, 02 Jan 2006 15:04:05 GMT". Used in Context.CheckIfModifiedSince.
TimeFormat string `ini:"time_format" json:"time_format,omitempty" yaml:"TimeFormat" toml:"TimeFormat"`
// PostMaxMemory defines the maximum size of post data a client can send, separate from the overall request body limit.
// Defaults to 32MB (32 << 20).
PostMaxMemory int64 `ini:"post_max_memory" json:"post_max_memory,omitzero" yaml:"PostMaxMemory" toml:"PostMaxMemory"`
// BodyMaxMemory limits the total number of bytes read from a request body by
// Body, ReadJSON, ReadJSONStream and ReadMultipartRelated (and therefore by
// the readers built on them, such as ReadXML/ReadYAML/ReadBody and
// ctx.BindJSON). Reading past it fails with
// ErrRequestEntityTooLarge, which the rest/errors package maps to 413.
//
// It is separate from PostMaxMemory, which only bounds multipart form parsing.
// A value of 0 (the default) means no limit, preserving prior behavior; set it
// to opt into protection against large-body and decompression-bomb denial of
// service. For per-route control use the bodylimit middleware instead.
BodyMaxMemory int64 `ini:"body_max_memory" json:"body_max_memory,omitzero" yaml:"BodyMaxMemory" toml:"BodyMaxMemory"`
// RemoteAddrHeaders specifies the request header names that can be used to determine the client's IP address.
// By default, no "X-" headers are considered safe. Use behind proxies or with trusted services like Cloudflare.
// Defaults to empty slice.
RemoteAddrHeaders []string `ini:"remote_addr_headers" json:"remote_addr_headers,omitempty" yaml:"RemoteAddrHeaders" toml:"RemoteAddrHeaders"`
// RemoteAddrHeadersForce overrides the default behavior of `Context.RemoteAddr()` to use the first entry
// from a request header as the client's IP, even if it's within the `RemoteAddrPrivateSubnets`.
// Defaults to false.
RemoteAddrHeadersForce bool `` /* 133-byte string literal not displayed */
// RemoteAddrPrivateSubnets lists the IP ranges considered as private subnets.
// These ranges are checked against IPs obtained from `RemoteAddrHeaders` or `Context.Request.RemoteAddr`.
// Defaults to specified ranges covering common private subnets.
RemoteAddrPrivateSubnets []netutil.IPRange `` /* 142-byte string literal not displayed */
// SSLProxyHeaders specifies headers that indicate a valid HTTPS request.
// Refer to `Context.IsSSL()` for usage.
// Defaults to empty map.
SSLProxyHeaders map[string]string `ini:"ssl_proxy_headers" json:"ssl_proxy_headers,omitempty" yaml:"SSLProxyHeaders" toml:"SSLProxyHeaders"`
// HostProxyHeaders lists headers that may contain a proxied hostname value.
// Refer to `Context.Host()` for usage.
// Defaults to empty map.
HostProxyHeaders map[string]bool `ini:"host_proxy_headers" json:"host_proxy_headers,omitempty" yaml:"HostProxyHeaders" toml:"HostProxyHeaders"`
// Validator is the request validator for the current context.
// It's been called after the request body was decoded to a given struct value on
// ReadValues, ReadHeader, UnmarshalBody, ReadJSON, ReadMsgPack, ReadForm, ReadParams, ReadURL and ReadQuery.
// Defaults to nil.
RequestValidator Validator `ini:"-" json:"-" yaml:"-" toml:"-"`
// Charset sets the character encoding for rendering, used in templates and other responses.
// Defaults to "utf-8".
Charset string `ini:"charset" json:"charset,omitempty" yaml:"Charset" toml:"Charset"`
// ErrorHandler is the handler for errors that occur during writes through
// Render, RenderComponent, JSON, JSONP, XML, Markdown, YAML, Protobuf and MsgPack methods.
ErrorHandler ErrorHandler `ini:"-" json:"-" yaml:"-" toml:"-"`
// DisableErrorHandler, when true, disables the error handler completely.
DisableErrorHandler bool `ini:"disable_error_handler" json:"disable_error_handler,omitzero" yaml:"DisableErrorHandler" toml:"DisableErrorHandler"`
// Objects holds other object options given by the end-developer.
// The key is the name of the object and the value is the pointer to the object.
Objects map[string]any `ini:"-" json:"-" yaml:"-" toml:"-"`
}
ContextOptions contains the request and response options for the current context.
func DefaultContextOptions ¶
func DefaultContextOptions() ContextOptions
DefaultContextOptions returns the default values of ContextOptions instance.
func (*ContextOptions) Clone ¶
func (o *ContextOptions) Clone() *ContextOptions
Clone returns a deep copy of the ContextOptions.
func (*ContextOptions) CopyFrom ¶
func (o *ContextOptions) CopyFrom(from *ContextOptions)
CopyFrom copies the values from the "from" ContextOptions to the current ContextOptions.
func (*ContextOptions) CopyTo ¶
func (o *ContextOptions) CopyTo(to *ContextOptions)
CopyTo writes a deep copy of the ContextOptions into "to", replacing its contents. See Clone for a copy that is returned instead.
func (*ContextOptions) Equal ¶
func (o *ContextOptions) Equal(other *ContextOptions) bool
Equal reports whether the ContextOptions and the other ContextOptions are equal.
func (*ContextOptions) FillZero ¶
func (o *ContextOptions) FillZero(from ContextOptions)
FillZero fills every unset (zero) field of o from "from". A non-nil empty slice or map is an explicit "none" and is kept as-is; boolean fields default to false and are never touched. A scalar whose zero value is meaningful cannot be distinguished from unset here; force a zero value per request through a middleware instead:
app.Use(func(ctx *Context) { ctx.Options().URLParamSeparator = ""; ctx.Next() })
func (*ContextOptions) Get ¶
func (opts *ContextOptions) Get(objectKey string) any
Get returns the object from the context options's holded objects based on the given key.
func (*ContextOptions) HandleError ¶
func (opts *ContextOptions) HandleError(ctx *Context, err error)
HandleError handles the error for the current context.
func (*ContextOptions) MimeToContentType ¶
func (opts *ContextOptions) MimeToContentType(mime string) string
MimeToContentType returns the media type and charset as content-type based on the given mime type, helps with reducing time to resolve a simple content type.
func (*ContextOptions) Set ¶
func (opts *ContextOptions) Set(objectKey string, objectValue any)
Set sets a new object to the context options's holded objects.
func (*ContextOptions) Validate ¶
func (opts *ContextOptions) Validate(ptr any) error
Validate validates the given struct value using the request validator for the current context.
type ContextPool ¶
type ContextPool[T any] interface { // Acquire must return a new T from a pool. Acquire(ctx *Context) T // Release must put the T back to the pool. Release(T) }
ContextPool is a pool of T. It's used to acquire and release custom context. Use of custom implementation or `NewContextPool`.
See `NewContextWrapper` and `NewContextPool` for more.
func NewContextPool ¶
func NewContextPool[T any, contextPtr ContextSetterPtr[T]]() ContextPool[contextPtr]
NewContextPool returns a new ContextPool default implementation which uses sync.Pool to implement its Acquire and Release methods. The contextPtr is acquired from the sync pool and released back to the sync pool after the handler's execution. The contextPtr is passed to the handler as an argument. ThecontextPtr is not shared between requests. The contextPtr must implement the `ContextSetter` interface. The T must be a struct. The contextPtr must be a pointer of T.
Example: w := context.NewContextWrapper(context.NewContextPool[myCustomContext]())
type ContextSetter ¶
type ContextSetter interface {
// SetContext sets the iris.Context to the struct.
SetContext(*Context)
}
ContextSetter is an interface which can be implemented by a struct to set the iris.Context to the struct. The receiver must be a pointer of the struct.
type ContextSetterPtr ¶
type ContextSetterPtr[T any] interface { *T ContextSetter }
ContextSetterPtr is a pointer of T which implements the `ContextSetter` interface. The T must be a struct.
type ContextWrapper ¶
type ContextWrapper[T any] struct { // contains filtered or unexported fields }
ContextWrapper is a wrapper for handlers which expect a T instead of Iris Context.
See the `NewContextWrapper` function for more.
func NewContextWrapper ¶
func NewContextWrapper[T any, contextPtr ContextSetterPtr[T]]() *ContextWrapper[contextPtr]
NewContextWrapper returns a new ContextWrapper. It uses the default pool. The default pool's Acquire returns a T from a sync.Pool and sets the iris Context to it. The default pool's Release zeroes the T before it puts it back to the sync.Pool, so per-request fields never leak into the next request.
Usage:
Initialize a new context wrapper using the default pool, where the myCustomContext SHOULD implement the `SetContext(ctx iris.Context)` method.
w := context.NewContextWrapper[myCustomContext]()
Use it to wrap the handlers.
app.Get("/", w.Handler(index))
See the `NewContextWrapperWithPool` for more.
func NewContextWrapperWithPool ¶
func NewContextWrapperWithPool[T any](pool ContextPool[T]) *ContextWrapper[T]
NewContextWrapperWithPool returns a new ContextWrapper. The "pool" must not be nil, this function panics if it is. Use the `NewContextPool[T, contextPtr]()` to pass the default sync.Pool-backed implementation, or the `NewContextWrapper[T]()` which builds it for you. Then, use the `Handler` method to wrap custom handlers to iris ones.
Create the context sync pool for our custom context, the pool must implement Acquire() T and Release(T) methods to satisfy the ContextPool interface.
Usage:
type myCustomContextPool struct {
pool sync.Pool
}
Acquire returns a new custom context from the pool.
func (p *myCustomContextPool) Acquire(ctx iris.Context) *myCustomContext {
v := p.pool.Get()
if v == nil {
v = &myCustomContext{
Context: ctx,
// custom fields here...
}
}
return v.(*myCustomContext)
}
Release puts a custom context back to the pool.
func (p *myCustomContextPool) Release(t *myCustomContext) {
// You can take advantage of this method to clear the context
// and re-use it on the Acquire method, use the sync.Pool.
p.pool.Put(t)
}
Declare a custom context.
type myCustomContext struct {
// It's just an embedded field which is set on AcquireFunc,
// so you can use myCustomContext with the same methods as iris.Context,
// override existing iris.Context's methods or add custom methods.
// You can use the `Context` field to access the original context.
iris.Context
}
func (c *myCustomContext) MyCustomMethod() {
// custom method here...
}
Initialize a new context wrapper.
w := context.NewContextWrapperWithPool(&myCustomContextPool{})
OR initialize a new context wrapper using the default pool, where the myCustomContext SHOULD implement the `SetContext(ctx iris.Context)` method.
w := context.NewContextWrapper[myCustomContext]()
Use it to wrap the handlers.
app.Get("/", w.Handler(index))
func (*ContextWrapper[T]) Filter ¶
func (w *ContextWrapper[T]) Filter(handler func(T) bool) Filter
Filter same as `Handler` but it converts a handler to Filter.
func (*ContextWrapper[T]) Handler ¶
func (w *ContextWrapper[T]) Handler(handler func(T)) Handler
Handler wraps the handler with the pool's Acquire and Release methods. It returns a new handler which expects a T instead of iris.Context. The T is the type of the pool. The T is acquired from the pool and released back to the pool after the handler's execution. The T is passed to the handler as an argument. The T is not shared between requests.
func (*ContextWrapper[T]) HandlerReturnDuration ¶
func (w *ContextWrapper[T]) HandlerReturnDuration(handler func(T) time.Duration) func(*Context) time.Duration
HandlerReturnDuration same as `Handler` but it converts a handler which returns a time.Duration.
func (*ContextWrapper[T]) HandlerReturnError ¶
func (w *ContextWrapper[T]) HandlerReturnError(handler func(T) error) func(*Context) error
HandlerReturnError same as `Handler` but it converts a handler which returns an error.
func (*ContextWrapper[T]) Handlers ¶
func (w *ContextWrapper[T]) Handlers(handlers ...func(T)) Handlers
Handlers wraps the handlers with the pool's Acquire and Release methods.
func (*ContextWrapper[T]) Pool ¶
func (w *ContextWrapper[T]) Pool() ContextPool[T]
Pool returns the pool, useful when manually Acquire and Release of custom context is required.
type CookieOption ¶
CookieOption is the type of function that is accepted on context's methods like `AddCookie`, `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 ¶
func CookieAllowReclaim(cookieNames ...string) CookieOption
CookieAllowReclaim accepts the Context itself. If set it will add the cookie to (on `SetCookie`, `AddCookie`) or remove the cookie from (on `RemoveCookie`) the Request object too.
func CookieAllowSubdomains ¶
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 CookieDomain ¶
func CookieDomain(domain string) CookieOption
CookieDomain is a CookieOption which sets the cookie's Domain field. If empty then the current domain is used.
Usage: ctx.RemoveCookie("the_cookie_name", iris.CookieDomain("example.com"))
func CookieEncoding ¶
func CookieEncoding(encoding SecureCookie, cookieNames ...string) CookieOption
CookieEncoding accepts a value which implements `Encode` and `Decode` methods. It calls its `Encode` on `Context.SetCookie` and `AddCookie` methods. And on `Context.Cookie` and `Context.CookieValue` methods 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".
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 `AddCookie`. See `CookieSecure` too.
func CookieOverride ¶
func CookieOverride(cookie *http.Cookie) CookieOption
CookieOverride is a CookieOption which overrides the cookie explicitly to the given "cookie".
Usage: ctx.RemoveCookie("the_cookie_name", iris.CookieOverride(&http.Cookie{Domain: "example.com"}))
func CookiePath ¶
func CookiePath(path string) CookieOption
CookiePath is a `CookieOption`. Use it to change the cookie's Path field.
func CookieSameSite ¶
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 CountResponse ¶
type CountResponse[N CountType] = pagination.CountResponse[N]
CountResponse is an alias of pagination.CountResponse.
type CountType ¶
type CountType = pagination.CountType
CountType is an alias of pagination.CountType.
type DecodeFunc ¶
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.
A decode error ends the stream even when the callback returns nil: the decoder is not positioned at the next value after a failure, so ReadJSONStream returns that error itself instead of reading on. Look the `Context.ReadJSONStream` method.
type DefaultResponseWriter ¶
type DefaultResponseWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
DefaultResponseWriter is the default response writer, it writes directly to the standard http.ResponseWriter.
func AcquireResponseWriter ¶
func AcquireResponseWriter(w http.ResponseWriter) *DefaultResponseWriter
AcquireResponseWriter returns a new *DefaultResponseWriter from the pool. Releasing is done automatically when request and response is done.
func (*DefaultResponseWriter) Clone ¶
func (w *DefaultResponseWriter) Clone() ResponseWriter
Clone returns a copy of this response writer, carrying over the status code and the number of bytes written so far.
The copy wraps the same underlying http.ResponseWriter, so it is a second handle on one connection rather than an independent response: writing to both interleaves their output, and neither is usable once the server has finished the request. Clone exists so a handler can hand a writer to a goroutine that outlives the handler; that goroutine must check Context.IsCanceled first.
func (*DefaultResponseWriter) Flush ¶
func (w *DefaultResponseWriter) Flush()
Flush sends any buffered data to the client.
Use FlushError when the result matters, which on a long-lived response it does: a failing flush is the earliest sign that the client has gone.
func (*DefaultResponseWriter) FlushError ¶
func (w *DefaultResponseWriter) FlushError() error
FlushError sends any buffered data to the client and reports whether it reached the transport. It writes the status code first, exactly as Flush does.
It follows the same preference order as http.ResponseController.Flush - a FlushError method, then http.Flusher, then one step down the Unwrap chain - without allocating a controller for every event of a stream. It returns an error matching errors.ErrUnsupported when nothing in the chain can flush, which is what happens under http.TimeoutHandler.
func (*DefaultResponseWriter) Flusher ¶
func (w *DefaultResponseWriter) Flusher() (http.Flusher, bool)
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.
func (*DefaultResponseWriter) Hijack ¶
func (w *DefaultResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack lets the caller take over the connection. After a call to Hijack(), the HTTP server library will not do anything else with the connection.
It becomes the caller's responsibility to manage and close the connection.
The returned net.Conn may have read or write deadlines already set, depending on the configuration of the Server. It is the caller's responsibility to set or clear those deadlines as needed.
func (*DefaultResponseWriter) IsHijacked ¶
func (w *DefaultResponseWriter) IsHijacked() bool
IsHijacked reports whether this response writer's connection is hijacked.
func (*DefaultResponseWriter) StatusCode ¶
func (w *DefaultResponseWriter) StatusCode() int
StatusCode returns the status code header value
func (*DefaultResponseWriter) Unwrap ¶
func (w *DefaultResponseWriter) Unwrap() http.ResponseWriter
Unwrap returns the simple, underlying and original http.ResponseWriter that backends this response writer.
func (*DefaultResponseWriter) Write ¶
func (w *DefaultResponseWriter) Write(contents []byte) (int, error)
Write writes to the client 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 (*DefaultResponseWriter) WriteHeader ¶
func (w *DefaultResponseWriter) WriteHeader(statusCode int)
WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.
A status code outside the valid 100-999 range is ignored, leaving the previous one in place. net/http panics on such a value, and it reaches here unchecked from Context.StatusCode, which handlers do call with numbers derived from user input or from an upstream response.
func (*DefaultResponseWriter) Written ¶
func (w *DefaultResponseWriter) Written() 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 were 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.
type ErrPanicRecovery ¶
type ErrPanicRecovery struct {
ErrPrivate
Cause any
Callers []string // file:line callers.
Stack []byte // the full debug stack.
RegisteredHandlers []string // file:line of all registered handlers.
CurrentHandlerFileLine string // the handler panic came from.
CurrentHandlerName string // the handler name panic came from.
Request string // the http dumped request.
}
ErrPanicRecovery may be returned from `Context` actions of a `Handler` which recovers from a manual panic.
func IsErrPanicRecovery ¶
func IsErrPanicRecovery(err error) (*ErrPanicRecovery, bool)
IsErrPanicRecovery reports whether the given "err" is a type of ErrPanicRecovery.
func (*ErrPanicRecovery) Error ¶
func (e *ErrPanicRecovery) Error() string
Error implements the Go standard error type.
It reports the cause and the callers but not the dumped request. This error is private (see ErrPrivate) so the default renderer never sends it to a client, but a custom error handler that formats it would otherwise put the request's headers in the response. Use LogMessage for the full form.
func (*ErrPanicRecovery) Is ¶
func (e *ErrPanicRecovery) Is(err error) bool
Is completes the internal errors.Is interface.
func (*ErrPanicRecovery) LogMessage ¶
func (e *ErrPanicRecovery) LogMessage() string
type ErrPrivate ¶
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 ¶
func PrivateError(err error) ErrPrivate
PrivateError accepts an error and returns an `ErrPrivate` by wrapping the given "err" with the internal privateError struct.
type ErrorHandler ¶
ErrorHandler describes a context error handler which applies on Render, RenderComponent, JSON, JSONP, XML, Markdown, YAML, Protobuf and MsgPack writes.
It does NOT modify or handle the result of Context.GetErr at all, use a custom middleware instead if you want to handle the handler-provided custom errors (Context.SetErr)
An ErrorHandler is registered through Options.Context.ErrorHandler (or per request via iris.WithErrorHandler) to override the default behavior, which is to send an internal server error status code without a body back to the client.
var DefaultErrorHandler ErrorHandler = func(ctx *Context, err error) { if ctx.IsDebug() { ctx.app.Logger().Error(err) } ctx.StopWithPlainError(http.StatusInternalServerError, err) }
DefaultErrorHandler is the default error handler for Render, RenderComponent, JSON, JSONP, XML, Markdown, YAML, Protobuf and MsgPack write methods.
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 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 FromStd ¶
FromStd converts native http.Handler & http.HandlerFunc to Handler.
The standard handler reads the route parameters with r.PathValue and the matched route template, for example "/users/{id:uuid}", with r.Pattern.
Under rest/errors.Handler, which iris.NewBuilder registers, a failure status the standard handler sets with no body is rendered as the JSON envelope unless the handler writes, flushes or declares a Content-Length.
Supported form types:
.FromStd(h http.Handler)
.FromStd(h func(w http.ResponseWriter, r *http.Request) {...})
.FromStd(h func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {...})
func FromStdWithNext ¶
func FromStdWithNext(h func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) Handler
FromStdWithNext receives a standard handler - middleware form - and returns a compatible Handler wrapper.
LIMITATION: only the request the middleware passes to "next" is adopted, not the response writer. A standard middleware that works by wrapping the writer, such as output escaping, CSP header injection, compression or a response size limit, has no effect here. It fails silently too: the middleware still runs and still looks installed. Wrap the whole router with Application.WrapRouter instead, which keeps the writer the middleware hands down.
Middleware that only reads the request, sets headers or short-circuits by not calling "next" converts correctly.
func JoinHandlersAsMiddleware ¶
JoinHandlersAsMiddleware converts a slice of Handlers to a single Handler which can be registered as a middleware. If all given handlers are nil, then it returns a nil Handler.
func JoinHandlersAsOneHandler ¶
JoinHandlersAsOneHandler converts a slice of Handlers to a single Handler.
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/06-middleware/conditional.
func TryFromStd ¶
TryFromStd converts native http.Handler & http.HandlerFunc to Handler. It returns an error if the conversion is not possible.
Supported form types:
.TryFromStd(h http.Handler)
.TryFromStd(h func(w http.ResponseWriter, r *http.Request) {...})
.TryFromStd(h func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {...})
type HandlerList ¶
HandlerList is a type of funcer.List[Handler]. It is an optimal type of list of handlers.
Usage:
handlers := context.NewHandlerList() handlers.Append/Prepend/AppendAfter/PrependBefore(...) and e.t.c.
func NewHandlerList ¶
func NewHandlerList(handlers ...Handler) *HandlerList
NewHandlerList returns a new HandlerList.
type Handlers ¶
type Handlers = []Handler
Handlers is just a type of slice of []Handler.
See `Handler` for more.
func ConcatHandlers ¶
ConcatHandlers returns a copy of given Handlers chains slice joined as one slice of Handlers.
func CopyHandlers ¶
CopyHandlers returns a copy of "handlers" Handlers slice.
func JoinHandlers ¶
JoinHandlers returns a copy of given Handlers slice joined as one slice of Handlers.
func UniqueHandlers ¶
UniqueHandlers returns a new slice of Handlers which does not contain any handler that exists in the "h2" Handlers slice.
Every occurrence is removed, not just the first, and "h1" itself is left untouched. That matters when "h1" is a route's registered Handlers, which every request for that route shares.
Only trusted names are excluded: an anonymous compiler-generated name is not a safe identity since Go 1.27 (distinct code-identical literals may share a code pointer), so matching on it could remove an unrelated handler.
func UpsertHandlers ¶
UpsertHandlers returns a new slice holding "h1" with "h2" merged into it: a handler of "h2" whose name matches one in "h1" replaces it in place, otherwise it is appended.
Only trusted names take the replace path: anonymous compiler-generated names (".funcN", "-fm") are not a safe identity since Go 1.27, where two distinct code-identical literals may share a code pointer — an unnamed closure is therefore always appended, never merged over an existing one. Name a middleware (SetHandlerName) to opt into replace semantics.
Neither input slice is modified. That matters when "h1" is a route's registered Handlers, which every request for that route shares.
type IDPayload ¶
type IDPayload[T IDType] struct { ID T `json:"id"` }
IDPayload is a simple struct which describes a json id value: the {"id": ...} body Created renders for a bare identifier.
type IDType ¶
IDType is a type which can be used as an unique identifier for a resource. It can be a string or int or int64 or uint64 or the standard library's uuid.UUID. Created wraps a response value of one of these types as an IDPayload.
type ItemsCollectorFunc ¶
type ItemsCollectorFunc[Filter any, Item any, TotalCount CountType] func(stdContext.Context, PageOptions, Filter) ([]Item, TotalCount, error)
ItemsCollectorFunc is a function that collects items and returns them along with the total count. It's used by the Context.Paginated method to collect items and return them in a paginated response.
type JSON ¶
type JSON struct {
// EscapeHTML escapes <, > and & inside JSON strings as <, >
// and & (the old encoding/json default). Off by default: JSON
// parsers decode both forms identically, responses are served as
// application/json (never inline HTML), and the bytes are smaller.
// JSONP responses always escape, regardless of this option — there the
// payload lands in a script body where "</script>" breakout matters.
EscapeHTML bool
// Indent is the per-level indentation string; empty writes compact JSON.
Indent string
// Prefix is written before the body, e.g. ")]}',\n".
Prefix string
// EscapeNonASCII writes every non-ASCII rune as a \uXXXX escape
// (surrogate pairs above the Basic Multilingual Plane), so the body is
// pure ASCII.
EscapeNonASCII bool
// ArrayPrefix prepends "while(1);" when the top-level value encodes to a
// JSON array. The prefix makes the body a syntax error for a <script>
// tag, which is the classic guard against JSON array hijacking; clients
// strip it before parsing. Objects are never prefixed.
ArrayPrefix bool
// MarshalOptions are appended after the framework defaults
// (deterministic map ordering, invalid UTF-8 allowed on output); later
// options win, so any encoding/json/v2 or jsontext encode behavior can
// be overridden per call.
MarshalOptions []jsonv2.Options
}
JSON contains the options for the JSON (Context's) Renderer.
type JSONReader ¶
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
// CaseSensitive disables the default case-insensitive matching of JSON
// object member names to struct field names for this call, restoring
// encoding/json/v2's strict default. The lenient default exists because
// deployed clients bind under the old encoding/json matching rules.
CaseSensitive bool
// This field only applies to the ReadJSONStream.
// 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
// UnmarshalOptions are appended after the defaults built from the fields
// above; later options win, so any encoding/json/v2 or jsontext decode
// behavior can be overridden per call, e.g.
// jsontext.AllowDuplicateNames(true) to accept duplicate object members.
UnmarshalOptions []jsonv2.Options
}
JSONReader holds the JSON decode options of the `Context.ReadJSON, ReadBody` methods.
type ListFilter ¶
type ListFilter = pagination.ListFilter
ListFilter is an alias of pagination.ListFilter: the request half every list endpoint shares. Embed it in a service's own filter.
type LogoutHandler ¶
LogoutHandler is a function which should be responsible to clear the authentication information of a request.
type Markdown ¶
type Markdown struct {
// content-specific
Sanitize bool
//
// Library-specific.
// E.g. Flags: html.CommonFlags | html.HrefTargetBlank
RenderOptions html.RendererOptions
}
Markdown contains the options for the Markdown (Context's) Renderer.
type MultipartRelated ¶
type MultipartRelated struct {
// ContentIDs keeps an ordered list of all the
// content-ids of the multipart related request.
ContentIDs []string
// Contents keeps each part's information by Content-ID.
// Contents holds each of the multipart/related part's data.
Contents map[string]MultipartRelatedContent
}
MultipartRelated is the result of the context.ReadMultipartRelated method.
type MultipartRelatedContent ¶
type MultipartRelatedContent struct {
// ID holds the Content-ID.
ID string
// Headers holds the part's request headers.
Headers map[string][]string
// Body holds the part's body.
Body []byte
}
MultipartRelatedContent holds a multipart/related part's id, header and body.
type N ¶
type N struct {
Text, HTML string
Markdown []byte
Binary []byte
JSON any
JSONP any
XML any
YAML any
Protobuf any
MsgPack any
Other []byte // custom content types.
}
N is a struct which can be passed on the `Context.Negotiate` method. It contains fields which should be filled based on the `Context.Negotiation()` server side values. If no matched mime then its "Other" field will be sent, which should be a string or []byte. It completes the `ContentSelector` interface.
func (N) SelectContent ¶
SelectContent returns a content based on the matched negotiated "mime".
type NegotiationAcceptBuilder ¶
type NegotiationAcceptBuilder struct {
// contains filtered or unexported fields
}
NegotiationAcceptBuilder builds the accepted mime types and charset
and "Accept-Charset" headers respectfully. The default values are set by the client side, server can append or override those. The end result will be challenged with runtime preffered set of content types and charsets.
See the `Negotiate` method too.
func (*NegotiationAcceptBuilder) Binary ¶
func (n *NegotiationAcceptBuilder) Binary() *NegotiationAcceptBuilder
Binary adds the "application/octet-stream" as accepted client content type. Returns itself.
func (*NegotiationAcceptBuilder) Charset ¶
func (n *NegotiationAcceptBuilder) Charset(charset ...string) *NegotiationAcceptBuilder
Charset adds one or more client accepted charsets. Returns itself.
func (*NegotiationAcceptBuilder) Encoding ¶
func (n *NegotiationAcceptBuilder) Encoding(encoding ...string) *NegotiationAcceptBuilder
Encoding adds one or more client accepted encoding algorithms. Returns itself.
func (*NegotiationAcceptBuilder) EncodingGzip ¶
func (n *NegotiationAcceptBuilder) EncodingGzip() *NegotiationAcceptBuilder
EncodingGzip adds the "gzip" as accepted encoding. Returns itself.
func (*NegotiationAcceptBuilder) HTML ¶
func (n *NegotiationAcceptBuilder) HTML() *NegotiationAcceptBuilder
HTML adds the "text/html" as accepted client content type. Returns itself.
func (*NegotiationAcceptBuilder) JSON ¶
func (n *NegotiationAcceptBuilder) JSON() *NegotiationAcceptBuilder
JSON adds the "application/json" as accepted client content type. Returns itself.
func (*NegotiationAcceptBuilder) JSONP ¶
func (n *NegotiationAcceptBuilder) JSONP() *NegotiationAcceptBuilder
JSONP adds the "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 ¶
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) Protobuf ¶
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 ¶
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.Negotiation` 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 `NegotiationAcceptBuilder`.
See the `Negotiate` method too.
func (*NegotiationBuilder) Any ¶
func (n *NegotiationBuilder) Any(v ...any) *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() (mediaType, charset, encoding string, content any)
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 `NegotiationBuilder.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, zstd. 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 ...any) *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 ...any) *NegotiationBuilder
JSONP registers the "text/javascript" content type and, optionally, a value that `Context.Negotiate` will render when a client accepts the "text/javascript" content type.
Returns itself for recursive calls.
func (*NegotiationBuilder) MIME ¶
func (n *NegotiationBuilder) MIME(mime string, content any) *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 ¶
func (n *NegotiationBuilder) MsgPack(v ...any) *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) Protobuf ¶
func (n *NegotiationBuilder) Protobuf(v ...any) *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 ¶
func (n *NegotiationBuilder) TextYAML(v ...any) *NegotiationBuilder
TextYAML registers the "text/yaml" content type and, optionally, a value that `Context.Negotiate` will render when a client accepts the "text/yaml" content type.
Returns itself for recursive calls.
func (*NegotiationBuilder) XML ¶
func (n *NegotiationBuilder) XML(v ...any) *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 ...any) *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 Page ¶
type Page[T any] = pagination.Page[T]
Page is an alias of pagination.Page: the response envelope of a paginated list.
type PageOptions ¶
type PageOptions = pagination.PageOptions
PageOptions is an alias of pagination.PageOptions: the page, size and details a client sends in the URL query.
type PaginationOption ¶
type PaginationOption func(*paginationOptions)
PaginationOption configures Context.BindPagination and Context.Paginated. See AllowSort and DenySort.
func AllowSort ¶
func AllowSort(columns ...string) PaginationOption
AllowSort limits the sort column a client may ask for. A sort outside the list answers 400 Bad Request naming the column and the allowed ones, before the collector runs.
It reads the decoded filter through its SortRequest method (ListFilter has one), so a filter without a sort request is unaffected.
func DenySort ¶
func DenySort(message string, render ...func(*Context, string)) PaginationOption
DenySort rejects any sort request with the given message. Use it on a list whose order is fixed by the query itself, where a client-chosen ORDER BY would either break the result or scan the table.
The rejection is a 400 Bad Request by default. An optional "render" answers it instead, so a caller that needs another status can say so: package rest/errors builds one from an error code, as errors.PermissionDenied.DenySort("..."). Only the first one is used.
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) ForceRelease ¶
ForceRelease puts a Context back to its pool, this function releases its resources. It does the same as Release.
type QueryOption ¶
type QueryOption func(*queryOptions)
QueryOption configures a strict query reader (QueryDate, QueryInt, QueryBool). See QueryRequired, QueryDefault and QueryZeroValues.
func QueryDefault ¶
func QueryDefault(raw string) QueryOption
QueryDefault sets the raw value to read when the key, or every accepted key, is absent. It is parsed exactly like a value the client sent, so the default is stated in the same wire form as the parameter itself ("2020-01-02", "25", "true"), and it is trimmed the same way.
A blank raw value is no default at all: a blank query value already reads as an absent one, so the reader falls back to QueryRequired or to the zero value instead of parsing the blank. Without that rule the three readers would disagree on the same option, QueryInt panicking where QueryDate answered a zero date.
An unparsable default is a programmer error and panics on the first request.
func QueryRequired ¶
func QueryRequired() QueryOption
QueryRequired makes an absent (or blank) query value a 400 Bad Request naming the key (or every accepted key), instead of the zero value.
QueryDefault wins over it: a reader that has a value to fall back on is never missing one, so the combination is not an error, it is simply the default.
func QueryZeroValues ¶
func QueryZeroValues(values ...string) QueryOption
QueryZeroValues lists the raw values that mean "unset", the placeholders older clients send instead of omitting the key: "0", "zero", "0000-00-00", "null". Such a value reads exactly like an absent one, so it takes the QueryDefault value when there is one and is a 400 under QueryRequired.
type Renderer ¶
Renderer is the interface that wraps the Render method. It is used to render a response to the client using the Iris Context as an argument.
type ResponseRenderer ¶
type ResponseRenderer interface {
// Render should push data with custom content type to the client.
Render(http.ResponseWriter) error
// WriteContentType writes custom content type to the response.
WriteContentType(w http.ResponseWriter)
}
ResponseRenderer is the interface which all custom response renderers must implement.
type ResponseWriter ¶
type ResponseWriter interface {
http.ResponseWriter
// Unwrap returns the underlying http.ResponseWriter,
// it's the original http.ResponseWriter that the first (*DefaultResponseWriter) Iris' response writer wraps.
//
// As of go 1.20 can work with http.NewResponseController.
Unwrap() http.ResponseWriter
// 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
// Flush sends any buffered data to the client.
Flush()
// Hijack lets the caller take over the connection.
// After a call to Hijack the HTTP server library
// will not do anything else with the connection.
Hijack() (net.Conn, *bufio.ReadWriter, error)
// Clone returns a copy of this response writer, carrying over the status code,
// the total number of bytes written and the hijacked flag.
// The copy wraps the same underlying http.ResponseWriter, therefore the headers
// are shared with the original one, they are not copied.
Clone() ResponseWriter
}
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.SetResponseWriter`. The rest of the response writers implementations (ResponseRecorder & CompressResponseWriter) are coupled to the internal ResponseWriter implementation(*DefaultResponseWriter).
A ResponseWriter may not be used after the Handler has returned.
type ResponseWriterBodyResetter ¶
type ResponseWriterBodyResetter interface {
// ResetBody should reset the body. It reports nothing back, use the
// ResponseWriterResetter.Reset method when the caller needs to know
// whether the reset was successful.
ResetBody()
}
ResponseWriterBodyResetter can be implemented by response writers that supports response body overriding (e.g. recorder and compressed).
type ResponseWriterDisabler ¶
type ResponseWriterDisabler interface {
// Disable makes this writer inert and returns the writer it wrapped, which
// the caller installs in its place.
//
// It must be safe to call before the first byte, it must be idempotent, and
// it must neutralise this writer's own deferred release, so that a compressor
// footer or a replayed status code cannot land in the middle of a live
// stream afterwards.
Disable() ResponseWriter
}
ResponseWriterDisabler is implemented by response writers that buffer or transform the response body and can step out of the chain before anything has been written to the client.
It exists for streaming. A writer that is correct for an ordinary response can be fatal for a stream: middleware/compress buffers into a compressor, and middleware/recorder - which accesslog, httpcache and servertiming all install - buffers into a bytes.Buffer. Neither reaches the client on a Flush.
See Context.DisableResponseBuffering, which walks the chain and calls this.
type ResponseWriterFlushError ¶
type ResponseWriterFlushError interface {
FlushError() error
}
ResponseWriterFlushError can be implemented by response writers that report whether a flush actually reached the client.
net/http's ResponseController probes this interface BEFORE http.Flusher, so implementing it turns a flush from "always succeeds" into the cheapest disconnect signal a long-lived response has. Only a real FIN/RST or a failing write cancels a request context, so a client that vanished without one - a closed lid, a dropped Wi-Fi link, an evicted NAT entry - otherwise goes unnoticed for as long as the kernel keeps retransmitting.
type ResponseWriterHeaderFlusher ¶
type ResponseWriterHeaderFlusher interface {
FlushHeaders()
Unwrap() ResponseWriter
Close() error
}
ResponseWriterHeaderFlusher can be implemented by response writers that can flush the headers before the body is being written. It's used internally. See middleare/compress/response_writer.go
type ResponseWriterResetter ¶
type ResponseWriterResetter interface {
// Reset should reset the whole response and reports
// whether it could reset successfully.
Reset() bool
}
ResponseWriterResetter 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 ¶
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 RestErrorRenderer ¶
type RestErrorRenderer interface {
// HandleError renders "err" as a server-side failure.
// Unrecognized errors render as 500. It reports whether a response
// was written and the caller should stop.
HandleError(ctx *Context, err error) bool
// HandleRequestError renders "err" as a client-side failure.
// Unrecognized errors render as 400. It reports whether a response
// was written and the caller should stop.
HandleRequestError(ctx *Context, err error) bool
// HandleRequestJSONError renders a failure to decode the request body
// as a client error (400). It reports whether a response was written.
HandleRequestJSONError(ctx *Context, err error) bool
// HandleResponseJSONError renders a failure to encode the response as
// a server error (500). It reports whether a response was written.
HandleResponseJSONError(ctx *Context, err error) bool
// HandleValidationError classifies-or-wraps a validation failure,
// then renders it as a 4xx client error.
HandleValidationError(ctx *Context, err error)
// HandleNotFound renders a 404 with the formatted message.
HandleNotFound(ctx *Context, format string, args ...any)
// HandleInvalidArgument renders a 400 with the formatted message.
HandleInvalidArgument(ctx *Context, format string, args ...any)
}
RestErrorRenderer renders the error responses of the Context's typed binding/response methods (BindJSON, BindParams, Count, Paginated, ...). The canonical implementation lives in rest/errors and installs itself at package-init time; the built-in fallback keeps package context usable alone.
type RouteReadOnly ¶
type RouteReadOnly interface {
// Router returns the Router which owns this route.
Router() Router
// GetName returns the route's name.
GetName() string
// GetMethod returns the route's method.
GetMethod() string
// GetSubdomain returns the route's subdomain.
GetSubdomain() string
// GetPath returns the route's original registered path.
GetPath() 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
// IsSitemapDisabled reports whether this route is excluded from the sitemap.
IsSitemapDisabled() 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
// GetMainHandlerName returns the name of the route's main handler,
// the last handler in its MainHandlerList (the one after every middleware).
GetMainHandlerName() string
// GetMainHandlerIndex returns the index of the route's main handler
// inside the MainHandlerList, that is the index of its last handler.
GetMainHandlerIndex() int
// GetHandlerList returns the route's handler list.
// It contains all handlers, middleware and main handlers.
// It's available only after BuildHandlers method.
GetHandlerList() *HandlerList
// GetRegisterFileName returns the file name that this route was registered on.
GetRegisterFileName() string
// GetRegisterLineNumber returns the line number that this route was registered on.
GetRegisterLineNumber() int
// GetProperty returns a specific property based on its "key"
// of this route's Router owner.
GetProperty(key string) (any, bool)
// IsNoRoute reports whether this route is a no-route (404, fired by the serve mux).
// Access of the not found path is gain by `ctx.Path()`.
IsNoRoute() bool
// IsMethodNotAllowed reports whether this route is a no-method (405, method not allowed, fired by the serve mux).
// Access of the forbidden request method is gain by `ctx.Method()` and allowed methods through "Allow" response header.
IsMethodNotAllowed() bool
// IsPreRouting reports whether this route is running before the main serve mux.
// Means that this Route's Handlers are running under `UseRouter`.
IsPreRouting() bool
// IsRoute reports whether this route is a registered route.
IsRoute() 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 Router ¶
type Router interface {
// GetRelPath returns the relative path of the router.
GetRelPath() string
// ContextOptions returns the router's request & response options.
ContextOptions() *ContextOptions
}
Router is the interface which all routers should implement.
type SecureCookie ¶
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 any) (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 any) error
}
SecureCookie should encodes and decodes authenticated and optionally encrypted cookie values. See `CookieEncoding` package-level function.
type SimpleUser ¶
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 is the user's plaintext password when basicauth created this user.
// Read it through GetPassword; never serialize it. See the type's doc.
Password string `json:"password,omitempty" db:"password"`
Email string `json:"email,omitempty" db:"email"`
Roles []string `json:"roles,omitempty" db:"roles"`
// Token is the raw credential this user authenticated with, e.g. a JWT.
// Read it through GetToken; never serialize it. See the type's doc.
Token json.RawMessage `json:"token,omitempty" db:"token"`
Fields Map `json:"fields,omitempty" db:"fields"`
}
SimpleUser is a simple implementation of the User interface.
SECURITY: never send a SimpleUser to a client. Its Password and Token fields are serialized like any other, so ctx.JSON(ctx.User()) hands the caller both of them. The basicauth middleware fills Password with the plaintext it read from the Authorization header. Build a response type carrying only the fields you mean to expose:
u := ctx.User()
username, _ := u.GetUsername()
id, _ := u.GetID()
ctx.JSON(iris.Map{"id": id, "username": username})
func (*SimpleUser) GetAuthorization ¶
func (u *SimpleUser) GetAuthorization() (string, error)
GetAuthorization returns the authorization method, e.g. Basic Authentication.
func (*SimpleUser) GetAuthorizedAt ¶
func (u *SimpleUser) GetAuthorizedAt() (time.Time, error)
GetAuthorizedAt returns the exact time the client has been authorized for the "first" time.
func (*SimpleUser) GetEmail ¶
func (u *SimpleUser) GetEmail() (string, error)
GetEmail returns the e-mail of (string,error) User.
func (*SimpleUser) GetField ¶
func (u *SimpleUser) GetField(key string) (any, error)
GetField optionally returns a dynamic field from the `Fields` field based on its key.
func (*SimpleUser) GetID ¶
func (u *SimpleUser) GetID() (string, error)
GetID returns the ID of the User.
func (*SimpleUser) GetPassword ¶
func (u *SimpleUser) GetPassword() (string, error)
GetPassword returns the raw password of the User.
func (*SimpleUser) GetRoles ¶
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 ¶
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 ¶
func (u *SimpleUser) GetUsername() (string, error)
GetUsername returns the name of the User.
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.
type User ¶
type User interface {
// GetRaw should return the raw instance of the user, if supported.
GetRaw() (any, 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) (any, 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() any 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 ¶
type UserGetPassword interface {
GetPassword() string
}
UserGetPassword interface which requires a single method to complete a User on Context.SetUser.
type UserGetUsername ¶
type UserGetUsername interface {
GetUsername() string
}
UserGetUsername interface which requires a single method to complete a User on Context.SetUser.
type UserMap ¶
type UserMap Map
UserMap can be used to convert a common map[string]any to a User. Usage:
user := map[string]any{
"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 ¶
GetAuthorization returns the authorization or Authorization value of the map.
func (UserMap) GetAuthorizedAt ¶
GetAuthorizedAt returns the authorized_at or Authorized_At value of the map.
func (UserMap) GetField ¶
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 ¶
GetPassword returns the password or Password value of the map.
func (UserMap) GetUsername ¶
GetUsername returns the username or Username value of the map.
type UserPartial ¶
type UserPartial struct {
Raw any `json:"raw"`
UserGetUsername `json:"-"`
UserGetPassword `json:"-"`
// 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.
SECURITY: Raw is the value passed to SetUser, kept whole and serialized whole. Sending a UserPartial to a client therefore sends every exported field of your own user type, including any secret on it. Build a response type instead; see Context.User. Only Raw is serialized: encoding/json/v2 rejects JSON tags on unexported fields outright, and the exported embedded interfaces are explicitly excluded — under the old encoder they re-serialized the user (credentials included) a second time under their own keys.
func (*UserPartial) GetAuthorization ¶
func (u *UserPartial) GetAuthorization() (string, error)
GetAuthorization should return the authorization method, e.g. Basic Authentication.
func (*UserPartial) GetAuthorizedAt ¶
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 ¶
func (u *UserPartial) GetEmail() (string, error)
GetEmail should return the e-mail of the User.
func (*UserPartial) GetField ¶
func (u *UserPartial) GetField(key string) (any, 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 ¶
func (u *UserPartial) GetID() (string, error)
GetID should return the ID of the User.
func (*UserPartial) GetPassword ¶
func (u *UserPartial) GetPassword() (string, error)
GetPassword should return the encoded or raw password (depends on the implementation) of the User.
func (*UserPartial) GetRaw ¶
func (u *UserPartial) GetRaw() (any, error)
GetRaw returns the original raw instance of the user.
func (*UserPartial) GetRoles ¶
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 ¶
func (u *UserPartial) GetToken() ([]byte, error)
GetToken should optionally return a token used to authorize this User.
func (*UserPartial) GetUsername ¶
func (u *UserPartial) GetUsername() (string, error)
GetUsername should return the name of the User.
type Validatable ¶
type Validatable interface {
Validate() error
}
Validatable is implemented by request types that validate themselves after decoding. BindJSON, BindJSONOptional and the BindJSONOneOrMany variants call Validate on the decoded value and reject the request with a client error response when it returns a non-nil error. BindUpdate calls it only for a full update: a partial update (the "columns" query key is present) skips it, see BindUpdate.
Source Files
¶
- accept_header.go
- application.go
- before_generic_methods_writef.go
- content_type.go
- context.go
- context_bind.go
- context_bind_update.go
- context_options.go
- context_request.go
- context_response.go
- context_wrapper.go
- dep.go
- doc.go
- fs.go
- handler.go
- handlerconv.go
- list_filter.go
- page.go
- pool.go
- query_strict.go
- response_writer.go
- rest_error_renderer.go
- rest_helpers.go
- route.go
- status.go
- user.go