iris

package module
v12.1.9-0...-e9b74bf Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2020 License: BSD-3-Clause Imports: 34 Imported by: 0

README ยถ

News

Iris version 12.1.8 has been released!

The official Iris Command Line Interface will soon be near you in 2020!

Support your favorite web framework through Github Sponsors Program!

Iris Web Framework

build status FOSSA Status view examples chat

Iris is a fast, simple yet fully featured and very efficient web framework for Go.

It provides a beautifully expressive and easy to use foundation for your next website or API.

Learn what others saying about Iris and star this open-source project to support its potentials.

๐Ÿ“– Learning Iris

Quick start
# https://github.com/kataras/iris/wiki/Installation
$ go get github.com/kataras/iris/v12@latest
# assume the following code in example.go file
$ cat example.go
package main

import "github.com/kataras/iris/v12"

func main() {
    app := iris.New()
    app.Get("/ping", func(ctx iris.Context) {
        ctx.JSON(iris.Map{
            "message": "pong",
        })
    })

    app.Listen(":8080")
}
# run example.go and
# visit http://localhost:8080/ping on browser
$ go run example.go

Routing is powered by muxie, the most powerful and fastest trie-based software written in Go.

Iris contains extensive and thorough wiki making it easy to get started with the framework.

For a more detailed technical documentation you can head over to our godocs. And for executable code you can always visit the _examples repository's subdirectory.

Do you like to read while traveling?

Book cover

You can request a PDF version and online access of the E-Book today and be participated in the development of Iris.

๐Ÿ™Œ Contributing

We'd love to see your contribution to the Iris Web Framework! For more information about contributing to the Iris project please check the CONTRIBUTING.md file.

List of all Contributors

๐Ÿ›ก Security Vulnerabilities

If you discover a security vulnerability within Iris, please send an e-mail to iris-go@outlook.com. All security vulnerabilities will be promptly addressed.

๐Ÿ“ License

This project is licensed under the BSD 3-clause license, just like the Go project itself.

The project name "Iris" was inspired by the Greek mythology.

Documentation ยถ

Overview ยถ

Package iris implements the highest realistic performance, easy to learn Go web framework. Iris provides a beautifully expressive and easy to use foundation for your next website, API, or distributed app. Low-level handlers compatible with `net/http` and high-level fastest MVC implementation and handlers dependency injection. Easy to learn for new gophers and advanced features for experienced, it goes as far as you dive into it!

Source code and other details for the project are available at GitHub:

https://github.com/kataras/iris

Current Version ยถ

12.1.8

Installation ยถ

The only requirement is the Go Programming Language, at least version 1.13.

$ go get github.com/kataras/iris/v12@latest

Wiki:

https://github.com/kataras/iris/wiki

Examples:

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

Middleware:

https://github.com/kataras/iris/tree/master/middleware
https://github.com/iris-contrib/middleware

Home Page:

https://iris-go.com

Index ยถ

Constants ยถ

View Source
const (
	StatusContinue             = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols   = 101 // RFC 7231, 6.2.2
	StatusProcessing           = 102 // RFC 2518, 10.1
	StatusEarlyHints           = 103 // RFC 8297
	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5

	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusTooEarly                     = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

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 (
	MethodGet     = "GET"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodDelete  = "DELETE"
	MethodConnect = "CONNECT"
	MethodHead    = "HEAD"
	MethodPatch   = "PATCH"
	MethodOptions = "OPTIONS"
	MethodTrace   = "TRACE"
)

HTTP Methods copied from `net/http`.

View Source
const (
	// RouteOverride an existing route with the new one, the default rule.
	RouteOverride = router.RouteOverride
	// RouteSkip registering a new route twice.
	RouteSkip = router.RouteSkip
	// RouteError log when a route already exists, shown after the `Build` state,
	// server never starts.
	RouteError = router.RouteError
)

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 MethodNone = "NONE"

MethodNone is an iris-specific "virtual" method to store the "offline" routes.

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 = "12.1.8"

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

Variables ยถ

View Source
var (
	// HTML view engine.
	// Shortcut of the kataras/iris/view.HTML.
	HTML = view.HTML
	// Django view engine.
	// Shortcut of the kataras/iris/view.Django.
	Django = view.Django
	// Handlebars view engine.
	// Shortcut of the kataras/iris/view.Handlebars.
	Handlebars = view.Handlebars
	// Pug view engine.
	// Shortcut of the kataras/iris/view.Pug.
	Pug = view.Pug
	// Amber view engine.
	// Shortcut of the kataras/iris/view.Amber.
	Amber = view.Amber
	// Jet view engine.
	// Shortcut of the kataras/iris/view.Jet.
	Jet = view.Jet
)
View Source
var (
	// 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
	// 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
	// Gzip is a middleware which enables writing
	// using gzip compression, if client supports.
	//
	// A shortcut for the `context#Gzip`.
	Gzip = context.Gzip
	// 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/v12/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
	// 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
	// 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
	// CookieEncode is a `CookieOption`.
	// Provides encoding functionality when adding a cookie.
	// Accepts a `context#CookieEncoder` and sets the cookie's value to the encoded value.
	// Users of that is the `context#SetCookie` and `context#SetCookieKV`.
	//
	// Example: https://github.com/kataras/iris/tree/master/_examples/cookies/securecookie
	//
	// A shortcut for the `context#CookieEncode`.
	CookieEncode = context.CookieEncode
	// CookieDecode is a `CookieOption`.
	// Provides decoding functionality when retrieving a cookie.
	// Accepts a `context#CookieDecoder` and sets the cookie's value to the decoded value before return by the `GetCookie`.
	// User of that is the `context#GetCookie`.
	//
	// Example: https://github.com/kataras/iris/tree/master/_examples/cookies/securecookie
	//
	// A shortcut for the `context#CookieDecode`.
	CookieDecode = context.CookieDecode
	// IsErrPath can be used at `context#ReadForm`.
	// 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
	// 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
)
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 RegisterOnInterrupt = host.RegisterOnInterrupt

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`.

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 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 disables the AutoFireStatusCode setting.

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 ยถ

This section is empty.

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
	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/v12/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`, 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") 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/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 Configuration ยถ

type Configuration struct {

	// 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-listening/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 */

	// 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"`

	// 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"`
	// 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"`

	// 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 */

	// DisableAutoFireStatusCode if true then it turns off the http error status code handler automatic execution
	// from (`context.StatusCodeNotSuccessful`, defaults to < 200 || >= 400).
	// If that is false then for a direct error firing, then call the "context#FireStatusCode(statusCode)" manually.
	//
	// By-default a custom http error handler will be fired when "context.StatusCode(code)" called,
	// code should be equal with the result of the the `context.StatusCodeNotSuccessful` in order to be received as an "http error handler".
	//
	// Developer may want this option to set as true in order to manually call the
	// error handlers when needed via "context#FireStatusCode(< 200 || >= 400)".
	// HTTP Custom error handlers are being registered via app.OnErrorCode(code, handler)".
	//
	// Defaults to false.
	DisableAutoFireStatusCode bool `json:"disableAutoFireStatusCode,omitempty" yaml:"DisableAutoFireStatusCode" toml:"DisableAutoFireStatusCode"`

	// 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"`

	// GetViewLayoutContextKey is the key of the context's user values' key
	// which is being used to set the template
	// layout from a middleware or the main handler.
	// Overrides the parent's or the configuration's.
	//
	// Defaults to "iris.ViewLayout"
	ViewLayoutContextKey string `json:"viewLayoutContextKey,omitempty" yaml:"ViewLayoutContextKey" toml:"ViewLayoutContextKey"`
	// GetViewDataContextKey is the key of the context's user values' key
	// which is being used to set the template
	// binding data from a middleware or the main handler.
	//
	// Defaults to "iris.viewData"
	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", inneed you
	// can allow the `ctx.RemoteAddr()` to use any header
	// that the client may sent.
	//
	// Defaults to an empty map but an example usage is:
	// RemoteAddrHeaders {
	//	"X-Real-Ip":             true,
	//  "X-Forwarded-For":       true,
	// 	"CF-Connecting-IP": 	 true,
	//	}
	//
	// Look `context.RemoteAddr()` for more.
	RemoteAddrHeaders map[string]bool `json:"remoteAddrHeaders,omitempty" yaml:"RemoteAddrHeaders" toml:"RemoteAddrHeaders"`

	// RemoteAddrPrivateSubnets defines the private sub-networks.
	// They are used to be compared against
	// IP Addresses fetched through `RemoteAddrHeaders` or `Request.RemoteAddr`.
	// For details please navigate through: https://github.com/kataras/iris/issues/1453
	// Defaults to an empty slice, usage:
	//
	// RemoteAddrPrivateSubnets {
	//	{Start: "10.0.0.0", End: "10.255.255.255"},
	//  {Start: "100.64.0.0", End: "100.127.255.255"},
	//	}
	//
	// Look `context.RemoteAddr()` for more.
	RemoteAddrPrivateSubnets []netutil.IPRange `json:"remoteAddrPrivateSubnets" yaml:"RemoteAddrPrivateSubnets" toml:"RemoteAddrPrivateSubnets"`
	// 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 a non-nil empty map.
	Other map[string]interface{} `json:"other,omitempty" yaml:"Other" toml:"Other"`
	// contains filtered or unexported fields
}

Configuration the whole configuration for an iris instance these can be passed via options also, look at the top of this file(configuration.go). Configuration is a valid OptionSetter.

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 doesn't exists 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 doesn't exists 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 Configuration#Charset, the character encoding for various rendering used for templates and the rest of the responses.

func (Configuration) GetDisableAutoFireStatusCode ยถ

func (c Configuration) GetDisableAutoFireStatusCode() bool

GetDisableAutoFireStatusCode returns the Configuration#DisableAutoFireStatusCode. Returns true when the http error status code handler automatic execution turned off.

func (Configuration) GetDisableBodyConsumptionOnUnmarshal ยถ

func (c Configuration) GetDisableBodyConsumptionOnUnmarshal() bool

GetDisableBodyConsumptionOnUnmarshal returns the Configuration#GetDisableBodyConsumptionOnUnmarshal, manages the reading behavior of the context's body readers/binders. If returns true then the body consumption by the `context.UnmarshalBody/ReadJSON/ReadXML` is disabled.

By-default io.ReadAll` is used to read the body from the `context.Request.Body which is an `io.ReadCloser`, if this field set to true then a new buffer will be created to read from and the request body. The body will not be changed and existing data before the context.UnmarshalBody/ReadJSON/ReadXML will be not consumed.

func (Configuration) GetDisablePathCorrection ยถ

func (c Configuration) GetDisablePathCorrection() bool

GetDisablePathCorrection returns the Configuration#DisablePathCorrection. 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.

func (Configuration) GetDisablePathCorrectionRedirection ยถ

func (c Configuration) GetDisablePathCorrectionRedirection() bool

GetDisablePathCorrectionRedirection returns the Configuration#DisablePathCorrectionRedirection field. If DisablePathCorrectionRedirection set to true then it will fire the handler of the matching route without the last slash ("/") instead of send a redirection status.

func (Configuration) GetEnableOptimizations ยถ

func (c Configuration) GetEnableOptimizations() bool

GetEnableOptimizations returns whether the application has performance optimizations enabled.

func (Configuration) GetEnablePathEscape ยถ

func (c Configuration) GetEnablePathEscape() bool

GetEnablePathEscape is the Configuration#EnablePathEscape, returns true when its escapes the path, the named parameters (if any).

func (Configuration) GetFireMethodNotAllowed ยถ

func (c Configuration) GetFireMethodNotAllowed() bool

GetFireMethodNotAllowed returns the Configuration#FireMethodNotAllowed.

func (Configuration) GetForceLowercaseRouting ยถ

func (c Configuration) GetForceLowercaseRouting() bool

GetForceLowercaseRouting returns the value of the `ForceLowercaseRouting` setting.

func (Configuration) GetLocaleContextKey ยถ

func (c Configuration) GetLocaleContextKey() string

GetLocaleContextKey returns the configuration's LocaleContextKey value, used for i18n.

func (Configuration) GetOther ยถ

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

GetOther returns the Configuration#Other map.

func (Configuration) GetPostMaxMemory ยถ

func (c Configuration) GetPostMaxMemory() int64

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

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

func (Configuration) GetRemoteAddrHeaders ยถ

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

GetRemoteAddrHeaders returns 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", inneed you can allow the `ctx.RemoteAddr()` to use any header that the client may sent.

Defaults to an empty map but an example usage is:

RemoteAddrHeaders {
	"X-Real-Ip":             true,
 "X-Forwarded-For":       true,
	"CF-Connecting-IP": 	 true,
	}

Look `context.RemoteAddr()` for more.

func (Configuration) GetRemoteAddrPrivateSubnets ยถ

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

GetRemoteAddrPrivateSubnets returns the configuration's private sub-networks. They are used to be compared against IP Addresses fetched through `RemoteAddrHeaders` or `Request.RemoteAddr`. For details please navigate through: https://github.com/kataras/iris/issues/1453 Defaults to an empty slice, usage:

RemoteAddrPrivateSubnets {
	{Start: "10.0.0.0", End: "10.255.255.255"},
 {Start: "100.64.0.0", End: "100.127.255.255"},
	}

Look `context.RemoteAddr()` for more.

func (Configuration) GetTimeFormat ยถ

func (c Configuration) GetTimeFormat() string

GetTimeFormat returns the Configuration#TimeFormat, format for any kind of datetime parsing.

func (Configuration) GetVHost ยถ

func (c Configuration) GetVHost() string

GetVHost returns the non-exported vhost config field.

If original addr ended with :443 or :80, it will return the host without the port. If original addr was :https or :http, it will return localhost. If original addr was 0.0.0.0, it will return localhost.

func (Configuration) GetViewDataContextKey ยถ

func (c Configuration) GetViewDataContextKey() string

GetViewDataContextKey returns the key of the context's user values' key which is being used to set the template binding data from a middleware or the main handler.

func (Configuration) GetViewLayoutContextKey ยถ

func (c Configuration) GetViewLayoutContextKey() string

GetViewLayoutContextKey returns the key of the context's user values' key which is being used to set the template layout from a middleware or the main handler. Overrides the parent's or the configuration's.

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 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 if you prefer.

func WithRemoteAddrHeader ยถ

func WithRemoteAddrHeader(headerName string) Configurator

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

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", inneed you can allow the `ctx.RemoteAddr()` to use any header that the client may sent.

Defaults to an empty map but an example usage is: WithRemoteAddrHeader("X-Forwarded-For")

Look `context.RemoteAddr()` for more.

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 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 disables an existing request header name that can be used to validate and parse the client's real IP.

Keep note that RemoteAddrHeaders is already defaults to an empty map so you don't have to call this Configurator if you didn't add allowed headers via configuration or via `WithRemoteAddrHeader` before.

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` 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-listening/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/Context#CookieOption`.

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/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 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-listening/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-listening/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-listening/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-listening/notify-on-shutdown/main.go Look at the `ConfigureHost` too.

See `Run` for more.

func TLS ยถ

func TLS(addr string, certFile, keyFile 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. CertFile & KeyFile should be filenames with their extensions.

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-listening/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 struct {
	// Name is the only one required field,
	// it is used to create and close tunnels, e.g. "MyApp".
	// If this field is not empty then ngrok tunnels will be created
	// when the iris app is up and running.
	Name string `json:"name" yaml:"Name" toml:"Name"`
	// Addr is basically optionally as it will be set through
	// Iris built-in Runners, however, if `iris.Raw` is used
	// then this field should be set of form 'hostname:port'
	// because framework cannot be aware
	// of the address you used to run the server on this custom runner.
	Addr string `json:"addr,omitempty" yaml:"Addr" toml:"Addr"`
}

Tunnel is the Tunnels field of the TunnelingConfiguration structure.

type TunnelingConfiguration ยถ

type TunnelingConfiguration struct {
	// AuthToken field is optionally and can be used
	// to authenticate the ngrok access.
	// ngrok authtoken <YOUR_AUTHTOKEN>
	AuthToken string `json:"authToken,omitempty" yaml:"AuthToken" toml:"AuthToken"`

	// Bin is the system binary path of the ngrok executable file.
	// If it's empty then the framework will try to find it through system env variables.
	Bin string `json:"bin,omitempty" yaml:"Bin" toml:"Bin"`

	// WebUIAddr is the web interface address of an already-running ngrok instance.
	// Iris will try to fetch the default web interface address(http://127.0.0.1:4040)
	// to determinate if a ngrok instance is running before try to start it manually.
	// However if a custom web interface address is used,
	// this field must be set e.g. http://127.0.0.1:5050.
	WebInterface string `json:"webInterface,omitempty" yaml:"WebInterface" toml:"WebInterface"`

	// Region is optionally, can be used to set the region which defaults to "us".
	// Available values are:
	// "us" for United States
	// "eu" for Europe
	// "ap" for Asia/Pacific
	// "au" for Australia
	// "sa" for South America
	// "jp" forJapan
	// "in" for India
	Region string `json:"region,omitempty" yaml:"Region" toml:"Region"`

	// Tunnels the collection of the tunnels.
	// One tunnel per Iris Host per Application, usually you only need one.
	Tunnels []Tunnel `json:"tunnels" yaml:"Tunnels" toml:"Tunnels"`
}

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/http_request/read-custom-via-unmarshaler/main.go

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
cache/client-side
Package main shows how you can use the `WriteWithExpiration` based on the "modtime", if it's newer than the request header then it will refresh the contents, otherwise will let the client (99.9% the browser) to handle the cache mechanism, it's faster than iris.Cache because server-side has nothing to do and no need to store the responses in the memory.
Package main shows how you can use the `WriteWithExpiration` based on the "modtime", if it's newer than the request header then it will refresh the contents, otherwise will let the client (99.9% the browser) to handle the cache mechanism, it's faster than iris.Cache because server-side has nothing to do and no need to store the responses in the memory.
experimental-handlers/csrf
This middleware provides Cross-Site Request Forgery protection.
This middleware provides Cross-Site Request Forgery protection.
experimental-handlers/jwt
iris provides some basic middleware, most for your learning curve.
iris provides some basic middleware, most for your learning curve.
http-listening/listen-letsencrypt
Package main provide one-line integration with letsencrypt.org
Package main provide one-line integration with letsencrypt.org
http_request/read-form
package main contains an example on how to use the ReadForm, but with the same way you can do the ReadJSON & ReadJSON
package main contains an example on how to use the ReadForm, but with the same way you can do the ReadJSON & ReadJSON
http_request/read-json-struct-validation
Package main shows the validator(latest, version 10) integration with Iris' Context methods of `ReadJSON`, `ReadXML`, `ReadMsgPack`, `ReadYAML`, `ReadForm`, `ReadQuery`, `ReadBody`.
Package main shows the validator(latest, version 10) integration with Iris' Context methods of `ReadJSON`, `ReadXML`, `ReadMsgPack`, `ReadYAML`, `ReadForm`, `ReadQuery`, `ReadBody`.
http_request/read-query
package main contains an example on how to use the ReadForm, but with the same way you can do the ReadJSON & ReadJSON
package main contains an example on how to use the ReadForm, but with the same way you can do the ReadJSON & ReadJSON
http_responsewriter/content-negotiation
Package main contains three different ways to render content based on the client's accepted.
Package main contains three different ways to render content based on the client's accepted.
Code generated by hero.
http_responsewriter/sse
Package main shows how to send continuous event messages to the clients through SSE via a broker.
Package main shows how to send continuous event messages to the clients through SSE via a broker.
mvc/grpc-compatible/grpc-client
Package main implements a client for Greeter service.
Package main implements a client for Greeter service.
mvc/middleware
Package main shows how you can add middleware to an mvc Application, simply by using its `Router` which is a sub router(an iris.Party) of the main iris app.
Package main shows how you can add middleware to an mvc Application, simply by using its `Router` which is a sub router(an iris.Party) of the main iris app.
mvc/middleware/per-method
If you want to use it as middleware for the entire controller you can use its router which is just a sub router to add it as you normally do with standard API: I'll show you 4 different methods for adding a middleware into an mvc application, all of those 4 do exactly the same thing, select what you prefer, I prefer the last code-snippet when I need the middleware to be registered somewhere else as well, otherwise I am going with the first one: โ€œ`go // 1 mvc.Configure(app.Party("/user"), func(m *mvc.Application) { m.Router.Use(cache.Handler(10*time.Second)) }) โ€œ` โ€œ`go // 2 // same: userRouter := app.Party("/user") userRouter.Use(cache.Handler(10*time.Second)) mvc.Configure(userRouter, ...) โ€œ` โ€œ`go // 3 // same: userRouter := app.Party("/user", cache.Handler(10*time.Second)) mvc.Configure(userRouter, ...) โ€œ` โ€œ`go // 4 // same: app.PartyFunc("/user", func(r iris.Party){ r.Use(cache.Handler(10*time.Second)) mvc.Configure(r, ...) }) โ€œ` If you want to use a middleware for a single route, for a single controller's method that is already registered by the engine and not by custom `Handle` (which you can add the middleware there on the last parameter) and it's not depend on the `Next Handler` to do its job then you just call it on the method: โ€œ`go var myMiddleware := myMiddleware.New(...) // this should return an iris/context.Handler type UserController struct{} func (c *UserController) GetSomething(ctx iris.Context) { // ctx.Proceed checks if myMiddleware called `ctx.Next()` // inside it and returns true if so, otherwise false.
If you want to use it as middleware for the entire controller you can use its router which is just a sub router to add it as you normally do with standard API: I'll show you 4 different methods for adding a middleware into an mvc application, all of those 4 do exactly the same thing, select what you prefer, I prefer the last code-snippet when I need the middleware to be registered somewhere else as well, otherwise I am going with the first one: โ€œ`go // 1 mvc.Configure(app.Party("/user"), func(m *mvc.Application) { m.Router.Use(cache.Handler(10*time.Second)) }) โ€œ` โ€œ`go // 2 // same: userRouter := app.Party("/user") userRouter.Use(cache.Handler(10*time.Second)) mvc.Configure(userRouter, ...) โ€œ` โ€œ`go // 3 // same: userRouter := app.Party("/user", cache.Handler(10*time.Second)) mvc.Configure(userRouter, ...) โ€œ` โ€œ`go // 4 // same: app.PartyFunc("/user", func(r iris.Party){ r.Use(cache.Handler(10*time.Second)) mvc.Configure(r, ...) }) โ€œ` If you want to use a middleware for a single route, for a single controller's method that is already registered by the engine and not by custom `Handle` (which you can add the middleware there on the last parameter) and it's not depend on the `Next Handler` to do its job then you just call it on the method: โ€œ`go var myMiddleware := myMiddleware.New(...) // this should return an iris/context.Handler type UserController struct{} func (c *UserController) GetSomething(ctx iris.Context) { // ctx.Proceed checks if myMiddleware called `ctx.Next()` // inside it and returns true if so, otherwise false.
mvc/middleware/without-ctx-next
Package main is a simple example of the behavior change of the execution flow of the handlers, normally we need the `ctx.Next()` to call the next handler in a route's handler chain, but with the new `ExecutionRules` we can change this default behavior.
Package main is a simple example of the behavior change of the execution flow of the handlers, normally we need the `ctx.Next()` to call the next handler in a route's handler chain, but with the new `ExecutionRules` we can change this default behavior.
mvc/regexp
Package main shows how to match "/xxx.json" in MVC handler.
Package main shows how to match "/xxx.json" in MVC handler.
orm/xorm
Package main shows how an orm can be used within your web app it just inserts a column and select the first.
Package main shows how an orm can be used within your web app it just inserts a column and select the first.
routing/macros
Package main shows how you can register a custom parameter type and macro functions that belongs to it.
Package main shows how you can register a custom parameter type and macro functions that belongs to it.
subdomains/redirect
Package main shows how to register a simple 'www' subdomain, using the `app.WWW` method, which will register a router wrapper which will redirect all 'mydomain.com' requests to 'www.mydomain.com'.
Package main shows how to register a simple 'www' subdomain, using the `app.WWW` method, which will register a router wrapper which will redirect all 'mydomain.com' requests to 'www.mydomain.com'.
subdomains/single
Package main register static subdomains, simple as parties, check ./hosts if you use windows
Package main register static subdomains, simple as parties, check ./hosts if you use windows
subdomains/wildcard
Package main an example on how to catch dynamic subdomains - wildcard.
Package main an example on how to catch dynamic subdomains - wildcard.
tutorial/url-shortener
Package main shows how you can create a simple URL Shortener.
Package main shows how you can create a simple URL Shortener.
view/embedding-templates-into-app
Code generated for package main by go-bindata DO NOT EDIT.
Code generated for package main by go-bindata DO NOT EDIT.
view/template_html_3
Package main an example on how to naming your routes & use the custom 'url path' HTML Template Engine, same for other template engines.
Package main an example on how to naming your routes & use the custom 'url path' HTML Template Engine, same for other template engines.
view/template_html_4
Package main an example on how to naming your routes & use the custom 'url' HTML Template Engine, same for other template engines.
Package main an example on how to naming your routes & use the custom 'url' HTML Template Engine, same for other template engines.
view/template_jet_0
Package main shows how to use jet template parser with ease using the Iris built-in Jet view engine.
Package main shows how to use jet template parser with ease using the Iris built-in Jet view engine.
view/template_jet_1_embedded
Package main shows how to use jet templates embedded in your application with ease using the Iris built-in Jet view engine.
Package main shows how to use jet templates embedded in your application with ease using the Iris built-in Jet view engine.
view/template_jet_2
Package main an example on how to naming your routes & use the custom 'url path' Jet Template Engine.
Package main an example on how to naming your routes & use the custom 'url path' Jet Template Engine.
view/template_pug_1
Package main shows an example of pug actions based on https://github.com/Joker/jade/tree/master/example/actions
Package main shows an example of pug actions based on https://github.com/Joker/jade/tree/master/example/actions
view/template_pug_3
Code generated for package main by go-bindata DO NOT EDIT.
Code generated for package main by go-bindata DO NOT EDIT.
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.
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.
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