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/radiantrfid/iris
Current Version ¶
11.2.8
Installation ¶
The only requirement is the Go Programming Language, at least version 1.12.
$ go get github.com/radiantrfid/iris@master
Wiki:
https://github.com/radiantrfid/iris/wiki
Examples:
https://github.com/radiantrfid/iris/tree/master/_examples
Middleware:
https://github.com/radiantrfid/iris/tree/master/middleware https://github.com/iris-contrib/middleware
Home Page:
https://iris-go.com
Index ¶
- Constants
- Variables
- func WithTunneling(app *Application)
- type Application
- func (app *Application) Build() error
- func (app *Application) ConfigurationReadOnly() context.ConfigurationReadOnly
- func (app *Application) Configure(configurators ...Configurator) *Application
- func (app *Application) ConfigureHost(configurators ...host.Configurator) *Application
- func (app *Application) Logger() *golog.Logger
- func (app *Application) NewHost(srv *http.Server) *host.Supervisor
- func (app *Application) RegisterView(viewEngine view.Engine)
- func (app *Application) Run(serve Runner, withOrWithout ...Configurator) error
- func (app *Application) Shutdown(ctx stdContext.Context) error
- func (app *Application) SubdomainRedirect(from, to router.Party) router.Party
- func (app *Application) View(writer io.Writer, filename string, layout string, bindingData interface{}) error
- func (app *Application) WWW() router.Party
- type Configuration
- func (c Configuration) GetCharset() string
- func (c Configuration) GetDisableAutoFireStatusCode() bool
- func (c Configuration) GetDisableBodyConsumptionOnUnmarshal() bool
- func (c Configuration) GetDisablePathCorrection() bool
- func (c Configuration) GetDisablePathCorrectionRedirection() bool
- func (c Configuration) GetEnableOptimizations() bool
- func (c Configuration) GetEnablePathEscape() bool
- func (c Configuration) GetFireMethodNotAllowed() bool
- func (c Configuration) GetOther() map[string]interface{}
- func (c Configuration) GetPostMaxMemory() int64
- func (c Configuration) GetRemoteAddrHeaders() map[string]bool
- func (c Configuration) GetTimeFormat() string
- func (c Configuration) GetTranslateFunctionContextKey() string
- func (c Configuration) GetTranslateLanguageContextKey() string
- func (c Configuration) GetVHost() string
- func (c Configuration) GetViewDataContextKey() string
- func (c Configuration) GetViewLayoutContextKey() string
- type Configurator
- func WithCharset(charset string) Configurator
- func WithConfiguration(c Configuration) Configurator
- func WithOtherValue(key string, val interface{}) Configurator
- func WithPostMaxMemory(limit int64) Configurator
- func WithRemoteAddrHeader(headerName string) Configurator
- func WithTimeFormat(timeformat string) Configurator
- func WithoutRemoteAddrHeader(headerName string) Configurator
- func WithoutServerError(errors ...error) Configurator
- type Context
- type CookieOption
- type DirOptions
- type ExecutionOptions
- type ExecutionRules
- type Filter
- type Handler
- type JSON
- type Map
- type N
- type Party
- type Problem
- type ProblemOptions
- type Runner
- func Addr(addr string, hostConfigs ...host.Configurator) Runner
- func AutoTLS(addr string, domain string, email string, hostConfigs ...host.Configurator) Runner
- func Listener(l net.Listener, hostConfigs ...host.Configurator) Runner
- func Raw(f func() error) Runner
- func Server(srv *http.Server, hostConfigs ...host.Configurator) Runner
- func TLS(addr string, certFile, keyFile string, hostConfigs ...host.Configurator) Runner
- type Supervisor
- type Tunnel
- type TunnelingConfiguration
- type UnmarshalerFunc
- type XML
Constants ¶
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 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 StatusInternalServerError = 500 // RFC 7231, 6.6.1 StatusNotImplemented = 501 // RFC 7231, 6.6.2 StatusBadGateway = 502 // RFC 7231, 6.6.3 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.
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`.
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.
const MethodNone = "NONE"
MethodNone is an iris-specific "virtual" method to store the "offline" routes.
const NoLayout = view.NoLayout
NoLayout to disable layout for a particular template file A shortcut for the `view#NoLayout`.
const Version = "11.2.8"
Version is the current version number of the Iris Web Framework.
Variables ¶
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 )
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/radiantrfid/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/{f:path}", h) // app.Head("/static/{f: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/radiantrfid/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/radiantrfid/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 // 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/radiantrfid/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/radiantrfid/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 retruns 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 )
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`.
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`.
var WithFireMethodNotAllowed = func(app *Application) { app.config.FireMethodNotAllowed = true }
WithFireMethodNotAllowed enanbles the FireMethodNotAllowed setting.
See `Configuration`.
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)`.
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`.
var WithPathEscape = func(app *Application) { app.config.EnablePathEscape = true }
WithPathEscape enanbles the PathEscape setting.
See `Configuration`.
var WithoutAutoFireStatusCode = func(app *Application) { app.config.DisableAutoFireStatusCode = true }
WithoutAutoFireStatusCode disables the AutoFireStatusCode setting.
See `Configuration`.
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.
var WithoutBodyConsumptionOnUnmarshal = func(app *Application) { app.config.DisableBodyConsumptionOnUnmarshal = true }
WithoutBodyConsumptionOnUnmarshal disables BodyConsumptionOnUnmarshal setting.
See `Configuration`.
var WithoutInterruptHandler = func(app *Application) { app.config.DisableInterruptHandler = true }
WithoutInterruptHandler disables the automatic graceful server shutdown when control/cmd+C pressed.
var WithoutPathCorrection = func(app *Application) { app.config.DisablePathCorrection = true }
WithoutPathCorrection disables the PathCorrection setting.
See `Configuration`.
var WithoutPathCorrectionRedirection = func(app *Application) { app.config.DisablePathCorrection = false app.config.DisablePathCorrectionRedirection = true }
WithoutPathCorrectionRedirection disables the PathCorrectionRedirection setting.
See `Configuration`.
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 WithTunneling ¶
func WithTunneling(app *Application)
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{ ...}}}`.
Types ¶
type Application ¶
type Application struct { // routing embedded | exposing APIBuilder's and Router's public API. *router.APIBuilder *router.Router ContextPool *context.Pool // 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, unlike `New`, recovers on panics and logs the incoming http requests.
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.
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) 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 standar *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. 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/radiantrfid/iris/tree/master/_examples/subdomains/redirect
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/radiantrfid/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 corrects and redirects or executes 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, // (permant)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, the named parameters (if any). // Change to false it if you want something like this https://github.com/radiantrfid/iris/issues/135 to work // // 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"` // 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. // // TranslateLanguageContextKey & TranslateFunctionContextKey are used by i18n handlers/middleware // currently we have only one: https://github.com/radiantrfid/iris/tree/master/middleware/i18n. // // Defaults to "iris.translate" and "iris.language" TranslateFunctionContextKey string `json:"translateFunctionContextKey,omitempty" yaml:"TranslateFunctionContextKey" toml:"TranslateFunctionContextKey"` // TranslateLanguageContextKey used for i18n. // // Defaults to "iris.language" TranslateLanguageContextKey string `json:"translateLanguageContextKey,omitempty" yaml:"TranslateLanguageContextKey" toml:"TranslateLanguageContextKey"` // 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"` // 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 corrects and redirects the requested path to the registered path for example, if /home/ path is requested but no handler for this Route found, then the Router checks if /home handler exists, if yes, (permant)redirects the client to the correct path /home.
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) 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) GetTimeFormat ¶
func (c Configuration) GetTimeFormat() string
GetTimeFormat returns the Configuration#TimeFormat, format for any kind of datetime parsing.
func (Configuration) GetTranslateFunctionContextKey ¶
func (c Configuration) GetTranslateFunctionContextKey() string
GetTranslateFunctionContextKey returns the configuration's TranslateFunctionContextKey value, used for i18n.
func (Configuration) GetTranslateLanguageContextKey ¶
func (c Configuration) GetTranslateLanguageContextKey() string
GetTranslateLanguageContextKey returns the configuration's TranslateLanguageContextKey value, used for i18n.
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.Run(iris.Addr(":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 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.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed)) will return `nil` if the server's error was `http/iris#ErrServerClosed`.
See `Configuration#IgnoreServerErrors []string` too.
type Context ¶
Context is the midle-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/radiantrfid/iris/tree/master/_examples/mvc/middleware/without-ctx-next
type Filter ¶
Filter is just a type of func(Handler) bool which reports whether an action must be performed based on the incoming request.
See `NewConditionalHandler` for more. An alias for the `context/Filter`.
type 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 ¶
JSON the optional settings for JSON renderer.
It is an alias of the `context#JSON` type.
type 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 ¶
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 ¶
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/radiantrfid/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 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/radiantrfid/iris/blob/master/_examples/http-listening/notify-on-shutdown/main.go Look at the `ConfigureHost` too.
See `Run` for more.
func AutoTLS ¶
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/radiantrfid/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/radiantrfid/iris/blob/master/_examples/http-listening/notify-on-shutdown/main.go Look at the `ConfigureHost` too.
See `Run` for more.
func Raw ¶
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/radiantrfid/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/radiantrfid/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.
Directories ¶
Path | Synopsis |
---|---|
_benchmarks
|
|
_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 9) integration with Iris.
|
Package main shows the validator(latest, version 9) integration with Iris. |
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. |
http_responsewriter/herotemplate/template
Code generated by hero.
|
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/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/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_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 |
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. |
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. |
di
Package di provides dependency injection for the Iris Hero and Iris MVC new features.
|
Package di provides dependency injection for the Iris Hero and Iris MVC new features. |
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. |
i18n
Package i18n provides internalization and localization via middleware.
|
Package i18n provides internalization and localization 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. |
Package typescript provides a typescript compiler with hot-reloader and optionally a cloud-based editor, called 'alm-tools'.
|
Package typescript provides a typescript compiler with hot-reloader and optionally a cloud-based editor, called 'alm-tools'. |