iris

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2020 License: BSD-3-Clause Imports: 38 Imported by: 11,032

README

Iris Web Framework

Stale Release for pre-go modules. Please follow <github.com/kataras/iris/tree/master> instead.

Documentation

Index

Constants

View Source
const (
	// RouteOverride replaces an existing route with the new one, the default rule.
	RouteOverride = router.RouteOverride
	// RouteSkip keeps the original route and skips the new one.
	RouteSkip = router.RouteSkip
	// RouteError log when a route already exists, shown after the `Build` state,
	// server never starts.
	RouteError = router.RouteError
	// RouteOverlap will overlap the new route to the previous one.
	// If the route stopped and its response can be reset then the new route will be execute.
	RouteOverlap = router.RouteOverlap
)

Constants for input argument at `router.RouteRegisterRule`. See `Party#SetRegisterRule`.

View Source
const (
	ReferrerInvalid  = context.ReferrerInvalid
	ReferrerIndirect = context.ReferrerIndirect
	ReferrerDirect   = context.ReferrerDirect
	ReferrerEmail    = context.ReferrerEmail
	ReferrerSearch   = context.ReferrerSearch
	ReferrerSocial   = context.ReferrerSocial

	ReferrerNotGoogleSearch     = context.ReferrerNotGoogleSearch
	ReferrerGoogleOrganicSearch = context.ReferrerGoogleOrganicSearch
	ReferrerGoogleAdwords       = context.ReferrerGoogleAdwords
)

Contains the enum values of the `Context.GetReferrer()` method, shortcuts of the context subpackage.

View Source
const (
	MethodGet     = http.MethodGet
	MethodPost    = http.MethodPost
	MethodPut     = http.MethodPut
	MethodDelete  = http.MethodDelete
	MethodConnect = http.MethodConnect
	MethodHead    = http.MethodHead
	MethodPatch   = http.MethodPatch
	MethodOptions = http.MethodOptions
	MethodTrace   = http.MethodTrace
	// MethodNone is an iris-specific "virtual" method
	// to store the "offline" routes.
	MethodNone = router.MethodNone
)

HTTP Methods copied from `net/http`.

View Source
const (
	StatusContinue             = http.StatusContinue
	StatusSwitchingProtocols   = http.StatusSwitchingProtocols
	StatusProcessing           = http.StatusProcessing
	StatusEarlyHints           = http.StatusEarlyHints
	StatusOK                   = http.StatusOK
	StatusCreated              = http.StatusCreated
	StatusAccepted             = http.StatusAccepted
	StatusNonAuthoritativeInfo = http.StatusNonAuthoritativeInfo
	StatusNoContent            = http.StatusNoContent
	StatusResetContent         = http.StatusResetContent
	StatusPartialContent       = http.StatusPartialContent
	StatusMultiStatus          = http.StatusMultiStatus
	StatusAlreadyReported      = http.StatusAlreadyReported
	StatusIMUsed               = http.StatusIMUsed

	StatusMultipleChoices  = http.StatusMultipleChoices
	StatusMovedPermanently = http.StatusMovedPermanently
	StatusFound            = http.StatusFound
	StatusSeeOther         = http.StatusSeeOther
	StatusNotModified      = http.StatusNotModified
	StatusUseProxy         = http.StatusUseProxy

	StatusTemporaryRedirect = http.StatusTemporaryRedirect
	StatusPermanentRedirect = http.StatusPermanentRedirect

	StatusBadRequest                   = http.StatusBadRequest
	StatusUnauthorized                 = http.StatusUnauthorized
	StatusPaymentRequired              = http.StatusPaymentRequired
	StatusForbidden                    = http.StatusForbidden
	StatusNotFound                     = http.StatusNotFound
	StatusMethodNotAllowed             = http.StatusMethodNotAllowed
	StatusNotAcceptable                = http.StatusNotAcceptable
	StatusProxyAuthRequired            = http.StatusProxyAuthRequired
	StatusRequestTimeout               = http.StatusRequestTimeout
	StatusConflict                     = http.StatusConflict
	StatusGone                         = http.StatusGone
	StatusLengthRequired               = http.StatusLengthRequired
	StatusPreconditionFailed           = http.StatusPreconditionFailed
	StatusRequestEntityTooLarge        = http.StatusRequestEntityTooLarge
	StatusPayloadTooRage               = StatusRequestEntityTooLarge
	StatusRequestURITooLong            = http.StatusRequestURITooLong
	StatusUnsupportedMediaType         = http.StatusUnsupportedMediaType
	StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable
	StatusExpectationFailed            = http.StatusExpectationFailed
	StatusTeapot                       = http.StatusTeapot
	StatusMisdirectedRequest           = http.StatusMisdirectedRequest
	StatusUnprocessableEntity          = http.StatusUnprocessableEntity
	StatusLocked                       = http.StatusLocked
	StatusFailedDependency             = http.StatusFailedDependency
	StatusTooEarly                     = http.StatusTooEarly
	StatusUpgradeRequired              = http.StatusUpgradeRequired
	StatusPreconditionRequired         = http.StatusPreconditionRequired
	StatusTooManyRequests              = http.StatusTooManyRequests
	StatusRequestHeaderFieldsTooLarge  = http.StatusRequestHeaderFieldsTooLarge
	StatusUnavailableForLegalReasons   = http.StatusUnavailableForLegalReasons
	// Unofficial Client Errors.
	StatusPageExpired                      = context.StatusPageExpired
	StatusBlockedByWindowsParentalControls = context.StatusBlockedByWindowsParentalControls
	StatusInvalidToken                     = context.StatusInvalidToken
	StatusTokenRequired                    = context.StatusTokenRequired
	//
	StatusInternalServerError           = http.StatusInternalServerError
	StatusNotImplemented                = http.StatusNotImplemented
	StatusBadGateway                    = http.StatusBadGateway
	StatusServiceUnavailable            = http.StatusServiceUnavailable
	StatusGatewayTimeout                = http.StatusGatewayTimeout
	StatusHTTPVersionNotSupported       = http.StatusHTTPVersionNotSupported
	StatusVariantAlsoNegotiates         = http.StatusVariantAlsoNegotiates
	StatusInsufficientStorage           = http.StatusInsufficientStorage
	StatusLoopDetected                  = http.StatusLoopDetected
	StatusNotExtended                   = http.StatusNotExtended
	StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired
	// Unofficial Server Errors.
	StatusBandwidthLimitExceeded = context.StatusBandwidthLimitExceeded
	StatusInvalidSSLCertificate  = context.StatusInvalidSSLCertificate
	StatusSiteOverloaded         = context.StatusSiteOverloaded
	StatusSiteFrozen             = context.StatusSiteFrozen
	StatusNetworkReadTimeout     = context.StatusNetworkReadTimeout
)

HTTP status codes as registered with IANA. See: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml. Raw Copy from the future(tip) net/http std package in order to recude the import path of "net/http" for the users.

View Source
const (
	B = 1 << (10 * iota)
	KB
	MB
	GB
	TB
	PB
	EB
)

Byte unit helpers.

View Source
const NoLayout = view.NoLayout

NoLayout to disable layout for a particular template file A shortcut for the `view#NoLayout`.

View Source
const Version = "stale"

Version is the current version number of the Iris Web Framework.

Variables

View Source
var (
	// HTML view engine.
	// Shortcut of the view.HTML.
	HTML = view.HTML
	// Blocks view engine.
	// Can be used as a faster alternative of the HTML engine.
	// Shortcut of the view.Blocks.
	Blocks = view.Blocks
	// Django view engine.
	// Shortcut of the view.Django.
	Django = view.Django
	// Handlebars view engine.
	// Shortcut of the view.Handlebars.
	Handlebars = view.Handlebars
	// Pug view engine.
	// Shortcut of the view.Pug.
	Pug = view.Pug
	// Amber view engine.
	// Shortcut of the view.Amber.
	Amber = view.Amber
	// Jet view engine.
	// Shortcut of the view.Jet.
	Jet = view.Jet
	// Ace view engine.
	// Shortcut of the view.Ace.
	Ace = view.Ace
)
View Source
var (
	// Compression is a middleware which enables
	// writing and reading using the best offered compression.
	Compression = func(ctx Context) {
		ctx.CompressWriter(true)
		ctx.CompressReader(true)
		ctx.Next()
	}

	// MatchImagesAssets is a simple regex expression
	// that can be passed to the DirOptions.Cache.CompressIgnore field
	// in order to skip compression on already-compressed file types
	// such as images and pdf.
	MatchImagesAssets = regexp.MustCompile("((.*).pdf|(.*).jpg|(.*).jpeg|(.*).gif|(.*).tif|(.*).tiff)$")
	// MatchCommonAssets is a simple regex expression which
	// can be used on `DirOptions.PushTargetsRegexp`.
	// It will match and Push
	// all available js, css, font and media files.
	// Ideal for Single Page Applications.
	MatchCommonAssets = regexp.MustCompile("((.*).js|(.*).css|(.*).ico|(.*).png|(.*).ttf|(.*).svg|(.*).webp|(.*).gif)$")
)
View Source
var (
	// RegisterOnInterrupt registers a global function to call when CTRL+C/CMD+C pressed or a unix kill command received.
	//
	// A shortcut for the `host#RegisterOnInterrupt`.
	RegisterOnInterrupt = host.RegisterOnInterrupt

	// LimitRequestBodySize is a middleware which sets a request body size limit
	// for all next handlers in the chain.
	//
	// A shortcut for the `context#LimitRequestBodySize`.
	LimitRequestBodySize = context.LimitRequestBodySize
	// NewConditionalHandler returns a single Handler which can be registered
	// as a middleware.
	// Filter is just a type of Handler which returns a boolean.
	// Handlers here should act like middleware, they should contain `ctx.Next` to proceed
	// to the next handler of the chain. Those "handlers" are registered to the per-request context.
	//
	//
	// It checks the "filter" and if passed then
	// it, correctly, executes the "handlers".
	//
	// If passed, this function makes sure that the Context's information
	// about its per-request handler chain based on the new "handlers" is always updated.
	//
	// If not passed, then simply the Next handler(if any) is executed and "handlers" are ignored.
	// Example can be found at: _examples/routing/conditional-chain.
	//
	// A shortcut for the `context#NewConditionalHandler`.
	NewConditionalHandler = context.NewConditionalHandler
	// FileServer returns a Handler which serves files from a specific system, phyisical, directory
	// or an embedded one.
	// The first parameter is the directory, relative to the executable program.
	// The second optional parameter is any optional settings that the caller can use.
	//
	// See `Party#HandleDir` too.
	// Examples can be found at: https://github.com/kataras/iris/tree/master/_examples/file-server
	// A shortcut for the `router.FileServer`.
	FileServer = router.FileServer
	// DirListRich can be passed to `DirOptions.DirList` field
	// to override the default file listing appearance.
	// Read more at: `core/router.DirListRich`.
	DirListRich = router.DirListRich
	// StripPrefix returns a handler that serves HTTP requests
	// by removing the given prefix from the request URL's Path
	// and invoking the handler h. StripPrefix handles a
	// request for a path that doesn't begin with prefix by
	// replying with an HTTP 404 not found error.
	//
	// Usage:
	// fileserver := iris.FileServer("./static_files", DirOptions {...})
	// h := iris.StripPrefix("/static", fileserver)
	// app.Get("/static/{file:path}", h)
	// app.Head("/static/{file:path}", h)
	StripPrefix = router.StripPrefix
	// FromStd converts native http.Handler, http.HandlerFunc & func(w, r, next) to context.Handler.
	//
	// Supported form types:
	// 		 .FromStd(h http.Handler)
	// 		 .FromStd(func(w http.ResponseWriter, r *http.Request))
	// 		 .FromStd(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc))
	//
	// A shortcut for the `handlerconv#FromStd`.
	FromStd = handlerconv.FromStd
	// Cache is a middleware providing server-side cache functionalities
	// to the next handlers, can be used as: `app.Get("/", iris.Cache, aboutHandler)`.
	// It should be used after Static methods.
	// See `iris#Cache304` for an alternative, faster way.
	//
	// Examples can be found at: https://github.com/kataras/iris/tree/master/_examples/#caching
	Cache = cache.Handler
	// NoCache is a middleware which overrides the Cache-Control, Pragma and Expires headers
	// in order to disable the cache during the browser's back and forward feature.
	//
	// A good use of this middleware is on HTML routes; to refresh the page even on "back" and "forward" browser's arrow buttons.
	//
	// See `iris#StaticCache` for the opposite behavior.
	//
	// A shortcut of the `cache#NoCache`
	NoCache = cache.NoCache
	// StaticCache middleware for caching static files by sending the "Cache-Control" and "Expires" headers to the client.
	// It accepts a single input parameter, the "cacheDur", a time.Duration that it's used to calculate the expiration.
	//
	// If "cacheDur" <=0 then it returns the `NoCache` middleware instaed to disable the caching between browser's "back" and "forward" actions.
	//
	// Usage: `app.Use(iris.StaticCache(24 * time.Hour))` or `app.Use(iris.StaticCache(-1))`.
	// A middleware, which is a simple Handler can be called inside another handler as well, example:
	// cacheMiddleware := iris.StaticCache(...)
	// func(ctx iris.Context){
	//  cacheMiddleware(ctx)
	//  [...]
	// }
	//
	// A shortcut of the `cache#StaticCache`
	StaticCache = cache.StaticCache
	// Cache304 sends a `StatusNotModified` (304) whenever
	// the "If-Modified-Since" request header (time) is before the
	// time.Now() + expiresEvery (always compared to their UTC values).
	// Use this, which is a shortcut of the, `chache#Cache304` instead of the "github.com/kataras/iris/cache" or iris.Cache
	// for better performance.
	// Clients that are compatible with the http RCF (all browsers are and tools like postman)
	// will handle the caching.
	// The only disadvantage of using that instead of server-side caching
	// is that this method will send a 304 status code instead of 200,
	// So, if you use it side by side with other micro services
	// you have to check for that status code as well for a valid response.
	//
	// Developers are free to extend this method's behavior
	// by watching system directories changes manually and use of the `ctx.WriteWithExpiration`
	// with a "modtime" based on the file modified date,
	// similar to the `HandleDir`(which sends status OK(200) and browser disk caching instead of 304).
	//
	// A shortcut of the `cache#Cache304`.
	Cache304 = cache.Cache304

	// CookieAllowReclaim accepts the Context itself.
	// If set it will add the cookie to (on `CookieSet`, `CookieSetKV`, `CookieUpsert`)
	// or remove the cookie from (on `CookieRemove`) the Request object too.
	//
	// A shortcut for the `context#CookieAllowReclaim`.
	CookieAllowReclaim = context.CookieAllowReclaim
	// 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.
	//
	// A shortcut for the `context#CookieAllowSubdomains`.
	CookieAllowSubdomains = context.CookieAllowSubdomains
	// 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.
	//
	// A shortcut for the `context#CookieSameSite`.
	CookieSameSite = context.CookieHTTPOnly
	// CookieSecure sets the cookie's Secure option if the current request's
	// connection is using TLS. See `CookieHTTPOnly` too.
	//
	// A shortcut for the `context#CookieSecure`.
	CookieSecure = context.CookieSecure
	// CookieHTTPOnly is a `CookieOption`.
	// Use it to set the cookie's HttpOnly field to false or true.
	// HttpOnly field defaults to true for `RemoveCookie` and `SetCookieKV`.
	//
	// A shortcut for the `context#CookieHTTPOnly`.
	CookieHTTPOnly = context.CookieHTTPOnly
	// CookiePath is a `CookieOption`.
	// Use it to change the cookie's Path field.
	//
	// A shortcut for the `context#CookiePath`.
	CookiePath = context.CookiePath
	// CookieCleanPath is a `CookieOption`.
	// Use it to clear the cookie's Path field, exactly the same as `CookiePath("")`.
	//
	// A shortcut for the `context#CookieCleanPath`.
	CookieCleanPath = context.CookieCleanPath
	// CookieExpires is a `CookieOption`.
	// Use it to change the cookie's Expires and MaxAge fields by passing the lifetime of the cookie.
	//
	// A shortcut for the `context#CookieExpires`.
	CookieExpires = context.CookieExpires
	// CookieEncoding accepts a value which implements `Encode` and `Decode` methods.
	// It calls its `Encode` on `Context.SetCookie, UpsertCookie, and SetCookieKV` methods.
	// And on `Context.GetCookie` method it calls its `Decode`.
	//
	// A shortcut for the `context#CookieEncoding`.
	CookieEncoding = context.CookieEncoding

	// IsErrPath can be used at `context#ReadForm` and `context#ReadQuery`.
	// It reports whether the incoming error is type of `formbinder.ErrPath`,
	// which can be ignored when server allows unknown post values to be sent by the client.
	//
	// A shortcut for the `context#IsErrPath`.
	IsErrPath = context.IsErrPath
	// ErrEmptyForm is the type error which API users can make use of
	// to check if a form was empty on `Context.ReadForm`.
	//
	// A shortcut for the `context#ErrEmptyForm`.
	ErrEmptyForm = context.ErrEmptyForm
	// NewProblem returns a new Problem.
	// Head over to the `Problem` type godoc for more.
	//
	// A shortcut for the `context#NewProblem`.
	NewProblem = context.NewProblem
	// XMLMap wraps a map[string]interface{} to compatible xml marshaler,
	// in order to be able to render maps as XML on the `Context.XML` method.
	//
	// Example: `Context.XML(XMLMap("Root", map[string]interface{}{...})`.
	//
	// A shortcut for the `context#XMLMap`.
	XMLMap = context.XMLMap
	// ErrStopExecution if returned from a hero middleware or a request-scope dependency
	// stops the handler's execution, see _examples/dependency-injection/basic/middleware.
	ErrStopExecution = hero.ErrStopExecution
	// ErrHijackNotSupported is returned by the Hijack method to
	// indicate that Hijack feature is not available.
	//
	// A shortcut for the `context#ErrHijackNotSupported`.
	ErrHijackNotSupported = context.ErrHijackNotSupported
	// ErrPushNotSupported is returned by the Push method to
	// indicate that HTTP/2 Push support is not available.
	//
	// A shortcut for the `context#ErrPushNotSupported`.
	ErrPushNotSupported = context.ErrPushNotSupported
)
View Source
var (
	// TLSNoRedirect is a `host.Configurator` which can be passed as last argument
	// to the `TLS` runner function. It disables the automatic
	// registration of redirection from "http://" to "https://" requests.
	// Applies only to the `TLS` runner.
	// See `AutoTLSNoRedirect` to register a custom fallback server for `AutoTLS` runner.
	TLSNoRedirect = func(su *host.Supervisor) { su.NoRedirect() }
	// AutoTLSNoRedirect is a `host.Configurator`.
	// It registers a fallback HTTP/1.1 server for the `AutoTLS` one.
	// The function accepts the letsencrypt wrapper and it
	// should return a valid instance of http.Server which its handler should be the result
	// of the "acmeHandler" wrapper.
	// Usage:
	//	 getServer := func(acme func(http.Handler) http.Handler) *http.Server {
	//	     srv := &http.Server{Handler: acme(yourCustomHandler), ...otherOptions}
	//	     go srv.ListenAndServe()
	//	     return srv
	//   }
	//   app.Run(iris.AutoTLS(":443", "example.com example2.com", "mail@example.com", getServer))
	//
	// Note that if Server.Handler is nil then the server is automatically ran
	// by the framework and the handler set to automatic redirection, it's still
	// a valid option when the caller wants just to customize the server's fields (except Addr).
	// With this host configurator the caller can customize the server
	// that letsencrypt relies to perform the challenge.
	// LetsEncrypt Certification Manager relies on http://%s:80/.well-known/acme-challenge/<TOKEN>.
	AutoTLSNoRedirect = func(getFallbackServer func(acmeHandler func(fallback http.Handler) http.Handler) *http.Server) host.Configurator {
		return func(su *host.Supervisor) {
			su.NoRedirect()
			su.Fallback = getFallbackServer
		}
	}
)
View Source
var ErrServerClosed = http.ErrServerClosed

ErrServerClosed is returned by the Server's Serve, ServeTLS, ListenAndServe, and ListenAndServeTLS methods after a call to Shutdown or Close.

A shortcut for the `http#ErrServerClosed`.

View Source
var StatusText = context.StatusText

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

Shortcut for core/router#StatusText.

View Source
var WithEmptyFormError = func(app *Application) {
	app.config.FireEmptyFormError = true
}

WithEmptyFormError enables the setting `FireEmptyFormError`.

See `Configuration`.

View Source
var WithFireMethodNotAllowed = func(app *Application) {
	app.config.FireMethodNotAllowed = true
}

WithFireMethodNotAllowed enables the FireMethodNotAllowed setting.

See `Configuration`.

View Source
var WithGlobalConfiguration = func(app *Application) {
	app.Configure(WithConfiguration(YAML(globalConfigurationKeyword)))
}

WithGlobalConfiguration will load the global yaml configuration file from the home directory and it will set/override the whole app's configuration to that file's contents. The global configuration file can be modified by user and be used by multiple iris instances.

This is useful when we run multiple iris servers that share the same configuration, even with custom values at its "Other" field.

Usage: `app.Configure(iris.WithGlobalConfiguration)` or `app.Run(iris.Runner, iris.WithGlobalConfiguration)`.

View Source
var WithLowercaseRouting = func(app *Application) {
	app.config.ForceLowercaseRouting = true
}

WithLowercaseRouting enables for lowercase routing by setting the `ForceLowercaseRoutes` to true.

See `Configuration`.

View Source
var WithOptimizations = func(app *Application) {
	app.config.EnableOptimizations = true
}

WithOptimizations can force the application to optimize for the best performance where is possible.

See `Configuration`.

View Source
var WithPathEscape = func(app *Application) {
	app.config.EnablePathEscape = true
}

WithPathEscape sets the EnablePathEscape setting to true.

See `Configuration`.

View Source
var WithPathIntelligence = func(app *Application) {
	app.config.EnablePathIntelligence = true
}

WithPathIntelligence enables the EnablePathIntelligence setting.

See `Configuration`.

View Source
var WithResetOnFireErrorCode = func(app *Application) {
	app.config.ResetOnFireErrorCode = true
}

WithResetOnFireErrorCode sets the ResetOnFireErrorCode setting to true.

See `Configuration`.

View Source
var WithTunneling = func(app *Application) {
	conf := TunnelingConfiguration{
		Tunnels: []Tunnel{{}},
	}

	app.config.Tunneling = conf
}

WithTunneling is the `iris.Configurator` for the `iris.Configuration.Tunneling` field. It's used to enable http tunneling for an Iris Application, per registered host

Alternatively use the `iris.WithConfiguration(iris.Configuration{Tunneling: iris.TunnelingConfiguration{ ...}}}`.

View Source
var WithoutAutoFireStatusCode = func(app *Application) {
	app.config.DisableAutoFireStatusCode = true
}

WithoutAutoFireStatusCode sets the DisableAutoFireStatusCode setting to true.

See `Configuration`.

View Source
var WithoutBanner = WithoutStartupLog

WithoutBanner is a conversion for the `WithoutStartupLog` option.

Turns off the information send, once, to the terminal when the main server is open.

View Source
var WithoutBodyConsumptionOnUnmarshal = func(app *Application) {
	app.config.DisableBodyConsumptionOnUnmarshal = true
}

WithoutBodyConsumptionOnUnmarshal disables BodyConsumptionOnUnmarshal setting.

See `Configuration`.

View Source
var WithoutInterruptHandler = func(app *Application) {
	app.config.DisableInterruptHandler = true
}

WithoutInterruptHandler disables the automatic graceful server shutdown when control/cmd+C pressed.

View Source
var WithoutPathCorrection = func(app *Application) {
	app.config.DisablePathCorrection = true
}

WithoutPathCorrection disables the PathCorrection setting.

See `Configuration`.

View Source
var WithoutPathCorrectionRedirection = func(app *Application) {
	app.config.DisablePathCorrection = false
	app.config.DisablePathCorrectionRedirection = true
}

WithoutPathCorrectionRedirection disables the PathCorrectionRedirection setting.

See `Configuration`.

View Source
var WithoutStartupLog = func(app *Application) {
	app.config.DisableStartupLog = true
}

WithoutStartupLog turns off the information send, once, to the terminal when the main server is open.

Functions

func PrefixDir

func PrefixDir(prefix string, fs http.FileSystem) http.FileSystem

PrefixDir returns a new FileSystem that opens files by adding the given "prefix" to the directory tree of "fs".

func WithSocketSharding

func WithSocketSharding(app *Application)

WithSocketSharding sets the `Configuration.SocketSharding` field to true.

Types

type APIContainer

type APIContainer = router.APIContainer

APIContainer is a wrapper of a common `Party` featured by Dependency Injection. See `Party.ConfigureContainer` for more.

A shortcut for the `core/router#APIContainer`.

type Application

type Application struct {
	// routing embedded | exposing APIBuilder's and Router's public API.
	*router.APIBuilder
	*router.Router
	router.HTTPErrorHandler // if Router is Downgraded this is nil.
	ContextPool             *context.Pool

	// I18n contains localization and internationalization support.
	// Use the `Load` or `LoadAssets` to locale language files.
	//
	// See `Context#Tr` method for request-based translations.
	I18n *i18n.I18n

	// Validator is the request body validator, defaults to nil.
	Validator context.Validator

	// Hosts contains a list of all servers (Host Supervisors) that this app is running on.
	//
	// Hosts may be empty only if application ran(`app.Run`) with `iris.Raw` option runner,
	// otherwise it contains a single host (`app.Hosts[0]`).
	//
	// Additional Host Supervisors can be added to that list by calling the `app.NewHost` manually.
	//
	// Hosts field is available after `Run` or `NewHost`.
	Hosts []*host.Supervisor
	// contains filtered or unexported fields
}

Application is responsible to manage the state of the application. It contains and handles all the necessary parts to create a fast web server.

func Default

func Default() *Application

Default returns a new Application instance which on build state registers html view engine on "./views" and load locales from "./locales/*/*". The return instance recovers on panics and logs the incoming http requests too.

func New

func New() *Application

New creates and returns a fresh empty iris *Application instance.

func (*Application) Build

func (app *Application) Build() error

Build sets up, once, the framework. It builds the default router with its default macros and the template functions that are very-closed to iris.

If error occurred while building the Application, the returns type of error will be an *errgroup.Group which let the callers to inspect the errors and cause, usage:

import "github.com/kataras/iris/core/errgroup"

errgroup.Walk(app.Build(), func(typ interface{}, err error) {
	app.Logger().Errorf("%s: %s", typ, err)
})

func (*Application) ConfigurationReadOnly

func (app *Application) ConfigurationReadOnly() context.ConfigurationReadOnly

ConfigurationReadOnly returns an object which doesn't allow field writing.

func (*Application) Configure

func (app *Application) Configure(configurators ...Configurator) *Application

Configure can called when modifications to the framework instance needed. It accepts the framework instance and returns an error which if it's not nil it's printed to the logger. See configuration.go for more.

Returns itself in order to be used like `app:= New().Configure(...)`

func (*Application) ConfigureHost

func (app *Application) ConfigureHost(configurators ...host.Configurator) *Application

ConfigureHost accepts one or more `host#Configuration`, these configurators functions can access the host created by `app.Run` or `app.Listen`, they're being executed when application is ready to being served to the public.

It's an alternative way to interact with a host that is automatically created by `app.Run`.

These "configurators" can work side-by-side with the `iris#Addr, iris#Server, iris#TLS, iris#AutoTLS, iris#Listener` final arguments("hostConfigs") too.

Note that these application's host "configurators" will be shared with the rest of the hosts that this app will may create (using `app.NewHost`), meaning that `app.NewHost` will execute these "configurators" everytime that is being called as well.

These "configurators" should be registered before the `app.Run` or `host.Serve/Listen` functions.

func (*Application) I18nReadOnly

func (app *Application) I18nReadOnly() context.I18nReadOnly

I18nReadOnly returns the i18n's read-only features. See `I18n` method for more.

func (*Application) Listen

func (app *Application) Listen(hostPort string, withOrWithout ...Configurator) error

Listen builds the application and starts the server on the TCP network address "host:port" which handles requests on incoming connections.

Listen always returns a non-nil error. Ignore specific errors by using an `iris.WithoutServerError(iris.ErrServerClosed)` as a second input argument.

Listen is a shortcut of `app.Run(iris.Addr(hostPort, withOrWithout...))`. See `Run` for details.

func (*Application) Logger

func (app *Application) Logger() *golog.Logger

Logger returns the golog logger instance(pointer) that is being used inside the "app".

Available levels: - "disable" - "fatal" - "error" - "warn" - "info" - "debug" Usage: app.Logger().SetLevel("error") Or set the level through Configurartion's LogLevel or WithLogLevel functional option. Defaults to "info" level.

Callers can use the application's logger which is the same `golog.Default` logger, to print custom logs too. Usage: app.Logger().Error/Errorf("...") app.Logger().Warn/Warnf("...") app.Logger().Info/Infof("...") app.Logger().Debug/Debugf("...")

Setting one or more outputs: app.Logger().SetOutput(io.Writer...) Adding one or more outputs : app.Logger().AddOutput(io.Writer...)

Adding custom levels requires import of the `github.com/kataras/golog` package:

First we create our level to a golog.Level
in order to be used in the Log functions.
var SuccessLevel golog.Level = 6
Register our level, just three fields.
golog.Levels[SuccessLevel] = &golog.LevelMetadata{
	Name:    "success",
	RawText: "[SUCC]",
	// ColorfulText (Green Color[SUCC])
	ColorfulText: "\x1b[32m[SUCC]\x1b[0m",
}

Usage: app.Logger().SetLevel("success") app.Logger().Logf(SuccessLevel, "a custom leveled log message")

func (*Application) NewHost

func (app *Application) NewHost(srv *http.Server) *host.Supervisor

NewHost accepts a standard *http.Server object, completes the necessary missing parts of that "srv" and returns a new, ready-to-use, host (supervisor).

func (*Application) RegisterView

func (app *Application) RegisterView(viewEngine view.Engine)

RegisterView should be used to register view engines mapping to a root directory and the template file(s) extension.

func (*Application) Run

func (app *Application) Run(serve Runner, withOrWithout ...Configurator) error

Run builds the framework and starts the desired `Runner` with or without configuration edits.

Run should be called only once per Application instance, it blocks like http.Server.

If more than one server needed to run on the same iris instance then create a new host and run it manually by `go NewHost(*http.Server).Serve/ListenAndServe` etc... or use an already created host: h := NewHost(*http.Server) Run(Raw(h.ListenAndServe), WithCharset("utf-8"), WithRemoteAddrHeader("CF-Connecting-IP"))

The Application can go online with any type of server or iris's host with the help of the following runners: `Listener`, `Server`, `Addr`, `TLS`, `AutoTLS` and `Raw`.

func (*Application) Shutdown

func (app *Application) Shutdown(ctx stdContext.Context) error

Shutdown gracefully terminates all the application's server hosts and any tunnels. Returns an error on the first failure, otherwise nil.

func (*Application) SubdomainRedirect

func (app *Application) SubdomainRedirect(from, to router.Party) router.Party

SubdomainRedirect registers a router wrapper which redirects(StatusMovedPermanently) a (sub)domain to another subdomain or to the root domain as fast as possible, before the router's try to execute route's handler(s).

It receives two arguments, they are the from and to/target locations, 'from' can be a wildcard subdomain as well (app.WildcardSubdomain()) 'to' is not allowed to be a wildcard for obvious reasons, 'from' can be the root domain(app) when the 'to' is not the root domain and visa-versa.

Usage: www := app.Subdomain("www") <- same as app.Party("www.") app.SubdomainRedirect(app, www) This will redirect all http(s)://mydomain.com/%anypath% to http(s)://www.mydomain.com/%anypath%.

One or more subdomain redirects can be used to the same app instance.

If you need more information about this implementation then you have to navigate through the `core/router#NewSubdomainRedirectWrapper` function instead.

Example: https://github.com/kataras/iris/tree/master/_examples/routing/subdomains/redirect

func (*Application) Validate

func (app *Application) Validate(v interface{}) error

Validate validates a value and returns nil if passed or the failure reason if does not.

func (*Application) View

func (app *Application) View(writer io.Writer, filename string, layout string, bindingData interface{}) error

View executes and writes the result of a template file to the writer.

First parameter is the writer to write the parsed template. Second parameter is the relative, to templates directory, template filename, including extension. Third parameter is the layout, can be empty string. Forth parameter is the bindable data to the template, can be nil.

Use context.View to render templates to the client instead. Returns an error on failure, otherwise nil.

func (*Application) WWW

func (app *Application) WWW() router.Party

WWW creates and returns a "www." subdomain. The difference from `app.Subdomain("www")` or `app.Party("www.")` is that the `app.WWW()` method wraps the router so all http(s)://mydomain.com will be redirect to http(s)://www.mydomain.com. Other subdomains can be registered using the app: `sub := app.Subdomain("mysubdomain")`, child subdomains can be registered using the www := app.WWW(); www.Subdomain("wwwchildSubdomain").

type Attachments

type Attachments = router.Attachments

Attachments options for files to be downloaded and saved locally by the client. See `DirOptions`.

type Configuration

type Configuration struct {

	// LogLevel is the log level the application should use to output messages.
	// Logger, by default, is mostly used on Build state but it is also possible
	// that debug error messages could be thrown when the app is running, e.g.
	// when malformed data structures try to be sent on Client (i.e Context.JSON/JSONP/XML...).
	//
	// Defaults to "info". Possible values are:
	// * "disable"
	// * "fatal"
	// * "error"
	// * "warn"
	// * "info"
	// * "debug"
	LogLevel string `json:"logLevel" yaml:"LogLevel" toml:"LogLevel" env:"LOG_LEVEL"`

	// SocketSharding enables SO_REUSEPORT (or SO_REUSEADDR for windows)
	// on all registered Hosts.
	// This option allows linear scaling server performance on multi-CPU servers.
	//
	// Please read the following:
	// 1. https://stackoverflow.com/a/14388707
	// 2. https://stackoverflow.com/a/59692868
	// 3. https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/
	// 4. (BOOK) Learning HTTP/2: A Practical Guide for Beginners:
	//	  Page 37, To Shard or Not to Shard?
	//
	// Defaults to false.
	SocketSharding bool `json:"socketSharding" yaml:"SocketSharding" toml:"SocketSharding" env:"SOCKET_SHARDING"`
	// Tunneling can be optionally set to enable ngrok http(s) tunneling for this Iris app instance.
	// See the `WithTunneling` Configurator too.
	Tunneling TunnelingConfiguration `json:"tunneling,omitempty" yaml:"Tunneling" toml:"Tunneling"`
	// IgnoreServerErrors will cause to ignore the matched "errors"
	// from the main application's `Run` function.
	// This is a slice of string, not a slice of error
	// users can register these errors using yaml or toml configuration file
	// like the rest of the configuration fields.
	//
	// See `WithoutServerError(...)` function too.
	//
	// Example: https://github.com/kataras/iris/tree/master/_examples/http-server/listen-addr/omit-server-errors
	//
	// Defaults to an empty slice.
	IgnoreServerErrors []string `json:"ignoreServerErrors,omitempty" yaml:"IgnoreServerErrors" toml:"IgnoreServerErrors"`

	// DisableStartupLog if set to true then it turns off the write banner on server startup.
	//
	// Defaults to false.
	DisableStartupLog bool `json:"disableStartupLog,omitempty" yaml:"DisableStartupLog" toml:"DisableStartupLog"`
	// DisableInterruptHandler if set to true then it disables the automatic graceful server shutdown
	// when control/cmd+C pressed.
	// Turn this to true if you're planning to handle this by your own via a custom host.Task.
	//
	// Defaults to false.
	DisableInterruptHandler bool `json:"disableInterruptHandler,omitempty" yaml:"DisableInterruptHandler" toml:"DisableInterruptHandler"`

	// DisablePathCorrection disables the correcting
	// and redirecting or executing directly the handler of
	// the requested path to the registered path
	// for example, if /home/ path is requested but no handler for this Route found,
	// then the Router checks if /home handler exists, if yes,
	// (permanent)redirects the client to the correct path /home.
	//
	// See `DisablePathCorrectionRedirection` to enable direct handler execution instead of redirection.
	//
	// Defaults to false.
	DisablePathCorrection bool `json:"disablePathCorrection,omitempty" yaml:"DisablePathCorrection" toml:"DisablePathCorrection"`
	// DisablePathCorrectionRedirection works whenever configuration.DisablePathCorrection is set to false
	// and if DisablePathCorrectionRedirection set to true then it will fire the handler of the matching route without
	// the trailing slash ("/") instead of send a redirection status.
	//
	// Defaults to false.
	DisablePathCorrectionRedirection bool `` /* 129-byte string literal not displayed */
	// EnablePathIntelligence if set to true,
	// the router will redirect HTTP "GET" not found pages to the most closest one path(if any). For example
	// you register a route at "/contact" path -
	// a client tries to reach it by "/cont", the path will be automatic fixed
	// and the client will be redirected to the "/contact" path
	// instead of getting a 404 not found response back.
	//
	// Defaults to false.
	EnablePathIntelligence bool `json:"enablePathIntelligence,omitempty" yaml:"EnablePathIntelligence" toml:"EnablePathIntelligence"`
	// EnablePathEscape when is true then its escapes the path and the named parameters (if any).
	// When do you need to Disable(false) it:
	// accepts parameters with slash '/'
	// Request: http://localhost:8080/details/Project%2FDelta
	// ctx.Param("project") returns the raw named parameter: Project%2FDelta
	// which you can escape it manually with net/url:
	// projectName, _ := url.QueryUnescape(c.Param("project").
	//
	// Defaults to false.
	EnablePathEscape bool `json:"enablePathEscape,omitempty" yaml:"EnablePathEscape" toml:"EnablePathEscape"`
	// ForceLowercaseRouting if enabled, converts all registered routes paths to lowercase
	// and it does lowercase the request path too for matching.
	//
	// Defaults to false.
	ForceLowercaseRouting bool `json:"forceLowercaseRouting,omitempty" yaml:"ForceLowercaseRouting" toml:"ForceLowercaseRouting"`
	// FireMethodNotAllowed if it's true router checks for StatusMethodNotAllowed(405) and
	//  fires the 405 error instead of 404
	// Defaults to false.
	FireMethodNotAllowed bool `json:"fireMethodNotAllowed,omitempty" yaml:"FireMethodNotAllowed" toml:"FireMethodNotAllowed"`
	// DisableAutoFireStatusCode if true then it turns off the http error status code
	// handler automatic execution on error code from a `Context.StatusCode` call.
	// By-default a custom http error handler will be fired when "Context.StatusCode(errorCode)" called.
	//
	// Defaults to false.
	DisableAutoFireStatusCode bool `json:"disableAutoFireStatusCode,omitempty" yaml:"DisableAutoFireStatusCode" toml:"DisableAutoFireStatusCode"`
	// ResetOnFireErrorCode if true then any previously response body or headers through
	// response recorder will be ignored and the router
	// will fire the registered (or default) HTTP error handler instead.
	// See `core/router/handler#FireErrorCode` and `Context.EndRequest` for more details.
	//
	// Read more at: https://github.com/kataras/iris/issues/1531
	//
	// Defaults to false.
	ResetOnFireErrorCode bool `json:"resetOnFireErrorCode,omitempty" yaml:"ResetOnFireErrorCode" toml:"ResetOnFireErrorCode"`

	// EnableOptimization when this field is true
	// then the application tries to optimize for the best performance where is possible.
	//
	// Defaults to false.
	EnableOptimizations bool `json:"enableOptimizations,omitempty" yaml:"EnableOptimizations" toml:"EnableOptimizations"`
	// DisableBodyConsumptionOnUnmarshal manages the reading behavior of the context's body readers/binders.
	// If set to true then it
	// disables the body consumption by the `context.UnmarshalBody/ReadJSON/ReadXML`.
	//
	// By-default io.ReadAll` is used to read the body from the `context.Request.Body which is an `io.ReadCloser`,
	// if this field set to true then a new buffer will be created to read from and the request body.
	// The body will not be changed and existing data before the
	// context.UnmarshalBody/ReadJSON/ReadXML will be not consumed.
	DisableBodyConsumptionOnUnmarshal bool `` /* 132-byte string literal not displayed */
	// FireEmptyFormError returns if set to tue true then the `context.ReadBody/ReadForm`
	// will return an `iris.ErrEmptyForm` on empty request form data.
	FireEmptyFormError bool `json:"fireEmptyFormError,omitempty" yaml:"FireEmptyFormError" toml:"FireEmptyFormError"`

	// TimeFormat time format for any kind of datetime parsing
	// Defaults to  "Mon, 02 Jan 2006 15:04:05 GMT".
	TimeFormat string `json:"timeFormat,omitempty" yaml:"TimeFormat" toml:"TimeFormat"`

	// Charset character encoding for various rendering
	// used for templates and the rest of the responses
	// Defaults to "utf-8".
	Charset string `json:"charset,omitempty" yaml:"Charset" toml:"Charset"`

	// PostMaxMemory sets the maximum post data size
	// that a client can send to the server, this differs
	// from the overral request body size which can be modified
	// by the `context#SetMaxRequestBodySize` or `iris#LimitRequestBodySize`.
	//
	// Defaults to 32MB or 32 << 20 if you prefer.
	PostMaxMemory int64 `json:"postMaxMemory" yaml:"PostMaxMemory" toml:"PostMaxMemory"`

	// Context values' keys for various features.
	//
	// LocaleContextKey is used by i18n to get the current request's locale, which contains a translate function too.
	//
	// Defaults to "iris.locale".
	LocaleContextKey string `json:"localeContextKey,omitempty" yaml:"LocaleContextKey" toml:"LocaleContextKey"`
	// LanguageContextKey is the context key which a language can be modified by a middleware.
	// It has the highest priority over the rest and if it is empty then it is ignored,
	// if it set to a static string of "default" or to the default language's code
	// then the rest of the language extractors will not be called at all and
	// the default language will be set instead.
	//
	// Use with `Context.SetLanguage("el-GR")`.
	//
	// See `i18n.ExtractFunc` for a more organised way of the same feature.
	// Defaults to "iris.locale.language".
	LanguageContextKey string `json:"languageContextKey,omitempty" yaml:"LanguageContextKey" toml:"LanguageContextKey"`
	// VersionContextKey is the context key which an API Version can be modified
	// via a middleware through `SetVersion` method, e.g. `versioning.SetVersion(ctx, "1.0, 1.1")`.
	// Defaults to "iris.api.version".
	VersionContextKey string `json:"versionContextKey" yaml:"VersionContextKey" toml:"VersionContextKey"`
	// ViewEngineContextKey is the context's values key
	// responsible to store and retrieve(view.Engine) the current view engine.
	// A middleware or a Party can modify its associated value to change
	// a view engine that `ctx.View` will render through.
	// If not an engine is registered by the end-developer
	// then its associated value is always nil,
	// meaning that the default value is nil.
	// See `Party.RegisterView` and `Context.ViewEngine` methods as well.
	//
	// Defaults to "iris.view.engine".
	ViewEngineContextKey string `json:"viewEngineContextKey,omitempty" yaml:"ViewEngineContextKey" toml:"ViewEngineContextKey"`
	// ViewLayoutContextKey is the context's values key
	// responsible to store and retrieve(string) the current view layout.
	// A middleware can modify its associated value to change
	// the layout that `ctx.View` will use to render a template.
	//
	// Defaults to "iris.view.layout".
	ViewLayoutContextKey string `json:"viewLayoutContextKey,omitempty" yaml:"ViewLayoutContextKey" toml:"ViewLayoutContextKey"`
	// ViewDataContextKey is the context's values key
	// responsible to store and retrieve(interface{}) the current view binding data.
	// A middleware can modify its associated value to change
	// the template's data on-fly.
	//
	// Defaults to "iris.view.data".
	ViewDataContextKey string `json:"viewDataContextKey,omitempty" yaml:"ViewDataContextKey" toml:"ViewDataContextKey"`
	// RemoteAddrHeaders are the allowed request headers names
	// that can be valid to parse the client's IP based on.
	// By-default no "X-" header is consired safe to be used for retrieving the
	// client's IP address, because those headers can manually change by
	// the client. But sometimes are useful e.g. when behind a proxy
	// you want to enable the "X-Forwarded-For" or when cloudflare
	// you want to enable the "CF-Connecting-IP", indeed you
	// can allow the `ctx.RemoteAddr()` to use any header
	// that the client may sent.
	//
	// Defaults to an empty slice but an example usage is:
	// RemoteAddrHeaders {
	//	"X-Real-Ip",
	//  "X-Forwarded-For",
	// 	"CF-Connecting-IP",
	//	}
	//
	// Look `context.RemoteAddr()` for more.
	RemoteAddrHeaders []string `json:"remoteAddrHeaders,omitempty" yaml:"RemoteAddrHeaders" toml:"RemoteAddrHeaders"`
	// RemoteAddrHeadersForce forces the `Context.RemoteAddr()` method
	// to return the first entry of a request header as a fallback,
	// even if that IP is a part of the `RemoteAddrPrivateSubnets` list.
	// The default behavior, if a remote address is part of the `RemoteAddrPrivateSubnets`,
	// is to retrieve the IP from the `Request.RemoteAddr` field instead.
	RemoteAddrHeadersForce bool `json:"remoteAddrHeadersForce,omitempty" yaml:"RemoteAddrHeadersForce" toml:"RemoteAddrHeadersForce"`
	// RemoteAddrPrivateSubnets defines the private sub-networks.
	// They are used to be compared against
	// IP Addresses fetched through `RemoteAddrHeaders` or `Context.Request.RemoteAddr`.
	// For details please navigate through: https://github.com/kataras/iris/issues/1453
	// Defaults to:
	// {
	// 	Start: net.ParseIP("10.0.0.0"),
	// 	End:   net.ParseIP("10.255.255.255"),
	// },
	// {
	// 	Start: net.ParseIP("100.64.0.0"),
	// 	End:   net.ParseIP("100.127.255.255"),
	// },
	// {
	// 	Start: net.ParseIP("172.16.0.0"),
	// 	End:   net.ParseIP("172.31.255.255"),
	// },
	// {
	// 	Start: net.ParseIP("192.0.0.0"),
	// 	End:   net.ParseIP("192.0.0.255"),
	// },
	// {
	// 	Start: net.ParseIP("192.168.0.0"),
	// 	End:   net.ParseIP("192.168.255.255"),
	// },
	// {
	// 	Start: net.ParseIP("198.18.0.0"),
	// 	End:   net.ParseIP("198.19.255.255"),
	// }
	//
	// Look `Context.RemoteAddr()` for more.
	RemoteAddrPrivateSubnets []netutil.IPRange `json:"remoteAddrPrivateSubnets" yaml:"RemoteAddrPrivateSubnets" toml:"RemoteAddrPrivateSubnets"`
	// SSLProxyHeaders defines the set of header key values
	// that would indicate a valid https Request (look `Context.IsSSL()`).
	// Example: `map[string]string{"X-Forwarded-Proto": "https"}`.
	//
	// Defaults to empty map.
	SSLProxyHeaders map[string]string `json:"sslProxyHeaders" yaml:"SSLProxyHeaders" toml:"SSLProxyHeaders"`
	// HostProxyHeaders defines the set of headers that may hold a proxied hostname value for the clients.
	// Look `Context.Host()` for more.
	// Defaults to empty map.
	HostProxyHeaders map[string]bool `json:"hostProxyHeaders" yaml:"HostProxyHeaders" toml:"HostProxyHeaders"`
	// Other are the custom, dynamic options, can be empty.
	// This field used only by you to set any app's options you want.
	//
	// Defaults to empty map.
	Other map[string]interface{} `json:"other,omitempty" yaml:"Other" toml:"Other"`
	// contains filtered or unexported fields
}

Configuration holds the necessary settings for an Iris Application instance. All fields are optionally, the default values will work for a common web application.

A Configuration value can be passed through `WithConfiguration` Configurator. Usage: conf := iris.Configuration{ ... } app := iris.New() app.Configure(iris.WithConfiguration(conf)) OR app.Run/Listen(..., iris.WithConfiguration(conf)).

func DefaultConfiguration

func DefaultConfiguration() Configuration

DefaultConfiguration returns the default configuration for an iris station, fills the main Configuration

func TOML

func TOML(filename string) Configuration

TOML reads Configuration from a toml-compatible document file. Read more about toml's implementation at: https://github.com/toml-lang/toml

Accepts the absolute path of the configuration file. An error will be shown to the user via panic with the error message. Error may occur when the file does not exist or is not formatted correctly.

Note: if the char '~' passed as "filename" then it tries to load and return the configuration from the $home_directory + iris.tml, see `WithGlobalConfiguration` for more information.

Usage: app.Configure(iris.WithConfiguration(iris.TOML("myconfig.tml"))) or app.Run(iris.Runner, iris.WithConfiguration(iris.TOML("myconfig.tml"))).

func YAML

func YAML(filename string) Configuration

YAML reads Configuration from a configuration.yml file.

Accepts the absolute path of the cfg.yml. An error will be shown to the user via panic with the error message. Error may occur when the cfg.yml does not exist or is not formatted correctly.

Note: if the char '~' passed as "filename" then it tries to load and return the configuration from the $home_directory + iris.yml, see `WithGlobalConfiguration` for more information.

Usage: app.Configure(iris.WithConfiguration(iris.YAML("myconfig.yml"))) or app.Run(iris.Runner, iris.WithConfiguration(iris.YAML("myconfig.yml"))).

func (Configuration) GetCharset

func (c Configuration) GetCharset() string

GetCharset returns the Charset field.

func (Configuration) GetDisableAutoFireStatusCode

func (c Configuration) GetDisableAutoFireStatusCode() bool

GetDisableAutoFireStatusCode returns the DisableAutoFireStatusCode field.

func (Configuration) GetDisableBodyConsumptionOnUnmarshal

func (c Configuration) GetDisableBodyConsumptionOnUnmarshal() bool

GetDisableBodyConsumptionOnUnmarshal returns the DisableBodyConsumptionOnUnmarshal field.

func (Configuration) GetDisablePathCorrection

func (c Configuration) GetDisablePathCorrection() bool

GetDisablePathCorrection returns the DisablePathCorrection field.

func (Configuration) GetDisablePathCorrectionRedirection

func (c Configuration) GetDisablePathCorrectionRedirection() bool

GetDisablePathCorrectionRedirection returns the DisablePathCorrectionRedirection field.

func (Configuration) GetEnableOptimizations

func (c Configuration) GetEnableOptimizations() bool

GetEnableOptimizations returns the EnableOptimizations.

func (Configuration) GetEnablePathEscape

func (c Configuration) GetEnablePathEscape() bool

GetEnablePathEscape returns the EnablePathEscape field.

func (Configuration) GetEnablePathIntelligence

func (c Configuration) GetEnablePathIntelligence() bool

GetEnablePathIntelligence returns the EnablePathIntelligence field.

func (Configuration) GetFireEmptyFormError

func (c Configuration) GetFireEmptyFormError() bool

GetFireEmptyFormError returns the DisableBodyConsumptionOnUnmarshal field.

func (Configuration) GetFireMethodNotAllowed

func (c Configuration) GetFireMethodNotAllowed() bool

GetFireMethodNotAllowed returns the FireMethodNotAllowed field.

func (Configuration) GetForceLowercaseRouting

func (c Configuration) GetForceLowercaseRouting() bool

GetForceLowercaseRouting returns the ForceLowercaseRouting field.

func (Configuration) GetHostProxyHeaders

func (c Configuration) GetHostProxyHeaders() map[string]bool

GetHostProxyHeaders returns the HostProxyHeaders field.

func (Configuration) GetLanguageContextKey

func (c Configuration) GetLanguageContextKey() string

GetLanguageContextKey returns the LanguageContextKey field.

func (Configuration) GetLocaleContextKey

func (c Configuration) GetLocaleContextKey() string

GetLocaleContextKey returns the LocaleContextKey field.

func (Configuration) GetLogLevel

func (c Configuration) GetLogLevel() string

GetLogLevel returns the LogLevel field.

func (Configuration) GetOther

func (c Configuration) GetOther() map[string]interface{}

GetOther returns the Other field.

func (Configuration) GetPostMaxMemory

func (c Configuration) GetPostMaxMemory() int64

GetPostMaxMemory returns the PostMaxMemory field.

func (Configuration) GetRemoteAddrHeaders

func (c Configuration) GetRemoteAddrHeaders() []string

GetRemoteAddrHeaders returns the RemoteAddrHeaders field.

func (Configuration) GetRemoteAddrHeadersForce

func (c Configuration) GetRemoteAddrHeadersForce() bool

GetRemoteAddrHeadersForce returns RemoteAddrHeadersForce field.

func (Configuration) GetRemoteAddrPrivateSubnets

func (c Configuration) GetRemoteAddrPrivateSubnets() []netutil.IPRange

GetRemoteAddrPrivateSubnets returns the RemoteAddrPrivateSubnets field.

func (Configuration) GetResetOnFireErrorCode

func (c Configuration) GetResetOnFireErrorCode() bool

GetResetOnFireErrorCode returns ResetOnFireErrorCode field.

func (Configuration) GetSSLProxyHeaders

func (c Configuration) GetSSLProxyHeaders() map[string]string

GetSSLProxyHeaders returns the SSLProxyHeaders field.

func (Configuration) GetSocketSharding

func (c Configuration) GetSocketSharding() bool

GetSocketSharding returns the SocketSharding field.

func (Configuration) GetTimeFormat

func (c Configuration) GetTimeFormat() string

GetTimeFormat returns the TimeFormat field.

func (Configuration) GetVHost

func (c Configuration) GetVHost() string

GetVHost returns the non-exported vhost config field.

func (Configuration) GetVersionContextKey

func (c Configuration) GetVersionContextKey() string

GetVersionContextKey returns the VersionContextKey field.

func (Configuration) GetViewDataContextKey

func (c Configuration) GetViewDataContextKey() string

GetViewDataContextKey returns the ViewDataContextKey field.

func (Configuration) GetViewEngineContextKey

func (c Configuration) GetViewEngineContextKey() string

GetViewEngineContextKey returns the ViewEngineContextKey field.

func (Configuration) GetViewLayoutContextKey

func (c Configuration) GetViewLayoutContextKey() string

GetViewLayoutContextKey returns the ViewLayoutContextKey field.

type Configurator

type Configurator func(*Application)

Configurator is just an interface which accepts the framework instance.

It can be used to register a custom configuration with `Configure` in order to modify the framework instance.

Currently Configurator is being used to describe the configuration's fields values.

func WithCharset

func WithCharset(charset string) Configurator

WithCharset sets the Charset setting.

See `Configuration`.

func WithConfiguration

func WithConfiguration(c Configuration) Configurator

WithConfiguration sets the "c" values to the framework's configurations.

Usage: app.Listen(":8080", iris.WithConfiguration(iris.Configuration{/* fields here */ })) or iris.WithConfiguration(iris.YAML("./cfg/iris.yml")) or iris.WithConfiguration(iris.TOML("./cfg/iris.tml"))

func WithHostProxyHeader

func WithHostProxyHeader(headers ...string) Configurator

WithHostProxyHeader sets a HostProxyHeaders key value pair. Example: WithHostProxyHeader("X-Host"). See `Context.Host` for more.

func WithLogLevel

func WithLogLevel(level string) Configurator

WithLogLevel sets the `Configuration.LogLevel` field.

func WithOtherValue

func WithOtherValue(key string, val interface{}) Configurator

WithOtherValue adds a value based on a key to the Other setting.

See `Configuration.Other`.

func WithPostMaxMemory

func WithPostMaxMemory(limit int64) Configurator

WithPostMaxMemory sets the maximum post data size that a client can send to the server, this differs from the overral request body size which can be modified by the `context#SetMaxRequestBodySize` or `iris#LimitRequestBodySize`.

Defaults to 32MB or 32 << 20 or 32*iris.MB if you prefer.

func WithRemoteAddrHeader

func WithRemoteAddrHeader(header ...string) Configurator

WithRemoteAddrHeader adds a new request header name that can be used to validate the client's real IP.

func WithRemoteAddrPrivateSubnet

func WithRemoteAddrPrivateSubnet(startIP, endIP string) Configurator

WithRemoteAddrPrivateSubnet adds a new private sub-net to be excluded from `context.RemoteAddr`. See `WithRemoteAddrHeader` too.

func WithSSLProxyHeader

func WithSSLProxyHeader(headerKey, headerValue string) Configurator

WithSSLProxyHeader sets a SSLProxyHeaders key value pair. Example: WithSSLProxyHeader("X-Forwarded-Proto", "https"). See `Context.IsSSL` for more.

func WithSitemap

func WithSitemap(startURL string) Configurator

WithSitemap enables the sitemap generator. Use the Route's `SetLastMod`, `SetChangeFreq` and `SetPriority` to modify the sitemap's URL child element properties.

It accepts a "startURL" input argument which is the prefix for the registered routes that will be included in the sitemap.

If more than 50,000 static routes are registered then sitemaps will be splitted and a sitemap index will be served in /sitemap.xml.

If `Application.I18n.Load/LoadAssets` is called then the sitemap will contain translated links for each static route.

If the result does not complete your needs you can take control and use the github.com/kataras/sitemap package to generate a customized one instead.

Example: https://github.com/kataras/iris/tree/master/_examples/sitemap.

func WithTimeFormat

func WithTimeFormat(timeformat string) Configurator

WithTimeFormat sets the TimeFormat setting.

See `Configuration`.

func WithoutRemoteAddrHeader

func WithoutRemoteAddrHeader(headerName string) Configurator

WithoutRemoteAddrHeader removes an existing request header name that can be used to validate and parse the client's real IP.

Look `context.RemoteAddr()` for more.

func WithoutServerError

func WithoutServerError(errors ...error) Configurator

WithoutServerError will cause to ignore the matched "errors" from the main application's `Run/Listen` function.

Usage: err := app.Listen(":8080", iris.WithoutServerError(iris.ErrServerClosed)) will return `nil` if the server's error was `http/iris#ErrServerClosed`.

See `Configuration#IgnoreServerErrors []string` too.

Example: https://github.com/kataras/iris/tree/master/_examples/http-server/listen-addr/omit-server-errors

type Context

type Context = *context.Context

Context is the middle-man server's "object" for the clients.

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 by a Context.

type CookieOption

type CookieOption = context.CookieOption

CookieOption is the type of function that is accepted on context's methods like `SetCookieKV`, `RemoveCookie` and `SetCookie` as their (last) variadic input argument to amend the end cookie's form.

Any custom or builtin `CookieOption` is valid, see `CookiePath`, `CookieCleanPath`, `CookieExpires` and `CookieHTTPOnly` for more.

An alias for the `context.CookieOption`.

type Dir

type Dir = http.Dir

Dir implements FileSystem using the native file system restricted to a specific directory tree, can be passed to the `FileServer` function and `HandleDir` method. It's an alias of `http.Dir`.

type DirCacheOptions

type DirCacheOptions = router.DirCacheOptions

DirCacheOptions holds the options for the cached file system. See `DirOptions`.

type DirListRichOptions

type DirListRichOptions = router.DirListRichOptions

DirListRichOptions the options for the `DirListRich` helper function. A shortcut for the `router.DirListRichOptions`. Useful when `DirListRich` function is passed to `DirOptions.DirList` field.

type DirOptions

type DirOptions = router.DirOptions

DirOptions contains the optional settings that `FileServer` and `Party#HandleDir` can use to serve files and assets. A shortcut for the `router.DirOptions`, useful when `FileServer` or `HandleDir` is being used.

type ExecutionOptions

type ExecutionOptions = router.ExecutionOptions

ExecutionOptions is a set of default behaviors that can be changed in order to customize the execution flow of the routes' handlers with ease.

See `ExecutionRules` and `core/router/Party#SetExecutionRules` for more.

type ExecutionRules

type ExecutionRules = router.ExecutionRules

ExecutionRules gives control to the execution of the route handlers outside of the handlers themselves. Usage:

Party#SetExecutionRules(ExecutionRules {
  Done: ExecutionOptions{Force: true},
})

See `core/router/Party#SetExecutionRules` for more. Example: https://github.com/kataras/iris/tree/master/_examples/mvc/middleware/without-ctx-next

type Filter

type Filter = context.Filter

Filter is just a type of func(Handler) bool which reports whether an action must be performed based on the incoming request.

See `NewConditionalHandler` for more. An alias for the `context/Filter`.

type Handler

type Handler = context.Handler

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.

type JSON

type JSON = context.JSON

JSON the optional settings for JSON renderer.

It is an alias of the `context#JSON` type.

type Map

type Map = context.Map

A Map is an alias of map[string]interface{}.

type N

type N = context.N

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 `context/context.ContentSelector` interface.

An alias for the `context.N`.

type Party

type Party = router.Party

Party is just a group joiner of routes which have the same prefix and share same middleware(s) also. Party could also be named as 'Join' or 'Node' or 'Group' , Party chosen because it is fun.

Look the `core/router#APIBuilder` for its implementation.

A shortcut for the `core/router#Party`, useful when `PartyFunc` is being used.

type Problem

type Problem = context.Problem

Problem Details for HTTP APIs. Pass a Problem value to `context.Problem` to write an "application/problem+json" response.

Read more at: https://github.com/kataras/iris/wiki/Routing-error-handlers

It is an alias of the `context#Problem` type.

type ProblemOptions

type ProblemOptions = context.ProblemOptions

ProblemOptions the optional settings when server replies with a Problem. See `Context.Problem` method and `Problem` type for more details.

It is an alias of the `context#ProblemOptions` type.

type ProtoMarshalOptions

type ProtoMarshalOptions = context.ProtoMarshalOptions

ProtoMarshalOptions is a type alias for protojson.MarshalOptions.

type ProtoUnmarshalOptions

type ProtoUnmarshalOptions = context.ProtoUnmarshalOptions

ProtoUnmarshalOptions is a type alias for protojson.UnmarshalOptions.

type ResultHandler

type ResultHandler = hero.ResultHandler

ResultHandler describes the function type which should serve the "v" struct value. See `APIContainer.UseResultHandler`.

type Runner

type Runner func(*Application) error

Runner is just an interface which accepts the framework instance and returns an error.

It can be used to register a custom runner with `Run` in order to set the framework's server listen action.

Currently `Runner` is being used to declare the builtin server listeners.

See `Run` for more.

func Addr

func Addr(addr string, hostConfigs ...host.Configurator) Runner

Addr can be used as an argument for the `Run` method. It accepts a host address which is used to build a server and a listener which listens on that host and port.

Addr should have the form of host:port, i.e localhost:8080 or :8080.

Second argument is optional, it accepts one or more `func(*host.Configurator)` that are being executed on that specific host that this function will create to start the server. Via host configurators you can configure the back-end host supervisor, i.e to add events for shutdown, serve or error. An example of this use case can be found at: https://github.com/kataras/iris/blob/master/_examples/http-server/notify-on-shutdown/main.go Look at the `ConfigureHost` too.

See `Run` for more.

func AutoTLS

func AutoTLS(
	addr string,
	domain string, email string,
	hostConfigs ...host.Configurator) Runner

AutoTLS can be used as an argument for the `Run` method. It will start the Application's secure server using certifications created on the fly by the "autocert" golang/x package, so localhost may not be working, use it at "production" machine.

Addr should have the form of host:port, i.e mydomain.com:443.

The whitelisted domains are separated by whitespace in "domain" argument, i.e "iris-go.com", can be different than "addr". If empty, all hosts are currently allowed. This is not recommended, as it opens a potential attack where clients connect to a server by IP address and pretend to be asking for an incorrect host name. Manager will attempt to obtain a certificate for that host, incorrectly, eventually reaching the CA's rate limit for certificate requests and making it impossible to obtain actual certificates.

For an "e-mail" use a non-public one, letsencrypt needs that for your own security.

Note: `AutoTLS` will start a new server for you which will redirect all http versions to their https, including subdomains as well.

Last argument is optional, it accepts one or more `func(*host.Configurator)` that are being executed on that specific host that this function will create to start the server. Via host configurators you can configure the back-end host supervisor, i.e to add events for shutdown, serve or error. An example of this use case can be found at: https://github.com/kataras/iris/blob/master/_examples/http-server/notify-on-shutdown/main.go Look at the `ConfigureHost` too.

Usage: app.Run(iris.AutoTLS("iris-go.com:443", "iris-go.com www.iris-go.com", "mail@example.com"))

See `Run` and `core/host/Supervisor#ListenAndServeAutoTLS` for more.

func Listener

func Listener(l net.Listener, hostConfigs ...host.Configurator) Runner

Listener can be used as an argument for the `Run` method. It can start a server with a custom net.Listener via server's `Serve`.

Second argument is optional, it accepts one or more `func(*host.Configurator)` that are being executed on that specific host that this function will create to start the server. Via host configurators you can configure the back-end host supervisor, i.e to add events for shutdown, serve or error. An example of this use case can be found at: https://github.com/kataras/iris/blob/master/_examples/http-server/notify-on-shutdown/main.go Look at the `ConfigureHost` too.

See `Run` for more.

func Raw

func Raw(f func() error) Runner

Raw can be used as an argument for the `Run` method. It accepts any (listen) function that returns an error, this function should be block and return an error only when the server exited or a fatal error caused.

With this option you're not limited to the servers that iris can run by-default.

See `Run` for more.

func Server

func Server(srv *http.Server, hostConfigs ...host.Configurator) Runner

Server can be used as an argument for the `Run` method. It can start a server with a *http.Server.

Second argument is optional, it accepts one or more `func(*host.Configurator)` that are being executed on that specific host that this function will create to start the server. Via host configurators you can configure the back-end host supervisor, i.e to add events for shutdown, serve or error. An example of this use case can be found at: https://github.com/kataras/iris/blob/master/_examples/http-server/notify-on-shutdown/main.go Look at the `ConfigureHost` too.

See `Run` for more.

func TLS

func TLS(addr string, certFileOrContents, keyFileOrContents string, hostConfigs ...host.Configurator) Runner

TLS can be used as an argument for the `Run` method. It will start the Application's secure server.

Use it like you used to use the http.ListenAndServeTLS function.

Addr should have the form of host:port, i.e localhost:443 or :443. "certFileOrContents" & "keyFileOrContents" should be filenames with their extensions or raw contents of the certificate and the private key.

Last argument is optional, it accepts one or more `func(*host.Configurator)` that are being executed on that specific host that this function will create to start the server. Via host configurators you can configure the back-end host supervisor, i.e to add events for shutdown, serve or error. An example of this use case can be found at: https://github.com/kataras/iris/blob/master/_examples/http-server/notify-on-shutdown/main.go Look at the `ConfigureHost` too.

See `Run` for more.

type Supervisor

type Supervisor = host.Supervisor

Supervisor is a shortcut of the `host#Supervisor`. Used to add supervisor configurators on common Runners without the need of importing the `core/host` package.

type Tunnel

type Tunnel = tunnel.Tunnel

Tunnel is the Tunnels field of the TunnelingConfiguration structure.

type TunnelingConfiguration

type TunnelingConfiguration = tunnel.Configuration

TunnelingConfiguration contains configuration for the optional tunneling through ngrok feature. Note that the ngrok should be already installed at the host machine.

type UnmarshalerFunc

type UnmarshalerFunc = context.UnmarshalerFunc

UnmarshalerFunc a shortcut, an alias for the `context#UnmarshalerFunc` type which implements the `context#Unmarshaler` interface for reading request's body via custom decoders, most of them already implement the `context#UnmarshalerFunc` like the json.Unmarshal, xml.Unmarshal, yaml.Unmarshal and every library which follows the best practises and is aligned with the Go standards.

See 'context#UnmarshalBody` for more.

Example: https://github.com/kataras/iris/blob/master/_examples/request-body/read-custom-via-unmarshaler/main.go

type ViewEngine

type ViewEngine = context.ViewEngine

ViewEngine is an alias of `context.ViewEngine`. See HTML, Blocks, Django, Jet, Pug, Ace, Handlebars, Amber and e.t.c.

type XML

type XML = context.XML

XML the optional settings for XML renderer.

It is an alias of the `context#XML` type.

Directories

Path Synopsis
_examples
apidoc/yaag Module
cfg
ruleset
Package ruleset provides the basics rules which are being extended by rules.
Package ruleset provides the basics rules which are being extended by rules.
uri
core
memstore
Package memstore contains a store which is just a collection of key-value entries with immutability capabilities.
Package memstore contains a store which is just a collection of key-value entries with immutability capabilities.
Package i18n provides internalization and localization features for Iris.
Package i18n provides internalization and localization features for Iris.
handler
Package handler is the highest level module of the macro package which makes use the rest of the macro package, it is mainly used, internally, by the router package.
Package handler is the highest level module of the macro package which makes use the rest of the macro package, it is mainly used, internally, by the router package.
middleware
basicauth
Package basicauth provides http basic authentication via middleware.
Package basicauth provides http basic authentication via middleware.
jwt
logger
Package logger provides request logging via middleware.
Package logger provides request logging via middleware.
pprof
Package pprof provides native pprof support via middleware.
Package pprof provides native pprof support via middleware.
rate
Package rate implements rate limiter for Iris client requests.
Package rate implements rate limiter for Iris client requests.
recover
Package recover provides recovery for specific routes or for the whole app via middleware.
Package recover provides recovery for specific routes or for the whole app via middleware.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL