Documentation ¶
Overview ¶
Package iris the fastest go web framework in (this) Earth. /NOTE: When you see 'framework' or 'station' we mean the Iris web framework's main implementation.
Basic usage ----------------------------------------------------------------------
package main
import "gopkg.in/kataras/iris.v4"
func main() { iris.Get("/hi_json", func(c *iris.Context) { c.JSON(iris.StatusOK, iris.Map{ "Name": "Iris", "Released": "13 March 2016", }) }) iris.ListenLETSENCRYPT("mydomain.com") }
----------------------------------------------------------------------
package main
import "gopkg.in/kataras/iris.v4"
func main() { s1 := iris.New() s1.Get("/hi_json", func(c *iris.Context) { c.JSON(200, iris.Map{ "Name": "Iris", "Released": "13 March 2016", }) }) s2 := iris.New() s2.Get("/hi_raw_html", func(c *iris.Context) { c.HTML(iris.StatusOK, "<b> Iris </b> welcomes <h1>you!</h1>") }) go s1.Listen(":8080") s2.Listen(":1993") }
-----------------------------DOCUMENTATION---------------------------- ----------------------------_______________--------------------------- For middleware, template engines, response engines, sessions, websockets, mails, subdomains, dynamic subdomains, routes, party of subdomains & routes, ssh and much more visit https://www.gitbook.com/book/kataras/iris/details
Index ¶
- Constants
- Variables
- func API(path string, restAPI HandlerAPI, middleware ...HandlerFunc)
- func Any(registedPath string, handlersFn ...HandlerFunc)
- func Build()
- func CERT(addr string, cert tls.Certificate) (net.Listener, error)
- func CheckForUpdates(force bool)
- func Close() error
- func DecodeFasthttpURL(path string) string
- func DecodeURL(uri string) string
- func DisableKeepalive(val bool)
- func EmitError(statusCode int, ctx *Context)
- func HTMLEscape(s string) string
- func InvalidateCache(ctx *Context)
- func IsRunning() bool
- func LETSENCRYPT(addr string, cacheFileOptional ...string) (net.Listener, error)
- func LETSENCRYPTPROD(addr string, cacheDirOptional ...string) (net.Listener, error)
- func Listen(addr string)
- func ListenLETSENCRYPT(addr string, cacheFileOptional ...string)
- func ListenTLS(addr string, certFile string, keyFile string)
- func ListenUNIX(addr string, mode os.FileMode)
- func Must(err error)
- func OnError(statusCode int, handlerFn HandlerFunc)
- func ParseHost(addr string) string
- func ParseHostname(addr string) string
- func ParsePort(addr string) int
- func ParseScheme(domain string) string
- func Path(routeName string, args ...interface{}) string
- func Proxy(proxyAddr string, redirectSchemeAndHost string) func() error
- func ReleaseCtx(ctx *Context)
- func Reserve() error
- func ResetDefault()
- func RouteConflicts(r *route, with string) bool
- func SerializeToString(keyOrContentType string, obj interface{}, options ...map[string]interface{}) string
- func Serve(ln net.Listener) error
- func Set(setters ...OptionSetter)
- func StatusText(code int) string
- func TCP4(addr string) (net.Listener, error)
- func TLS(addr, certFile, keyFile string) (net.Listener, error)
- func TemplateSourceString(src string, pageContext interface{}) string
- func TemplateString(templateFile string, pageContext interface{}, ...) string
- func UNIX(addr string, mode os.FileMode) (net.Listener, error)
- func URL(routeName string, args ...interface{}) (url string)
- func Use(handlers ...Handler)
- func UseFunc(handlersFn ...HandlerFunc)
- func UseGlobal(handlers ...Handler)
- func UseGlobalFunc(handlersFn ...HandlerFunc)
- func UsePreRender(pre PreRender)
- func UseSerializer(forContentType string, e serializer.Serializer)
- func UseSessionDB(db sessions.Database)
- func UseTemplate(e template.Engine) *template.Loader
- type BodyDecoder
- type Configuration
- type Context
- func (ctx *Context) Data(status int, v []byte) error
- func (ctx *Context) Do()
- func (ctx *Context) EmitError(statusCode int)
- func (ctx *Context) FormValueString(name string) string
- func (ctx *Context) FormValues(name string) []string
- func (ctx *Context) Framework() *Framework
- func (ctx *Context) Get(key string) interface{}
- func (ctx *Context) GetCookie(name string) (val string)
- func (ctx *Context) GetFlash(key string) (string, error)
- func (ctx *Context) GetFlashes() map[string]string
- func (ctx *Context) GetFmt(key string) func(format string, args ...interface{}) string
- func (ctx *Context) GetHandlerName() string
- func (ctx *Context) GetInt(key string) (int, error)
- func (ctx *Context) GetRequestCtx() *fasthttp.RequestCtx
- func (ctx *Context) GetString(key string) string
- func (ctx *Context) Gzip(b []byte, status int)
- func (ctx *Context) HTML(status int, htmlContents string)
- func (ctx *Context) HostString() string
- func (ctx *Context) InvalidateCache()
- func (ctx *Context) IsAjax() bool
- func (ctx *Context) IsStopped() bool
- func (ctx *Context) JSON(status int, v interface{}) error
- func (ctx *Context) JSONP(status int, callback string, v interface{}) error
- func (ctx *Context) Log(format string, a ...interface{})
- func (ctx *Context) Markdown(status int, markdown string)
- func (ctx *Context) MarkdownString(markdownText string) string
- func (ctx *Context) MaxAge() int64
- func (ctx *Context) MethodString() string
- func (ctx *Context) MustRender(name string, binding interface{}, options ...map[string]interface{})
- func (ctx *Context) Next()
- func (ctx *Context) NotFound()
- func (ctx *Context) Panic()
- func (ctx *Context) Param(key string) string
- func (ctx *Context) ParamInt(key string) (int, error)
- func (ctx *Context) ParamInt64(key string) (int64, error)
- func (ctx *Context) ParamsLen() (n int)
- func (ctx *Context) ParamsSentence() string
- func (ctx *Context) PathString() string
- func (ctx *Context) PostValue(name string) string
- func (ctx *Context) PostValues(name string) []string
- func (ctx *Context) PostValuesAll() (valuesAll map[string][]string)
- func (ctx *Context) ReadForm(formObject interface{}) error
- func (ctx *Context) ReadJSON(jsonObject interface{}) error
- func (ctx *Context) ReadXML(xmlObject interface{}) error
- func (ctx *Context) Redirect(urlToRedirect string, statusHeader ...int)
- func (ctx *Context) RedirectTo(routeName string, args ...interface{})
- func (ctx *Context) RemoteAddr() string
- func (ctx *Context) RemoveCookie(name string)
- func (ctx *Context) Render(name string, binding interface{}, options ...map[string]interface{}) error
- func (ctx *Context) RenderTemplateSource(status int, src string, binding interface{}, options ...map[string]interface{}) error
- func (ctx *Context) RenderWithStatus(status int, name string, binding interface{}, ...) (err error)
- func (ctx *Context) RequestHeader(k string) string
- func (ctx *Context) RequestIP() string
- func (ctx *Context) RequestPath(escape bool) string
- func (ctx *Context) SendFile(filename string, destinationName string)
- func (ctx *Context) ServeContent(content io.ReadSeeker, filename string, modtime time.Time, ...) error
- func (ctx *Context) ServeFile(filename string, gzipCompression bool) error
- func (ctx *Context) Session() sessions.Session
- func (ctx *Context) SessionDestroy()
- func (ctx *Context) Set(key string, value interface{})
- func (ctx *Context) SetContentType(s string)
- func (ctx *Context) SetCookie(cookie *fasthttp.Cookie)
- func (ctx *Context) SetCookieKV(key, value string)
- func (ctx *Context) SetFlash(key string, value string)
- func (ctx *Context) SetHeader(k string, v string)
- func (ctx *Context) StopExecution()
- func (ctx *Context) Stream(cb func(writer *bufio.Writer))
- func (ctx *Context) StreamReader(bodyStream io.Reader, bodySize int)
- func (ctx *Context) StreamWriter(cb func(writer *bufio.Writer))
- func (ctx *Context) Subdomain() (subdomain string)
- func (ctx *Context) TemplateString(name string, binding interface{}, options ...map[string]interface{}) string
- func (ctx *Context) Text(status int, v string) error
- func (ctx *Context) URLParam(key string) string
- func (ctx *Context) URLParamInt(key string) (int, error)
- func (ctx *Context) URLParamInt64(key string) (int64, error)
- func (ctx *Context) URLParams() map[string]string
- func (ctx *Context) ValuesLen() (n int)
- func (ctx *Context) VirtualHostname() string
- func (ctx *Context) VisitAllCookies(visitor func(key string, value string))
- func (ctx *Context) Write(format string, a ...interface{})
- func (ctx *Context) XML(status int, v interface{}) error
- type Framework
- func (api Framework) API(path string, restAPI HandlerAPI, middleware ...HandlerFunc)
- func (s *Framework) AcquireCtx(reqCtx *fasthttp.RequestCtx) *Context
- func (api Framework) Any(registedPath string, handlersFn ...HandlerFunc)
- func (s *Framework) Build()
- func (s *Framework) Cache(bodyHandler HandlerFunc, expiration time.Duration) HandlerFunc
- func (s *Framework) CheckForUpdates(force bool)
- func (s *Framework) Close() error
- func (api Framework) Connect(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func (api Framework) Delete(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func (s *Framework) DisableKeepalive(val bool)
- func (api Framework) Done(handlers ...Handler) MuxAPI
- func (api Framework) DoneFunc(handlersFn ...HandlerFunc) MuxAPI
- func (api Framework) EmitError(statusCode int, ctx *Context)
- func (api Framework) Favicon(favPath string, requestPath ...string) RouteNameFunc
- func (api Framework) Get(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func (api Framework) Handle(method string, registedPath string, handlers ...Handler) RouteNameFunc
- func (api Framework) HandleFunc(method string, registedPath string, handlersFn ...HandlerFunc) RouteNameFunc
- func (api Framework) Head(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func (s *Framework) InvalidateCache(ctx *Context)
- func (s *Framework) IsRunning() bool
- func (api Framework) Layout(tmplLayoutFile string) MuxAPI
- func (s *Framework) Listen(addr string)
- func (s *Framework) ListenLETSENCRYPT(addr string, cacheFileOptional ...string)
- func (s *Framework) ListenTLS(addr string, certFile, keyFile string)
- func (s *Framework) ListenUNIX(addr string, mode os.FileMode)
- func (s *Framework) Lookup(routeName string) Route
- func (s *Framework) Lookups() (routes []Route)
- func (s *Framework) Must(err error)
- func (api Framework) OnError(statusCode int, handlerFn HandlerFunc)
- func (api Framework) Options(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func (api Framework) Party(relativePath string, handlersFn ...HandlerFunc) MuxAPI
- func (api Framework) Patch(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func (s *Framework) Path(routeName string, args ...interface{}) string
- func (api Framework) Post(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func (api Framework) Put(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func (s *Framework) ReleaseCtx(ctx *Context)
- func (s *Framework) Reserve() error
- func (s *Framework) SerializeToString(keyOrContentType string, obj interface{}, options ...map[string]interface{}) string
- func (s *Framework) Serve(ln net.Listener) error
- func (s *Framework) Set(setters ...OptionSetter)
- func (api Framework) Static(reqPath string, systemPath string, stripSlashes int) RouteNameFunc
- func (api Framework) StaticContent(reqPath string, cType string, content []byte) RouteNameFunc
- func (api Framework) StaticEmbedded(requestPath string, vdir string, assetFn func(name string) ([]byte, error), ...) RouteNameFunc
- func (api Framework) StaticFS(reqPath string, systemPath string, stripSlashes int) RouteNameFunc
- func (api Framework) StaticHandler(systemPath string, stripSlashes int, compress bool, generateIndexPages bool, ...) HandlerFunc
- func (api Framework) StaticServe(systemPath string, requestPath ...string) RouteNameFunc
- func (api Framework) StaticWeb(reqPath string, systemPath string, stripSlashes int) RouteNameFunc
- func (s *Framework) TemplateSourceString(src string, pageContext interface{}) string
- func (s *Framework) TemplateString(templateFile string, pageContext interface{}, ...) string
- func (api Framework) Trace(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func (s *Framework) URL(routeName string, args ...interface{}) (url string)
- func (api Framework) Use(handlers ...Handler)
- func (api Framework) UseFunc(handlersFn ...HandlerFunc)
- func (s *Framework) UseGlobal(handlers ...Handler)
- func (s *Framework) UseGlobalFunc(handlersFn ...HandlerFunc)
- func (s *Framework) UsePreRender(pre PreRender)
- func (s *Framework) UseSerializer(forContentType string, e serializer.Serializer)
- func (s *Framework) UseSessionDB(db sessions.Database)
- func (s *Framework) UseTemplate(e template.Engine) *template.Loader
- type FrameworkAPI
- type Handler
- type HandlerAPI
- type HandlerFunc
- type Map
- type Middleware
- type MuxAPI
- type OptionSet
- type OptionSetter
- type Plugin
- type PluginContainer
- type PluginDownloadManager
- type PostListenFunc
- type PreBuildFunc
- type PreCloseFunc
- type PreDownloadFunc
- type PreListenFunc
- type PreLookupFunc
- type PreRender
- type RenderOptions
- type Route
- type RouteNameFunc
- func Connect(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func Delete(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func Favicon(favPath string, requestPath ...string) RouteNameFunc
- func Get(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func Handle(method string, registedPath string, handlers ...Handler) RouteNameFunc
- func HandleFunc(method string, registedPath string, handlersFn ...HandlerFunc) RouteNameFunc
- func Head(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func Options(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func Patch(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func Post(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func Put(path string, handlersFn ...HandlerFunc) RouteNameFunc
- func Static(reqPath string, systemPath string, stripSlashes int) RouteNameFunc
- func StaticContent(reqPath string, contentType string, content []byte) RouteNameFunc
- func StaticEmbedded(requestPath string, vdir string, assetFn func(name string) ([]byte, error), ...) RouteNameFunc
- func StaticFS(reqPath string, systemPath string, stripSlashes int) RouteNameFunc
- func StaticServe(systemPath string, requestPath ...string) RouteNameFunc
- func StaticWeb(reqPath string, systemPath string, stripSlashes int) RouteNameFunc
- func Trace(path string, handlersFn ...HandlerFunc) RouteNameFunc
- type SessionsConfiguration
- type TCPKeepAliveListener
- type WebsocketConfiguration
- type WebsocketConnection
- type WebsocketServer
Constants ¶
const ( DefaultDisablePathCorrection = false DefaultDisablePathEscape = false DefaultCharset = "UTF-8" DefaultLoggerPreffix = "[IRIS] " // DefaultMaxRequestBodySize is 8MB DefaultMaxRequestBodySize = 2 * fasthttp.DefaultMaxRequestBodySize // Per-connection buffer size for requests' reading. // This also limits the maximum header size. // // Increase this buffer if your clients send multi-KB RequestURIs // and/or multi-KB headers (for example, BIG cookies). // // Default buffer size is 8MB DefaultReadBufferSize = 8096 // Per-connection buffer size for responses' writing. // // Default buffer size is 8MB DefaultWriteBufferSize = 8096 )
Default values for base Iris conf
const ( // DefaultCookieName the secret cookie's name for sessions DefaultCookieName = "irissessionid" // DefaultSessionGcDuration is the default Session Manager's GCDuration , which is 2 hours DefaultSessionGcDuration = time.Duration(2) * time.Hour // DefaultCookieLength is the default Session Manager's CookieLength, which is 32 DefaultCookieLength = 32 )
const ( // DefaultWriteTimeout 15 * time.Second DefaultWriteTimeout = 15 * time.Second // DefaultPongTimeout 60 * time.Second DefaultPongTimeout = 60 * time.Second // DefaultPingPeriod (DefaultPongTimeout * 9) / 10 DefaultPingPeriod = (DefaultPongTimeout * 9) / 10 // DefaultMaxMessageSize 1024 DefaultMaxMessageSize = 1024 )
const ( // DefaultServerHostname returns the default hostname which is 0.0.0.0 DefaultServerHostname = "0.0.0.0" // DefaultServerPort returns the default port which is 8080, not used DefaultServerPort = 8080 )
Default values for base Server conf
const ( // MethodGet "GET" MethodGet = "GET" // MethodPost "POST" MethodPost = "POST" // MethodPut "PUT" MethodPut = "PUT" // MethodDelete "DELETE" MethodDelete = "DELETE" // MethodConnect "CONNECT" MethodConnect = "CONNECT" // MethodHead "HEAD" MethodHead = "HEAD" // MethodPatch "PATCH" MethodPatch = "PATCH" // MethodOptions "OPTIONS" MethodOptions = "OPTIONS" // MethodTrace "TRACE" MethodTrace = "TRACE" )
const ( // StatusContinue http status '100' StatusContinue = 100 // StatusSwitchingProtocols http status '101' StatusSwitchingProtocols = 101 // StatusOK http status '200' StatusOK = 200 // StatusCreated http status '201' StatusCreated = 201 // StatusAccepted http status '202' StatusAccepted = 202 // StatusNonAuthoritativeInfo http status '203' StatusNonAuthoritativeInfo = 203 // StatusNoContent http status '204' StatusNoContent = 204 // StatusResetContent http status '205' StatusResetContent = 205 // StatusPartialContent http status '206' StatusPartialContent = 206 // StatusMultipleChoices http status '300' StatusMultipleChoices = 300 // StatusMovedPermanently http status '301' StatusMovedPermanently = 301 // StatusFound http status '302' StatusFound = 302 // StatusSeeOther http status '303' StatusSeeOther = 303 // StatusNotModified http status '304' StatusNotModified = 304 // StatusUseProxy http status '305' StatusUseProxy = 305 // StatusTemporaryRedirect http status '307' StatusTemporaryRedirect = 307 // StatusBadRequest http status '400' StatusBadRequest = 400 StatusUnauthorized = 401 // StatusPaymentRequired http status '402' StatusPaymentRequired = 402 // StatusForbidden http status '403' StatusForbidden = 403 // StatusNotFound http status '404' StatusNotFound = 404 // StatusMethodNotAllowed http status '405' StatusMethodNotAllowed = 405 // StatusNotAcceptable http status '406' StatusNotAcceptable = 406 // StatusProxyAuthRequired http status '407' StatusProxyAuthRequired = 407 // StatusRequestTimeout http status '408' StatusRequestTimeout = 408 // StatusConflict http status '409' StatusConflict = 409 // StatusGone http status '410' StatusGone = 410 // StatusLengthRequired http status '411' StatusLengthRequired = 411 // StatusPreconditionFailed http status '412' StatusPreconditionFailed = 412 // StatusRequestEntityTooLarge http status '413' StatusRequestEntityTooLarge = 413 // StatusRequestURITooLong http status '414' StatusRequestURITooLong = 414 // StatusUnsupportedMediaType http status '415' StatusUnsupportedMediaType = 415 // StatusRequestedRangeNotSatisfiable http status '416' StatusRequestedRangeNotSatisfiable = 416 // StatusExpectationFailed http status '417' StatusExpectationFailed = 417 // StatusTeapot http status '418' StatusTeapot = 418 // StatusPreconditionRequired http status '428' StatusPreconditionRequired = 428 // StatusTooManyRequests http status '429' StatusTooManyRequests = 429 // StatusRequestHeaderFieldsTooLarge http status '431' StatusRequestHeaderFieldsTooLarge = 431 StatusUnavailableForLegalReasons = 451 // StatusInternalServerError http status '500' StatusInternalServerError = 500 // StatusNotImplemented http status '501' StatusNotImplemented = 501 // StatusBadGateway http status '502' StatusBadGateway = 502 StatusServiceUnavailable = 503 // StatusGatewayTimeout http status '504' StatusGatewayTimeout = 504 // StatusHTTPVersionNotSupported http status '505' StatusHTTPVersionNotSupported = 505 // StatusNetworkAuthenticationRequired http status '511' StatusNetworkAuthenticationRequired = 511 )
const ( // SchemeHTTPS returns "https://" (full) SchemeHTTPS = "https://" // SchemeHTTP returns "http://" (full) SchemeHTTP = "http://" )
const ( // IsLongTermSupport flag is true when the below version number is a long-term-support version IsLongTermSupport = true // Version is the current version number of the Iris web framework Version = "4" )
const ( // NoLayout to disable layout for a particular template file NoLayout = template.NoLayout // TemplateLayoutContextKey is the name of the user values which can be used to set a template layout from a middleware and override the parent's TemplateLayoutContextKey = "templateLayout" )
const ( // All is the string which the Emmiter use to send a message to all All = websocket.All // NotMe is the string which the Emmiter use to send a message to all except this websocket.Connection NotMe = websocket.NotMe // Broadcast is the string which the Emmiter use to send a message to all except this websocket.Connection, same as 'NotMe' Broadcast = websocket.Broadcast )
conversionals
Variables ¶
var ( // OptionVHost is the addr or the domain that server listens to, which it's optional // When to set VHost manually: // 1. it's automatically setted when you're calling // $instance.Listen/ListenUNIX/ListenTLS/ListenLETSENCRYPT functions or // ln,_ := iris.TCP4/UNIX/TLS/LETSENCRYPT; $instance.Serve(ln) // 2. If you using a balancer, or something like nginx // then set it in order to have the correct url // when calling the template helper '{{url }}' // *keep note that you can use {{urlpath }}) instead* // // Note: this is the main's server Host, you can setup unlimited number of fasthttp servers // listening to the $instance.Handler after the manually-called $instance.Build // // Default comes from iris.Listen/.Serve with iris' listeners (iris.TCP4/UNIX/TLS/LETSENCRYPT) OptionVHost = func(val string) OptionSet { return func(c *Configuration) { c.VHost = val } } // OptionVScheme is the scheme (http:// or https://) putted at the template function '{{url }}' // It's an optional field, // When to set Scheme manually: // 1. You didn't start the main server using $instance.Listen/ListenTLS/ListenLETSENCRYPT or $instance.Serve($instance.TCP4()/.TLS...) // 2. if you're using something like nginx and have iris listening with addr only(http://) but the nginx mapper is listening to https:// // // Default comes from iris.Listen/.Serve with iris' listeners (TCP4,UNIX,TLS,LETSENCRYPT) OptionVScheme = func(val string) OptionSet { return func(c *Configuration) { c.VScheme = val } } // OptionMaxRequestBodySize Maximum request body size. // // The server rejects requests with bodies exceeding this limit. // // By default request body size is 8MB. OptionMaxRequestBodySize = func(val int) OptionSet { return func(c *Configuration) { c.MaxRequestBodySize = val } } // Per-connection buffer size for requests' reading.“ // This also limits the maximum header size. // // Increase this buffer if your clients send multi-KB RequestURIs // and/or multi-KB headers (for example, BIG cookies). // // Default buffer size is used if not set. OptionReadBufferSize = func(val int) OptionSet { return func(c *Configuration) { c.ReadBufferSize = val } } // Per-connection buffer size for responses' writing. // // Default buffer size is used if not set. OptionWriteBufferSize = func(val int) OptionSet { return func(c *Configuration) { c.WriteBufferSize = val } } // Maximum duration for reading the full request (including body). // // This also limits the maximum duration for idle keep-alive // connections. // // By default request read timeout is unlimited. OptionReadTimeout = func(val time.Duration) OptionSet { return func(c *Configuration) { c.ReadTimeout = val } } // Maximum duration for writing the full response (including body). // // By default response write timeout is unlimited. OptionWriteTimeout = func(val time.Duration) OptionSet { return func(c *Configuration) { c.WriteTimeout = val } } // OptionMaxConnsPerIP Maximum number of concurrent client connections allowed per IP. // // By default unlimited number of concurrent connections // may be established to the server from a single IP address. OptionMaxConnsPerIP = func(val int) OptionSet { return func(c *Configuration) { c.MaxConnsPerIP = val } } // OptionMaxRequestsPerConn Maximum number of requests served per connection. // // The server closes connection after the last request. // 'Connection: close' header is added to the last response. // // By default unlimited number of requests may be served per connection. OptionMaxRequestsPerConn = func(val int) OptionSet { return func(c *Configuration) { c.MaxRequestsPerConn = val } } // OptionCheckForUpdates will try to search for newer version of Iris based on the https://github.com/kataras/iris/releases // If a newer version found then the app will ask the he dev/user if want to update the 'x' version // if 'y' is pressed then the updater will try to install the latest version // the updater, will notify the dev/user that the update is finished and should restart the App manually. // Notes: // 1. Experimental feature // 2. If setted to true, the app will have a little startup delay // 3. If you as developer edited the $GOPATH/src/github/kataras or any other Iris' Go dependencies at the past // then the update process will fail. // // Usage: iris.Set(iris.OptionCheckForUpdates(true)) or // iris.Config.CheckForUpdates = true or // app := iris.New(iris.OptionCheckForUpdates(true)) // Default is false OptionCheckForUpdates = func(val bool) OptionSet { return func(c *Configuration) { c.CheckForUpdates = val } } // CheckForUpdatesSync checks for updates before server starts, it will have a little delay depends on the machine's download's speed // See CheckForUpdates for more // Notes: // 1. you could use the CheckForUpdatesSync while CheckForUpdates is false, set this or CheckForUpdates to true not both // 2. if both CheckForUpdates and CheckForUpdatesSync are setted to true then the updater will run in sync mode, before server server starts. // // Default is false OptionCheckForUpdatesSync = func(val bool) OptionSet { return func(c *Configuration) { c.CheckForUpdatesSync = val } } // OptionDisablePathCorrection corrects and redirects the requested path to the registed 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 // // Default is false OptionDisablePathCorrection = func(val bool) OptionSet { return func(c *Configuration) { c.DisablePathCorrection = val } } // OptionDisablePathEscape when is false then its escapes the path, the named parameters (if any). OptionDisablePathEscape = func(val bool) OptionSet { return func(c *Configuration) { c.DisablePathEscape = val } } // FireMethodNotAllowed if it's true router checks for StatusMethodNotAllowed(405) and fires the 405 error instead of 404 // Default is false OptionFireMethodNotAllowed = func(val bool) OptionSet { return func(c *Configuration) { c.FireMethodNotAllowed = val } } // OptionDisableBanner outputs the iris banner at startup // // Default is false OptionDisableBanner = func(val bool) OptionSet { return func(c *Configuration) { c.DisableBanner = val } } // OptionLoggerOut is the destination for output // // Default is os.Stdout OptionLoggerOut = func(val io.Writer) OptionSet { return func(c *Configuration) { c.LoggerOut = val } } // OptionLoggerPreffix is the logger's prefix to write at beginning of each line // // Default is [IRIS] OptionLoggerPreffix = func(val string) OptionSet { return func(c *Configuration) { c.LoggerPreffix = val } } // OptionDisableTemplateEngines set to true to disable loading the default template engine (html/template) and disallow the use of iris.UseEngine // Default is false OptionDisableTemplateEngines = func(val bool) OptionSet { return func(c *Configuration) { c.DisableTemplateEngines = val } } // OptionIsDevelopment iris will act like a developer, for example // If true then re-builds the templates on each request // Default is false OptionIsDevelopment = func(val bool) OptionSet { return func(c *Configuration) { c.IsDevelopment = val } } // OptionTimeFormat time format for any kind of datetime parsing OptionTimeFormat = func(val string) OptionSet { return func(c *Configuration) { c.TimeFormat = val } } // OptionCharset character encoding for various rendering // used for templates and the rest of the responses // Default is "UTF-8" OptionCharset = func(val string) OptionSet { return func(c *Configuration) { c.Charset = val } } // OptionGzip enables gzip compression on your Render actions, this includes any type of render, templates and pure/raw content // If you don't want to enable it globaly, you could just use the third parameter on context.Render("myfileOrResponse", structBinding{}, iris.RenderOptions{"gzip": true}) // Default is false OptionGzip = func(val bool) OptionSet { return func(c *Configuration) { c.Gzip = val } } // OptionOther are the custom, dynamic options, can be empty // this fill used only by you to set any app's options you want // for each of an Iris instance OptionOther = func(val ...options.Options) OptionSet { opts := options.Options{} for _, opt := range val { for k, v := range opt { opts[k] = v } } return func(c *Configuration) { c.Other = opts } } )
All options starts with "Option" preffix in order to be easier to find what dev searching for
var ( // DefaultTimeFormat default time format for any kind of datetime parsing DefaultTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" // StaticCacheDuration expiration duration for INACTIVE file handlers, it's a global configuration field to all iris instances StaticCacheDuration = 20 * time.Second // CompressedFileSuffix is the suffix to add to the name of // cached compressed file when using the .StaticFS function. // // Defaults to iris-fasthttp.gz CompressedFileSuffix = "iris-fasthttp.gz" )
var ( // DefaultLoggerOut is the default logger's output DefaultLoggerOut = os.Stdout // DefaultServerName the response header of the 'Server' value when writes to the client DefaultServerName = "" )
var ( // OptionSessionsCookie string, the session's client cookie name, for example: "qsessionid" OptionSessionsCookie = func(val string) OptionSet { return func(c *Configuration) { c.Sessions.Cookie = val } } // OptionSessionsDecodeCookie set it to true to decode the cookie key with base64 URLEncoding // Defaults to false OptionSessionsDecodeCookie = func(val bool) OptionSet { return func(c *Configuration) { c.Sessions.DecodeCookie = val } } // OptionSessionsExpires the duration of which the cookie must expires (created_time.Add(Expires)). // If you want to delete the cookie when the browser closes, set it to -1 but in this case, the server side's session duration is up to GcDuration // // Default infinitive/unlimited life duration(0) OptionSessionsExpires = func(val time.Duration) OptionSet { return func(c *Configuration) { c.Sessions.Expires = val } } // OptionSessionsCookieLength the length of the sessionid's cookie's value, let it to 0 if you don't want to change it // Defaults to 32 OptionSessionsCookieLength = func(val int) OptionSet { return func(c *Configuration) { c.Sessions.CookieLength = val } } // OptionSessionsGcDuration every how much duration(GcDuration) the memory should be clear for unused cookies (GcDuration) // for example: time.Duration(2)*time.Hour. it will check every 2 hours if cookie hasn't be used for 2 hours, // deletes it from backend memory until the user comes back, then the session continue to work as it was // // Default 2 hours OptionSessionsGcDuration = func(val time.Duration) OptionSet { return func(c *Configuration) { c.Sessions.GcDuration = val } } // OptionSessionsDisableSubdomainPersistence set it to true in order dissallow your q subdomains to have access to the session cookie // Defaults to false OptionSessionsDisableSubdomainPersistence = func(val bool) OptionSet { return func(c *Configuration) { c.Sessions.DisableSubdomainPersistence = val } } )
var ( // OptionWebsocketWriteTimeout time allowed to write a message to the connection. // Default value is 15 * time.Second OptionWebsocketWriteTimeout = func(val time.Duration) OptionSet { return func(c *Configuration) { c.Websocket.WriteTimeout = val } } // OptionWebsocketPongTimeout allowed to read the next pong message from the connection // Default value is 60 * time.Second OptionWebsocketPongTimeout = func(val time.Duration) OptionSet { return func(c *Configuration) { c.Websocket.PongTimeout = val } } // OptionWebsocketPingPeriod send ping messages to the connection with this period. Must be less than PongTimeout // Default value is (PongTimeout * 9) / 10 OptionWebsocketPingPeriod = func(val time.Duration) OptionSet { return func(c *Configuration) { c.Websocket.PingPeriod = val } } // OptionWebsocketMaxMessageSize max message size allowed from connection // Default value is 1024 OptionWebsocketMaxMessageSize = func(val int64) OptionSet { return func(c *Configuration) { c.Websocket.MaxMessageSize = val } } // OptionWebsocketBinaryMessages set it to true in order to denotes binary data messages instead of utf-8 text // see https://github.com/kataras/iris/issues/387#issuecomment-243006022 for more // Defaults to false OptionWebsocketBinaryMessages = func(val bool) OptionSet { return func(c *Configuration) { c.Websocket.BinaryMessages = val } } // OptionWebsocketEndpoint is the path which the websocket server will listen for clients/connections // Default value is empty string, if you don't set it the Websocket server is disabled. OptionWebsocketEndpoint = func(val string) OptionSet { return func(c *Configuration) { c.Websocket.Endpoint = val } } // OptionWebsocketReadBufferSize is the buffer size for the underline reader OptionWebsocketReadBufferSize = func(val int) OptionSet { return func(c *Configuration) { c.Websocket.ReadBufferSize = val } } // OptionWebsocketWriteBufferSize is the buffer size for the underline writer OptionWebsocketWriteBufferSize = func(val int) OptionSet { return func(c *Configuration) { c.Websocket.WriteBufferSize = val } } // OptionWebsocketHeaders if true then the client's headers are copy to the websocket connection OptionWebsocketHeaders = func(val bool) OptionSet { return func(c *Configuration) { c.Websocket.Headers = val } } // OptionWebsocketError specifies the function for generating HTTP error responses. OptionWebsocketError = func(val func(*Context, int, string)) OptionSet { return func(c *Configuration) { c.Websocket.Error = val } } // OptionWebsocketCheckOrigin returns true if the request Origin header is acceptable. If // CheckOrigin is nil, the host in the Origin header must not be set or // must match the host of the request. OptionWebsocketCheckOrigin = func(val func(*Context) bool) OptionSet { return func(c *Configuration) { c.Websocket.CheckOrigin = val } } )
var ( // DefaultWebsocketError is the default method to manage the handshake websocket errors DefaultWebsocketError = func(ctx *Context, status int, reason string) { ctx.Set("WsError", reason) ctx.EmitError(status) } // DefaultWebsocketCheckOrigin is the default method to allow websocket clients to connect to this server // you can change this behavior by setting the iris.Config.Websocket.CheckOrigin = iris.WebsocketCheckSameOrigin DefaultWebsocketCheckOrigin = func(ctx *Context) bool { return true } // WebsocketCheckSameOrigin returns true if the origin is not set or is equal to the request host WebsocketCheckSameOrigin = func(ctx *Context) bool { origin := ctx.RequestHeader("origin") if len(origin) == 0 { return true } u, err := url.Parse(origin) if err != nil { return false } return u.Host == ctx.HostString() } )
var ( // AllMethods "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", "PATCH", "OPTIONS", "TRACE" AllMethods = [...]string{MethodGet, MethodPost, MethodPut, MethodDelete, MethodConnect, MethodHead, MethodPatch, MethodOptions, MethodTrace} // MethodGetBytes "GET" MethodGetBytes = []byte(MethodGet) // MethodPostBytes "POST" MethodPostBytes = []byte(MethodPost) // MethodPutBytes "PUT" MethodPutBytes = []byte(MethodPut) // MethodDeleteBytes "DELETE" MethodDeleteBytes = []byte(MethodDelete) // MethodConnectBytes "CONNECT" MethodConnectBytes = []byte(MethodConnect) // MethodHeadBytes "HEAD" MethodHeadBytes = []byte(MethodHead) // MethodPatchBytes "PATCH" MethodPatchBytes = []byte(MethodPatch) // MethodOptionsBytes "OPTIONS" MethodOptionsBytes = []byte(MethodOptions) // MethodTraceBytes "TRACE" MethodTraceBytes = []byte(MethodTrace) )
var ( Default *Framework Config *Configuration Logger *log.Logger // if you want colors in your console then you should use this https://github.com/iris-contrib/logger instead. Plugins PluginContainer Router fasthttp.RequestHandler Websocket *WebsocketServer // Available is a channel type of bool, fired to true when the server is opened and all plugins ran // never fires false, if the .Close called then the channel is re-allocating. // the channel remains open until you close it. // // look at the http_test.go file for a usage example Available chan bool )
Default iris instance entry and its public fields, use it with iris.$anyPublicFuncOrField
var ( // CookieExpireNever the default cookie's life for sessions, unlimited (23 years) CookieExpireNever = time.Now().AddDate(23, 0, 0) )
var ( // DefaultServerAddr the default server addr which is: 0.0.0.0:8080 DefaultServerAddr = DefaultServerHostname + ":" + strconv.Itoa(DefaultServerPort) )
var ProxyHandler = func(proxyAddr string, redirectSchemeAndHost string) fasthttp.RequestHandler { return func(reqCtx *fasthttp.RequestCtx) { redirectTo := redirectSchemeAndHost fakehost := string(reqCtx.Request.Host()) path := string(reqCtx.Path()) if strings.Count(fakehost, ".") >= 3 { if sufIdx := strings.LastIndexByte(fakehost, '.'); sufIdx > 0 { if _, err := strconv.Atoi(fakehost[sufIdx+1:]); err != nil { redirectScheme := ParseScheme(redirectSchemeAndHost) realHost := strings.Replace(redirectSchemeAndHost, redirectScheme, "", 1) redirectHost := strings.Replace(fakehost, fakehost, realHost, 1) redirectTo = redirectScheme + redirectHost + path reqCtx.Redirect(redirectTo, StatusMovedPermanently) return } } } if path != "/" { redirectTo += path } reqCtx.Redirect(redirectTo, StatusMovedPermanently) } }
ProxyHandler returns a new fasthttp handler which works as 'proxy', maybe doesn't suits you look its code before using that in production
Functions ¶
func API ¶
func API(path string, restAPI HandlerAPI, middleware ...HandlerFunc)
API converts & registers a custom struct to the router receives two parameters first is the request path (string) second is the custom struct (interface{}) which can be anything that has a *iris.Context as field. third is the common middlewares, it's optional
Note that API's routes have their default-name to the full registed path, no need to give a special name for it, because it's not supposed to be used inside your templates.
Recommend to use when you retrieve data from an external database, and the router-performance is not the (only) thing which slows the server's overall performance.
This is a slow method, if you care about router-performance use the Handle/HandleFunc/Get/Post/Put/Delete/Trace/Options... instead
func Any ¶
func Any(registedPath string, handlersFn ...HandlerFunc)
Any registers a route for ALL of the http methods (Get,Post,Put,Head,Patch,Options,Connect,Delete)
func Build ¶
func Build()
Build builds the whole framework's parts together DO NOT CALL IT MANUALLY IF YOU ARE NOT: SERVE IRIS BEHIND AN EXTERNAL CUSTOM fasthttp.Server, CAN BE CALLED ONCE PER IRIS INSTANCE FOR YOUR SAFETY
func CERT ¶
CERT returns a listener which contans tls.Config with the provided certificate, use for ssl
func CheckForUpdates ¶
func CheckForUpdates(force bool)
CheckForUpdates will try to search for newer version of Iris based on the https://github.com/kataras/iris/releases If a newer version found then the app will ask the he dev/user if want to update the 'x' version if 'y' is pressed then the updater will try to install the latest version the updater, will notify the dev/user that the update is finished and should restart the App manually.
func Close ¶
func Close() error
Close terminates all the registered servers and returns an error if any if you want to panic on this error use the iris.Must(iris.Close())
func DecodeFasthttpURL ¶
DecodeFasthttpURL returns the path decoded as url useful when you want to pass something to a database and be valid to retrieve it via context.Param use it only for special cases, when the default behavior doesn't suits you.
http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
Credits to Manish Singh @kryptodev for URLDecode by post issue share code
simple things, if DecodeURL doesn't gives you the results you waited, use this function I know it is not the best way to describe it, but I don't think you will ever need this, it is here for ANY CASE
func DecodeURL ¶
DecodeURL returns the uri parameter as url (string) useful when you want to pass something to a database and be valid to retrieve it via context.Param use it only for special cases, when the default behavior doesn't suits you.
http://www.blooberry.com/indexdot/html/topics/urlencoding.htm it uses just the url.QueryUnescape
func DisableKeepalive ¶
func DisableKeepalive(val bool)
DisableKeepalive whether to disable keep-alive connections.
The server will close all the incoming connections after sending the first response to client if this option is set to true.
By default keep-alive connections are enabled ¶
Note: Used on packages like graceful, after the server runs.
func EmitError ¶
EmitError fires a custom http error handler to the client
if no custom error defined with this statuscode, then iris creates one, and once at runtime
func HTMLEscape ¶
HTMLEscape returns a string which has no valid html code
func InvalidateCache ¶
func InvalidateCache(ctx *Context)
InvalidateCache clears the cache body for a specific context's url path(cache unique key)
Note that it depends on a station instance's cache service. Do not try to call it from default' station if you use the form of app := iris.New(), use the app.InvalidateCache instead of iris.InvalidateCache
func LETSENCRYPT ¶
LETSENCRYPT returns a new Automatic TLS Listener using letsencrypt.org service receives two parameters, the first is the domain of the server and the second is optionally, the cache file, if you skip it then the cache directory is "./letsencrypt.cache" if you want to disable cache file then simple give it a value of empty string ""
supports localhost domains for testing, but I recommend you to use the LETSENCRYPTPROD if you gonna to use it on production
func LETSENCRYPTPROD ¶
LETSENCRYPTPROD returns a new Automatic TLS Listener using letsencrypt.org service receives two parameters, the first is the domain of the server and the second is optionally, the cache directory, if you skip it then the cache directory is "./certcache" if you want to disable cache directory then simple give it a value of empty string ""
does NOT supports localhost domains for testing, use LETSENCRYPT instead.
this is the recommended function to use when you're ready for production state
func Listen ¶
func Listen(addr string)
Listen starts the standalone http server which listens to the addr parameter which as the form of host:port
It panics on error if you need a func to return an error, use the Serve
func ListenLETSENCRYPT ¶
ListenLETSENCRYPT starts a server listening at the specific nat address using key & certification taken from the letsencrypt.org 's servers it's also starts a second 'http' server to redirect all 'http://$ADDR_HOSTNAME:80' to the' https://$ADDR' it creates a cache file to store the certifications, for performance reasons, this file by-default is "./letsencrypt.cache" if you skip the second parameter then the cache file is "./letsencrypt.cache" if you want to disable cache then simple pass as second argument an empty empty string ""
example: https://github.com/iris-contrib/examples/blob/master/letsencyrpt/main.go
supports localhost domains for testing, NOTE: if you are ready for production then use `$app.Serve(iris.LETSENCRYPTPROD("mydomain.com"))` instead
func ListenTLS ¶
ListenTLS Starts a https server with certificates, if you use this method the requests of the form of 'http://' will fail only https:// connections are allowed which listens to the addr parameter which as the form of host:port
It panics on error if you need a func to return an error, use the Serve ex: iris.ListenTLS(":8080","yourfile.cert","yourfile.key")
func ListenUNIX ¶
ListenUNIX starts the process of listening to the new requests using a 'socket file', this works only on unix
It panics on error if you need a func to return an error, use the Serve ex: iris.ListenUNIX(":8080", Mode: os.FileMode)
func OnError ¶
func OnError(statusCode int, handlerFn HandlerFunc)
OnError registers a custom http error handler
func ParseHost ¶
ParseHost tries to convert a given string to an address which is compatible with net.Listener and server
func ParseHostname ¶
ParseHostname receives an addr of form host[:port] and returns the hostname part of it ex: localhost:8080 will return the `localhost`, mydomain.com:8080 will return the 'mydomain'
func ParsePort ¶
ParsePort receives an addr of form host[:port] and returns the port part of it ex: localhost:8080 will return the `8080`, mydomain.com will return the '80'
func ParseScheme ¶
ParseScheme returns the scheme based on the host,addr,domain Note: the full scheme not just http*,https* *http:// *https://
func Path ¶
Path used to check arguments with the route's named parameters and return the correct url if parse failed returns empty string
func Proxy ¶
Proxy not really a proxy, it's just starts a server listening on proxyAddr but redirects all requests to the redirectToSchemeAndHost+$path nothing special, use it only when you want to start a secondary server which its only work is to redirect from one requested path to another
returns a close function
func ReleaseCtx ¶
func ReleaseCtx(ctx *Context)
ReleaseCtx puts the Iris' Context back to the pool in order to be re-used see .AcquireCtx & .Serve
func ResetDefault ¶
func ResetDefault()
ResetDefault resets the iris.Default which is the instance which is used on the default iris station for
iris.Get(all api functions)
iris.Config iris.Logger iris.Plugins iris.Router iris.Websocket iris.Available channel useful mostly when you are not using the form of app := iris.New() inside your tests, to make sure that you're using a new iris instance
func RouteConflicts ¶
RouteConflicts checks for route's middleware conflicts
func SerializeToString ¶
func SerializeToString(keyOrContentType string, obj interface{}, options ...map[string]interface{}) string
SerializeToString returns the string of a serializer, does not render it to the client returns empty string on error
func Serve ¶
Serve serves incoming connections from the given listener.
Serve blocks until the given listener returns permanent error.
func Set ¶
func Set(setters ...OptionSetter)
Set sets an option aka configuration field to the default iris instance
func StatusText ¶
StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.
func TCP4 ¶
TCP4 returns a new tcp4 Listener *tcp6 has some bugs in some operating systems, as reported by Go Community*
func TemplateSourceString ¶
TemplateSourceString executes a template source(raw string contents) from the first template engines which supports raw parsing returns its result as string,
useful when you want it for sending rich e-mails
returns empty string on error
func TemplateString ¶
func TemplateString(templateFile string, pageContext interface{}, options ...map[string]interface{}) string
TemplateString executes a template from the default template engine and returns its result as string, useful when you want it for sending rich e-mails returns empty string on error
func URL ¶
URL returns the subdomain+ host + Path(...optional named parameters if route is dynamic) returns an empty string if parse is failed
func UseGlobal ¶
func UseGlobal(handlers ...Handler)
UseGlobal registers Handler middleware to the beginning, prepends them instead of append
Use it when you want to add a global middleware to all parties, to all routes in all subdomains It can be called after other, (but before .Listen of course)
func UseGlobalFunc ¶
func UseGlobalFunc(handlersFn ...HandlerFunc)
UseGlobalFunc registers HandlerFunc middleware to the beginning, prepends them instead of append
Use it when you want to add a global middleware to all parties, to all routes in all subdomains It can be called after other, (but before .Listen of course)
func UsePreRender ¶
func UsePreRender(pre PreRender)
UsePreRender adds a Template's PreRender PreRender is typeof func(*iris.Context, filenameOrSource string, binding interface{}, options ...map[string]interface{}) bool PreRenders helps developers to pass middleware between the route Handler and a context.Render call all parameter receivers can be changed before passing it to the actual context's Render so, you can change the filenameOrSource, the page binding, the options, and even add cookies, session value or a flash message through ctx the return value of a PreRender is a boolean, if returns false then the next PreRender will not be executed, keep note that the actual context's Render will be called at any case.
func UseSerializer ¶
func UseSerializer(forContentType string, e serializer.Serializer)
UseSerializer accepts a Serializer and the key or content type on which the developer wants to register this serializer the gzip and charset are automatically supported by Iris, by passing the iris.RenderOptions{} map on the context.Render context.Render renders this response or a template engine if no response engine with the 'key' found with these engines you can inject the context.JSON,Text,Data,JSONP,XML also to do that just register with UseSerializer(mySerializer,"application/json") and so on look at the https://github.com/kataras/go-serializer for examples
if more than one serializer with the same key/content type exists then the results will be appended to the final request's body this allows the developer to be able to create 'middleware' responses engines
Note: if you pass an engine which contains a dot('.') as key, then the engine will not be registered. you don't have to import and use github.com/iris-contrib/json, jsonp, xml, data, text, markdown because iris uses these by default if no other response engine is registered for these content types
func UseSessionDB ¶
func UseSessionDB(db sessions.Database)
UseSessionDB registers a session database, you can register more than one accepts a session database which implements a Load(sid string) map[string]interface{} and an Update(sid string, newValues map[string]interface{}) the only reason that a session database will be useful for you is when you want to keep the session's values/data after the app restart a session database doesn't have write access to the session, it doesn't accept the context, so forget 'cookie database' for sessions, I will never allow that, for your protection.
Note: Don't worry if no session database is registered, your context.Session will continue to work.
func UseTemplate ¶
func UseTemplate(e template.Engine) *template.Loader
UseTemplate adds a template engine to the iris view system it does not build/load them yet
Types ¶
type BodyDecoder ¶
BodyDecoder is an interface which any struct can implement in order to customize the decode action from ReadJSON and ReadXML
Trivial example of this could be: type User struct { Username string }
func (u *User) Decode(data []byte) error { return json.Unmarshal(data, u) }
the 'context.ReadJSON/ReadXML(&User{})' will call the User's Decode option to decode the request body
Note: This is totally optionally, the default decoders for ReadJSON is the encoding/json and for ReadXML is the encoding/xml
type Configuration ¶
type Configuration struct { // VHost is the addr or the domain that server listens to, which it's optional // When to set VHost manually: // 1. it's automatically setted when you're calling // $instance.Listen/ListenUNIX/ListenTLS/ListenLETSENCRYPT functions or // ln,_ := iris.TCP4/UNIX/TLS/LETSENCRYPT; $instance.Serve(ln) // 2. If you using a balancer, or something like nginx // then set it in order to have the correct url // when calling the template helper '{{url }}' // *keep note that you can use {{urlpath }}) instead* // // Note: this is the main's server Host, you can setup unlimited number of fasthttp servers // listening to the $instance.Handler after the manually-called $instance.Build // // Default comes from iris.Listen/.Serve with iris' listeners (iris.TCP4/UNIX/TLS/LETSENCRYPT) VHost string // VScheme is the scheme (http:// or https://) putted at the template function '{{url }}' // It's an optional field, // When to set VScheme manually: // 1. You didn't start the main server using $instance.Listen/ListenTLS/ListenLETSENCRYPT or $instance.Serve($instance.TCP4()/.TLS...) // 2. if you're using something like nginx and have iris listening with addr only(http://) but the nginx mapper is listening to https:// // // Default comes from iris.Listen/.Serve with iris' listeners (TCP4,UNIX,TLS,LETSENCRYPT) VScheme string // MaxRequestBodySize Maximum request body size. // // The server rejects requests with bodies exceeding this limit. // // By default request body size is 8MB. MaxRequestBodySize int // Per-connection buffer size for requests' reading. // This also limits the maximum header size. // // Increase this buffer if your clients send multi-KB RequestURIs // and/or multi-KB headers (for example, BIG cookies). // // Default buffer size is used if not set. ReadBufferSize int // Per-connection buffer size for responses' writing. // // Default buffer size is used if not set. WriteBufferSize int // Maximum duration for reading the full request (including body). // // This also limits the maximum duration for idle keep-alive // connections. // // By default request read timeout is unlimited. ReadTimeout time.Duration // Maximum duration for writing the full response (including body). // // By default response write timeout is unlimited. WriteTimeout time.Duration // Maximum number of concurrent client connections allowed per IP. // // By default unlimited number of concurrent connections MaxConnsPerIP int // Maximum number of requests served per connection. // // The server closes connection after the last request. // 'Connection: close' header is added to the last response. // // By default unlimited number of requests may be served per connection. MaxRequestsPerConn int // CheckForUpdates will try to search for newer version of Iris based on the https://github.com/kataras/iris/releases // If a newer version found then the app will ask the he dev/user if want to update the 'x' version // if 'y' is pressed then the updater will try to install the latest version // the updater, will notify the dev/user that the update is finished and should restart the App manually. // Notes: // 1. Experimental feature // 2. If setted to true, the app will start the server normally and runs the updater in its own goroutine, // for a sync operation see CheckForUpdatesSync. // 3. If you as developer edited the $GOPATH/src/github/kataras or any other Iris' Go dependencies at the past // then the update process will fail. // // Usage: iris.Set(iris.OptionCheckForUpdates(true)) or // iris.Config.CheckForUpdates = true or // app := iris.New(iris.OptionCheckForUpdates(true)) // Default is false CheckForUpdates bool // CheckForUpdatesSync checks for updates before server starts, it will have a little delay depends on the machine's download's speed // See CheckForUpdates for more // Notes: // 1. you could use the CheckForUpdatesSync while CheckForUpdates is false, set this or CheckForUpdates to true not both // 2. if both CheckForUpdates and CheckForUpdatesSync are setted to true then the updater will run in sync mode, before server server starts. // // Default is false CheckForUpdatesSync bool // DisablePathCorrection corrects and redirects the requested path to the registed 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 // // Default is false DisablePathCorrection bool // DisablePathEscape when is false then its escapes the path, the named parameters (if any). // Change to true it if you want something like this https://github.com/kataras/iris/issues/135 to work // // When do you need to Disable(true) 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"). // Look here: https://github.com/kataras/iris/issues/135 for more // // Default is false DisablePathEscape bool // FireMethodNotAllowed if it's true router checks for StatusMethodNotAllowed(405) and fires the 405 error instead of 404 // Default is false FireMethodNotAllowed bool // DisableBanner outputs the iris banner at startup // // Default is false DisableBanner bool // LoggerOut is the destination for output // // Default is os.Stdout LoggerOut io.Writer // LoggerPreffix is the logger's prefix to write at beginning of each line // // Default is [IRIS] LoggerPreffix string // DisableTemplateEngines set to true to disable loading the default template engine (html/template) and disallow the use of iris.UseEngine // Defaults to false DisableTemplateEngines bool // IsDevelopment iris will act like a developer, for example // If true then re-builds the templates on each request // Defaults to false IsDevelopment bool // TimeFormat time format for any kind of datetime parsing TimeFormat string // Charset character encoding for various rendering // used for templates and the rest of the responses // Defaults to "UTF-8" Charset string // Gzip enables gzip compression on your Render actions, this includes any type of render, templates and pure/raw content // If you don't want to enable it globaly, you could just use the third parameter on context.Render("myfileOrResponse", structBinding{}, iris.RenderOptions{"gzip": true}) // Defaults to false Gzip bool // Sessions contains the configs for sessions Sessions SessionsConfiguration // Websocket contains the configs for Websocket's server integration Websocket WebsocketConfiguration // Other are the custom, dynamic options, can be empty // this fill used only by you to set any app's options you want // for each of an Iris instance Other options.Options }
Configuration the whole configuration for an iris instance ($instance.Config) or global iris instance (iris.Config) these can be passed via options also, look at the top of this file(configuration.go)
Configuration is also implements the OptionSet so it's a valid option itself, this is brilliant enough
func DefaultConfiguration ¶
func DefaultConfiguration() Configuration
DefaultConfiguration returns the default configuration for an Iris station, fills the main Configuration
func (Configuration) Set ¶
func (c Configuration) Set(main *Configuration)
Set implements the OptionSetter
type Context ¶
type Context struct { *fasthttp.RequestCtx //keep track all registed middleware (handlers) Middleware Middleware // exported because is useful for debugging // Pos is the position number of the Context, look .Next to understand Pos uint8 // exported because is useful for debugging // contains filtered or unexported fields }
Context is resetting every time a request is coming to the server it is not good practice to use this object in goroutines, for these cases use the .Clone()
func AcquireCtx ¶
func AcquireCtx(reqCtx *fasthttp.RequestCtx) *Context
AcquireCtx gets an Iris' Context from pool see .ReleaseCtx & .Serve
func (*Context) Do ¶
func (ctx *Context) Do()
Do calls the first handler only, it's like Next with negative pos, used only on Router&MemoryRouter
func (*Context) EmitError ¶
EmitError executes the custom error by the http status code passed to the function
func (*Context) FormValueString ¶
FormValueString returns a single value, as string, from post request's data
func (*Context) FormValues ¶
FormValues returns a slice of string from post request's data
func (*Context) Framework ¶
Framework returns the Iris instance, containing the configuration and all other fields
func (*Context) GetCookie ¶
GetCookie returns cookie's value by it's name returns empty string if nothing was found
func (*Context) GetFlash ¶
GetFlash get a flash message by it's key returns the value as string and an error
if the cookie doesn't exists the string is empty and the error is filled after the request's life the value is removed
func (*Context) GetFlashes ¶
GetFlashes returns all the flash messages for available for this request
func (*Context) GetFmt ¶
GetFmt returns a value which has this format: func(format string, args ...interface{}) string if doesn't exists returns nil
func (*Context) GetHandlerName ¶
GetHandlerName as requested returns the stack-name of the function which the Middleware is setted from
func (*Context) GetInt ¶
GetInt same as Get but tries to convert the return value as integer if nothing found or canno be parsed to integer it returns an error
func (*Context) GetRequestCtx ¶
func (ctx *Context) GetRequestCtx() *fasthttp.RequestCtx
GetRequestCtx returns the current fasthttp context
func (*Context) GetString ¶
GetString same as Get but returns the value as string if nothing founds returns empty string ""
func (*Context) Gzip ¶
Gzip accepts bytes, which are compressed to gzip format and sent to the client
func (*Context) HostString ¶
HostString returns the Host of the request( the url as string )
func (*Context) InvalidateCache ¶
func (ctx *Context) InvalidateCache()
InvalidateCache clears the cache manually for this request uri context's handler's route
func (*Context) IsAjax ¶
IsAjax returns true if this request is an 'ajax request'( XMLHttpRequest)
Read more at: http://www.w3schools.com/ajax/
func (*Context) IsStopped ¶
IsStopped checks and returns true if the current position of the Context is 255, means that the StopExecution has called
func (*Context) Markdown ¶
Markdown parses and renders to the client a particular (dynamic) markdown string accepts two parameters first is the http status code second is the markdown string
func (*Context) MarkdownString ¶
MarkdownString parses the (dynamic) markdown string and returns the converted html string
func (*Context) MaxAge ¶
MaxAge returns the "cache-control" request header's value seconds as int64 if header not found or parse failed then it returns -1
func (*Context) MethodString ¶
MethodString returns the HTTP Method
func (*Context) MustRender ¶
MustRender same as .Render but returns 503 service unavailable http status with a (html) message if render failed Note: the options: "gzip" and "charset" are built'n support by Iris, so you can pass these on any template engine or serialize engine
func (*Context) Next ¶
func (ctx *Context) Next()
Next calls all the next handler from the middleware stack, it used inside a middleware
func (*Context) NotFound ¶
func (ctx *Context) NotFound()
NotFound emits an error 404 to the client, using the custom http errors if no custom errors provided then it sends the default error message
func (*Context) Panic ¶
func (ctx *Context) Panic()
Panic emits an error 500 to the client, using the custom http errors if no custom errors rpovided then it sends the default error message
func (*Context) Param ¶
Param returns the string representation of the key's path named parameter's value same as GetString
func (*Context) ParamInt ¶
ParamInt returns the int representation of the key's path named parameter's value same as GetInt
func (*Context) ParamInt64 ¶
ParamInt64 returns the int64 representation of the key's path named parameter's value
func (*Context) ParamsLen ¶
ParamsLen tries to return all the stored values which values are string, probably most of them will be the path parameters
func (*Context) ParamsSentence ¶
ParamsSentence returns a string implementation of all parameters that this context keeps hasthe form of key1=value1,key2=value2...
func (*Context) PathString ¶
PathString returns the full escaped path as string for unescaped use: ctx.RequestCtx.RequestURI() or RequestPath(escape bool)
func (*Context) PostValue ¶
PostValue returns the post data value of a single key/name returns an empty string if nothing found
func (*Context) PostValues ¶
PostValues returns the post data values as []string of a single key/name
func (*Context) PostValuesAll ¶
PostValuesAll returns all post data values with their keys multipart, form data, get & post query arguments
func (*Context) ReadForm ¶
ReadForm binds the formObject with the form data it supports any kind of struct
func (*Context) Redirect ¶
Redirect redirect sends a redirect response the client accepts 2 parameters string and an optional int first parameter is the url to redirect second parameter is the http status should send, default is 302 (StatusFound), you can set it to 301 (Permant redirect), if that's nessecery
func (*Context) RedirectTo ¶
RedirectTo does the same thing as Redirect but instead of receiving a uri or path it receives a route name
func (*Context) RemoteAddr ¶
RemoteAddr is like RequestIP but it checks for proxy servers also, tries to get the real client's request IP
func (*Context) RemoveCookie ¶
RemoveCookie deletes a cookie by it's name/key
func (*Context) Render ¶
func (ctx *Context) Render(name string, binding interface{}, options ...map[string]interface{}) error
Render same as .RenderWithStatus but with status to iris.StatusOK (200) if no previous status exists builds up the response from the specified template or a serialize engine. Note: the options: "gzip" and "charset" are built'n support by Iris, so you can pass these on any template engine or serialize engine
func (*Context) RenderTemplateSource ¶
func (ctx *Context) RenderTemplateSource(status int, src string, binding interface{}, options ...map[string]interface{}) error
RenderTemplateSource serves a template source(raw string contents) from the first template engines which supports raw parsing returns its result as string
func (*Context) RenderWithStatus ¶
func (ctx *Context) RenderWithStatus(status int, name string, binding interface{}, options ...map[string]interface{}) (err error)
RenderWithStatus builds up the response from the specified template or a serialize engine. Note: the options: "gzip" and "charset" are built'n support by Iris, so you can pass these on any template engine or serialize engines
func (*Context) RequestHeader ¶
RequestHeader returns the request header's value accepts one parameter, the key of the header (string) returns string
func (*Context) RequestPath ¶
RequestPath returns the requested path
func (*Context) SendFile ¶
SendFile sends file for force-download to the client
Use this instead of ServeFile to 'force-download' bigger files to the client
func (*Context) ServeContent ¶
func (ctx *Context) ServeContent(content io.ReadSeeker, filename string, modtime time.Time, gzipCompression bool) error
ServeContent serves content, headers are autoset receives three parameters, it's low-level function, instead you can use .ServeFile(string,bool)/SendFile(string,string)
You can define your own "Content-Type" header also, after this function call Doesn't implements resuming (by range), use ctx.SendFile instead
func (*Context) ServeFile ¶
ServeFile serves a view file, to send a file ( zip for example) to the client you should use the SendFile(serverfilename,clientfilename) receives two parameters filename/path (string) gzipCompression (bool)
You can define your own "Content-Type" header also, after this function call This function doesn't implement resuming (by range), use ctx.SendFile/fasthttp.ServeFileUncompressed(ctx.RequestCtx,path)/fasthttpServeFile(ctx.RequestCtx,path) instead
Use it when you want to serve css/js/... files to the client, for bigger files and 'force-download' use the SendFile
func (*Context) Session ¶
func (ctx *Context) Session() sessions.Session
Session returns the current session
func (*Context) SessionDestroy ¶
func (ctx *Context) SessionDestroy()
SessionDestroy destroys the whole session, calls the provider's destroy and remove the cookie
func (*Context) SetContentType ¶
SetContentType sets the response writer's header key 'Content-Type' to a given value(s)
func (*Context) SetCookieKV ¶
SetCookieKV adds a cookie, receives just a key(string) and a value(string)
func (*Context) SetFlash ¶
SetFlash sets a flash message, accepts 2 parameters the key(string) and the value(string) the value will be available on the NEXT request
func (*Context) SetHeader ¶
SetHeader write to the response writer's header to a given key the given value(s)
Note: If you want to send a multi-line string as header's value use: strings.TrimSpace first.
func (*Context) StopExecution ¶
func (ctx *Context) StopExecution()
StopExecution just sets the .pos to 255 in order to not move to the next middlewares(if any)
func (*Context) StreamReader ¶
StreamReader sets response body stream and, optionally body size.
If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes before returning io.EOF.
If bodySize < 0, then bodyStream is read until io.EOF.
bodyStream.Close() is called after finishing reading all body data if it implements io.Closer.
See also the StreamWriter
func (*Context) StreamWriter ¶
StreamWriter registers the given stream writer for populating response body.
This function may be used in the following cases:
- if response body is too big (more than 10MB).
- if response body is streamed from slow external sources.
- if response body must be streamed to the client in chunks. (aka `http server push`).
See also the StreamReader
func (*Context) TemplateString ¶
func (ctx *Context) TemplateString(name string, binding interface{}, options ...map[string]interface{}) string
TemplateString accepts a template filename, its context data and returns the result of the parsed template (string) if any error returns empty string
func (*Context) URLParamInt ¶
URLParamInt returns the url query parameter as int value from a request , returns error on parse fail
func (*Context) URLParamInt64 ¶
URLParamInt64 returns the url query parameter as int64 value from a request , returns error on parse fail
func (*Context) ValuesLen ¶
ValuesLen returns the total length of the user values storage, some of them maybe path parameters
func (*Context) VirtualHostname ¶
VirtualHostname returns the hostname that user registers, host path maybe differs from the real which is HostString, which taken from a net.listener
func (*Context) VisitAllCookies ¶
VisitAllCookies takes a visitor which loops on each (request's) cookie key and value
Note: the method ctx.Request.Header.VisitAllCookie by fasthttp, has a strange bug which I cannot solve at the moment. This is the reason which this function exists and should be used instead of fasthttp's built'n.
type Framework ¶
type Framework struct { Available chan bool // // Router field which can change the default iris' mux behavior // if you want to get benefit with iris' context make use of: // ctx:= iris.AcquireCtx(*fasthttp.RequestCtx) to get the context at the beginning of your handler // iris.ReleaseCtx(ctx) to release/put the context to the pool, at the very end of your custom handler. Router fasthttp.RequestHandler Config *Configuration Logger *log.Logger Plugins PluginContainer Websocket *WebsocketServer // contains filtered or unexported fields }
Framework is our God |\| Google.Search('Greek mythology Iris')
Implements the FrameworkAPI
func New ¶
func New(setters ...OptionSetter) *Framework
New creates and returns a new Iris instance.
Receives (optional) multi options, use iris.Option and your editor should show you the available options to set all options are inside ./configuration.go example 1: iris.New(iris.OptionIsDevelopment(true), iris.OptionCharset("UTF-8"), irisOptionSessionsCookie("mycookieid"),iris.OptionWebsocketEndpoint("my_endpoint")) example 2: iris.New(iris.Configuration{IsDevelopment:true, Charset: "UTF-8", Sessions: iris.SessionsConfiguration{Cookie:"mycookieid"}, Websocket: iris.WebsocketConfiguration{Endpoint:"/my_endpoint"}}) both ways are totally valid and equal
func (Framework) API ¶
func (api Framework) API(path string, restAPI HandlerAPI, middleware ...HandlerFunc)
API converts & registers a custom struct to the router receives two parameters first is the request path (string) second is the custom struct (interface{}) which can be anything that has a *iris.Context as field. third is the common middleware, it's optional
Note that API's routes have their default-name to the full registed path, no need to give a special name for it, because it's not supposed to be used inside your templates.
Recommend to use when you retrieve data from an external database, and the router-performance is not the (only) thing which slows the server's overall performance.
This is a slow method, if you care about router-performance use the Handle/HandleFunc/Get/Post/Put/Delete/Trace/Options... instead
func (*Framework) AcquireCtx ¶
func (s *Framework) AcquireCtx(reqCtx *fasthttp.RequestCtx) *Context
AcquireCtx gets an Iris' Context from pool see .ReleaseCtx & .Serve
func (Framework) Any ¶
func (api Framework) Any(registedPath string, handlersFn ...HandlerFunc)
Any registers a route for ALL of the http methods (Get,Post,Put,Head,Patch,Options,Connect,Delete)
func (*Framework) Build ¶
func (s *Framework) Build()
Build builds the whole framework's parts together DO NOT CALL IT MANUALLY IF YOU ARE NOT: SERVE IRIS BEHIND AN EXTERNAL CUSTOM fasthttp.Server, CAN BE CALLED ONCE PER IRIS INSTANCE FOR YOUR SAFETY
func (*Framework) Cache ¶
func (s *Framework) Cache(bodyHandler HandlerFunc, expiration time.Duration) HandlerFunc
Cache is just a wrapper for a route's handler which you want to enable body caching
Usage: iris.Get("/", iris.Cache(func(ctx *iris.Context){ ctx.WriteString("Hello, world!") // or a template or anything else }, time.Duration(10*time.Second))) // duration of expiration
if <=time.Second then it tries to find it though request header's "cache-control" maxage value
Note that it depends on a station instance's cache service. Do not try to call it from default' station if you use the form of app := iris.New(), use the app.Cache instead of iris.Cache
func (*Framework) CheckForUpdates ¶
CheckForUpdates will try to search for newer version of Iris based on the https://github.com/kataras/iris/releases If a newer version found then the app will ask the he dev/user if want to update the 'x' version if 'y' is pressed then the updater will try to install the latest version the updater, will notify the dev/user that the update is finished and should restart the App manually. Note: exported func CheckForUpdates exists because of the reason that an update can be executed while Iris is running
func (*Framework) Close ¶
Close terminates all the registered servers and returns an error if any if you want to panic on this error use the iris.Must(iris.Close())
func (Framework) Connect ¶
func (api Framework) Connect(path string, handlersFn ...HandlerFunc) RouteNameFunc
Connect registers a route for the Connect http method
func (Framework) Delete ¶
func (api Framework) Delete(path string, handlersFn ...HandlerFunc) RouteNameFunc
Delete registers a route for the Delete http method
func (*Framework) DisableKeepalive ¶
DisableKeepalive whether to disable keep-alive connections.
The server will close all the incoming connections after sending the first response to client if this option is set to true.
By default keep-alive connections are enabled ¶
Note: Used on packages like graceful, after the server runs.
func (Framework) Done ¶
Done registers Handler 'middleware' the only difference from .Use is that it should be used BEFORE any party route registered or AFTER ALL party's routes have been registered.
returns itself
func (Framework) DoneFunc ¶
func (api Framework) DoneFunc(handlersFn ...HandlerFunc) MuxAPI
Done registers HandlerFunc 'middleware' the only difference from .Use is that it should be used BEFORE any party route registered or AFTER ALL party's routes have been registered.
returns itself
func (Framework) EmitError ¶
EmitError fires a custom http error handler to the client
if no custom error defined with this statuscode, then iris creates one, and once at runtime
func (Framework) Favicon ¶
func (api Framework) Favicon(favPath string, requestPath ...string) RouteNameFunc
Favicon serves static favicon accepts 2 parameters, second is optional favPath (string), declare the system directory path of the __.ico requestPath (string), it's the route's path, by default this is the "/favicon.ico" because some browsers tries to get this by default first, you can declare your own path if you have more than one favicon (desktop, mobile and so on)
this func will add a route for you which will static serve the /yuorpath/yourfile.ico to the /yourfile.ico (nothing special that you can't handle by yourself) Note that you have to call it on every favicon you have to serve automatically (dekstop, mobile and so on)
panics on error
func (Framework) Get ¶
func (api Framework) Get(path string, handlersFn ...HandlerFunc) RouteNameFunc
Get registers a route for the Get http method
func (Framework) Handle ¶
func (api Framework) Handle(method string, registedPath string, handlers ...Handler) RouteNameFunc
Handle registers a route to the server's router if empty method is passed then registers handler(s) for all methods, same as .Any, but returns nil as result
func (Framework) HandleFunc ¶
func (api Framework) HandleFunc(method string, registedPath string, handlersFn ...HandlerFunc) RouteNameFunc
HandleFunc registers and returns a route with a method string, path string and a handler registedPath is the relative url path
func (Framework) Head ¶
func (api Framework) Head(path string, handlersFn ...HandlerFunc) RouteNameFunc
Head registers a route for the Head http method
func (*Framework) InvalidateCache ¶
InvalidateCache clears the cache body for a specific context's url path(cache unique key)
Note that it depends on a station instance's cache service. Do not try to call it from default' station if you use the form of app := iris.New(), use the app.InvalidateCache instead of iris.InvalidateCache
func (Framework) Layout ¶
Layout oerrides the parent template layout with a more specific layout for this Party returns this Party, to continue as normal example: my := iris.Party("/my").Layout("layouts/mylayout.html")
{ my.Get("/", func(ctx *iris.Context) { ctx.MustRender("page1.html", nil) }) }
func (*Framework) Listen ¶
Listen starts the standalone http server which listens to the addr parameter which as the form of host:port
It panics on error if you need a func to return an error, use the Serve
func (*Framework) ListenLETSENCRYPT ¶
ListenLETSENCRYPT starts a server listening at the specific nat address using key & certification taken from the letsencrypt.org 's servers it's also starts a second 'http' server to redirect all 'http://$ADDR_HOSTNAME:80' to the' https://$ADDR' it creates a cache file to store the certifications, for performance reasons, this file by-default is "./letsencrypt.cache" if you skip the second parameter then the cache file is "./letsencrypt.cache" if you want to disable cache then simple pass as second argument an empty empty string ""
example: https://github.com/iris-contrib/examples/blob/master/letsencyrpt/main.go
supports localhost domains for testing, NOTE: if you are ready for production then use `$app.Serve(iris.LETSENCRYPTPROD("mydomain.com"))` instead
func (*Framework) ListenTLS ¶
ListenTLS Starts a https server with certificates, if you use this method the requests of the form of 'http://' will fail only https:// connections are allowed which listens to the addr parameter which as the form of host:port
It panics on error if you need a func to return an error, use the Serve ex: iris.ListenTLS(":8080","yourfile.cert","yourfile.key")
func (*Framework) ListenUNIX ¶
ListenUNIX starts the process of listening to the new requests using a 'socket file', this works only on unix
It panics on error if you need a func to return an error, use the Serve ex: iris.ListenUNIX(":8080", Mode: os.FileMode)
func (Framework) OnError ¶
func (api Framework) OnError(statusCode int, handlerFn HandlerFunc)
OnError registers a custom http error handler
func (Framework) Options ¶
func (api Framework) Options(path string, handlersFn ...HandlerFunc) RouteNameFunc
Options registers a route for the Options http method
func (Framework) Party ¶
func (api Framework) Party(relativePath string, handlersFn ...HandlerFunc) MuxAPI
Party is just a group joiner of routes which have the same prefix and share same middleware(s) also. Party can also be named as 'Join' or 'Node' or 'Group' , Party chosen because it has more fun
func (Framework) Patch ¶
func (api Framework) Patch(path string, handlersFn ...HandlerFunc) RouteNameFunc
Patch registers a route for the Patch http method
func (*Framework) Path ¶
Path used to check arguments with the route's named parameters and return the correct url if parse failed returns empty string
func (Framework) Post ¶
func (api Framework) Post(path string, handlersFn ...HandlerFunc) RouteNameFunc
Post registers a route for the Post http method
func (Framework) Put ¶
func (api Framework) Put(path string, handlersFn ...HandlerFunc) RouteNameFunc
Put registers a route for the Put http method
func (*Framework) ReleaseCtx ¶
ReleaseCtx puts the Iris' Context back to the pool in order to be re-used see .AcquireCtx & .Serve
func (*Framework) SerializeToString ¶
func (s *Framework) SerializeToString(keyOrContentType string, obj interface{}, options ...map[string]interface{}) string
SerializeToString returns the string of a serializer, does not render it to the client returns empty string on error
func (*Framework) Serve ¶
Serve serves incoming connections from the given listener.
Serve blocks until the given listener returns permanent error.
func (*Framework) Set ¶
func (s *Framework) Set(setters ...OptionSetter)
Set sets an option aka configuration field to this iris instance
func (Framework) Static ¶
func (api Framework) Static(reqPath string, systemPath string, stripSlashes int) RouteNameFunc
Static registers a route which serves a system directory this doesn't generates an index page which list all files no compression is used also, for these features look at StaticFS func accepts three parameters first parameter is the request url path (string) second parameter is the system directory (string) third parameter is the level (int) of stripSlashes * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: ""
func (Framework) StaticContent ¶
func (api Framework) StaticContent(reqPath string, cType string, content []byte) RouteNameFunc
StaticContent serves bytes, memory cached, on the reqPath a good example of this is how the websocket server uses that to auto-register the /iris-ws.js
func (Framework) StaticEmbedded ¶
func (api Framework) StaticEmbedded(requestPath string, vdir string, assetFn func(name string) ([]byte, error), namesFn func() []string) RouteNameFunc
StaticEmbedded used when files are distrubuted inside the app executable, using go-bindata mostly First parameter is the request path, the path which the files in the vdir will be served to, for example "/static" Second parameter is the (virtual) directory path, for example "./assets" Third parameter is the Asset function Forth parameter is the AssetNames function
For more take a look at the example: https://github.com/iris-contrib/examples/tree/4.0.0/static_files_embedded
func (Framework) StaticFS ¶
func (api Framework) StaticFS(reqPath string, systemPath string, stripSlashes int) RouteNameFunc
StaticFS registers a route which serves a system directory this is the fastest method to serve static files generates an index page which list all files if you use this method it will generate compressed files also think this function as small fileserver with http accepts three parameters first parameter is the request url path (string) second parameter is the system directory (string) third parameter is the level (int) of stripSlashes * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: ""
func (Framework) StaticHandler ¶
func (api Framework) StaticHandler(systemPath string, stripSlashes int, compress bool, generateIndexPages bool, indexNames []string) HandlerFunc
StaticHandler returns a Handler to serve static system directory Accepts 5 parameters
first is the systemPath (string) Path to the root directory to serve files from.
second is the stripSlashes (int) level * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: ""
third is the compress (bool) Transparently compresses responses if set to true.
The server tries minimizing CPU usage by caching compressed files. It adds fasthttp.FSCompressedFileSuffix suffix to the original file name and tries saving the resulting compressed file under the new file name. So it is advisable to give the server write access to Root and to all inner folders in order to minimze CPU usage when serving compressed responses.
fourth is the generateIndexPages (bool) Index pages for directories without files matching IndexNames are automatically generated if set.
Directory index generation may be quite slow for directories with many files (more than 1K), so it is discouraged enabling index pages' generation for such directories.
fifth is the indexNames ([]string) List of index file names to try opening during directory access.
For example:
- index.html
- index.htm
- my-super-index.xml
func (Framework) StaticServe ¶
func (api Framework) StaticServe(systemPath string, requestPath ...string) RouteNameFunc
StaticServe serves a directory as web resource it's the simpliest form of the Static* functions Almost same usage as StaticWeb accepts only one required parameter which is the systemPath ( the same path will be used to register the GET&HEAD routes) if second parameter is empty, otherwise the requestPath is the second parameter it uses gzip compression (compression on each request, no file cache)
func (Framework) StaticWeb ¶
func (api Framework) StaticWeb(reqPath string, systemPath string, stripSlashes int) RouteNameFunc
StaticWeb same as Static but if index.html exists and request uri is '/' then display the index.html's contents accepts three parameters first parameter is the request url path (string) second parameter is the system directory (string) third parameter is the level (int) of stripSlashes * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: "" * if you don't know what to put on stripSlashes just 1 example: https://github.com/iris-contrib/examples/tree/4.0.0/static_web
func (*Framework) TemplateSourceString ¶
TemplateSourceString executes a template source(raw string contents) from the first template engines which supports raw parsing returns its result as string,
useful when you want it for sending rich e-mails
returns empty string on error
func (*Framework) TemplateString ¶
func (s *Framework) TemplateString(templateFile string, pageContext interface{}, options ...map[string]interface{}) string
TemplateString executes a template from the default template engine and returns its result as string, useful when you want it for sending rich e-mails returns empty string on error
func (Framework) Trace ¶
func (api Framework) Trace(path string, handlersFn ...HandlerFunc) RouteNameFunc
Trace registers a route for the Trace http method
func (*Framework) URL ¶
URL returns the subdomain+ host + Path(...optional named parameters if route is dynamic) returns an empty string if parse is failed
func (Framework) Use ¶
func (api Framework) Use(handlers ...Handler)
Use registers Handler middleware
func (Framework) UseFunc ¶
func (api Framework) UseFunc(handlersFn ...HandlerFunc)
UseFunc registers HandlerFunc middleware
func (*Framework) UseGlobal ¶
UseGlobal registers Handler middleware to the beginning, prepends them instead of append
Use it when you want to add a global middleware to all parties, to all routes in all subdomains It can be called after other, (but before .Listen of course)
func (*Framework) UseGlobalFunc ¶
func (s *Framework) UseGlobalFunc(handlersFn ...HandlerFunc)
UseGlobalFunc registers HandlerFunc middleware to the beginning, prepends them instead of append
Use it when you want to add a global middleware to all parties, to all routes in all subdomains It can be called after other, (but before .Listen of course)
func (*Framework) UsePreRender ¶
UsePreRender adds a Template's PreRender PreRender is typeof func(*iris.Context, filenameOrSource string, binding interface{}, options ...map[string]interface{}) bool PreRenders helps developers to pass middleware between the route Handler and a context.Render call all parameter receivers can be changed before passing it to the actual context's Render so, you can change the filenameOrSource, the page binding, the options, and even add cookies, session value or a flash message through ctx the return value of a PreRender is a boolean, if returns false then the next PreRender will not be executed, keep note that the actual context's Render will be called at any case.
func (*Framework) UseSerializer ¶
UseSerializer accepts a Serializer and the key or content type on which the developer wants to register this serializer the gzip and charset are automatically supported by Iris, by passing the iris.RenderOptions{} map on the context.Render context.Render renders this response or a template engine if no response engine with the 'key' found with these engines you can inject the context.JSON,Text,Data,JSONP,XML also to do that just register with UseSerializer(mySerializer,"application/json") and so on look at the https://github.com/kataras/go-serializer for examples
if more than one serializer with the same key/content type exists then the results will be appended to the final request's body this allows the developer to be able to create 'middleware' responses engines
Note: if you pass an engine which contains a dot('.') as key, then the engine will not be registered. you don't have to import and use github.com/iris-contrib/json, jsonp, xml, data, text, markdown because iris uses these by default if no other response engine is registered for these content types
func (*Framework) UseSessionDB ¶
func (s *Framework) UseSessionDB(db sessions.Database)
UseSessionDB registers a session database, you can register more than one accepts a session database which implements a Load(sid string) map[string]interface{} and an Update(sid string, newValues map[string]interface{}) the only reason that a session database will be useful for you is when you want to keep the session's values/data after the app restart a session database doesn't have write access to the session, it doesn't accept the context, so forget 'cookie database' for sessions, I will never allow that, for your protection.
Note: Don't worry if no session database is registered, your context.Session will continue to work.
func (*Framework) UseTemplate ¶
func (s *Framework) UseTemplate(e template.Engine) *template.Loader
UseTemplate adds a template engine to the iris view system it does not build/load them yet
type FrameworkAPI ¶
type FrameworkAPI interface { MuxAPI Set(...OptionSetter) Must(error) Build() Serve(net.Listener) error Listen(string) ListenTLS(string, string, string) ListenLETSENCRYPT(string, ...string) ListenUNIX(string, os.FileMode) Close() error Reserve() error AcquireCtx(*fasthttp.RequestCtx) *Context ReleaseCtx(*Context) CheckForUpdates(bool) UseSessionDB(sessions.Database) UseSerializer(string, serializer.Serializer) UseTemplate(template.Engine) *template.Loader UsePreRender(PreRender) UseGlobal(...Handler) UseGlobalFunc(...HandlerFunc) Lookup(string) Route Lookups() []Route Path(string, ...interface{}) string URL(string, ...interface{}) string TemplateString(string, interface{}, ...map[string]interface{}) string TemplateSourceString(string, interface{}) string SerializeToString(string, interface{}, ...map[string]interface{}) string Cache(HandlerFunc, time.Duration) HandlerFunc InvalidateCache(*Context) }
FrameworkAPI contains the main Iris Public API
type Handler ¶
type Handler interface {
Serve(ctx *Context)
}
Handler the main Iris Handler interface.
func ToHandler ¶
func ToHandler(handler interface{}) Handler
ToHandler converts an http.Handler or http.HandlerFunc to an iris.Handler
func ToHandlerFastHTTP ¶
func ToHandlerFastHTTP(h fasthttp.RequestHandler) Handler
ToHandlerFastHTTP converts an fasthttp.RequestHandler to an iris.Handler
type HandlerFunc ¶
type HandlerFunc func(*Context)
HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.
func Cache ¶
func Cache(bodyHandler HandlerFunc, expiration time.Duration) HandlerFunc
Cache is just a wrapper for a route's handler which you want to enable body caching
Usage: iris.Get("/", iris.Cache(func(ctx *iris.Context){ ctx.WriteString("Hello, world!") // or a template or anything else }, time.Duration(10*time.Second))) // duration of expiration
if <=time.Second then it tries to find it though request header's "cache-control" maxage value
Note that it depends on a station instance's cache service. Do not try to call it from default' station if you use the form of app := iris.New(), use the app.Cache instead of iris.Cache
func StaticHandler ¶
func StaticHandler(systemPath string, stripSlashes int, compress bool, generateIndexPages bool, indexNames []string) HandlerFunc
StaticHandler returns a Handler to serve static system directory Accepts 5 parameters
first is the systemPath (string) Path to the root directory to serve files from.
second is the stripSlashes (int) level * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: ""
third is the compress (bool) Transparently compresses responses if set to true.
The server tries minimizing CPU usage by caching compressed files. It adds fasthttp.FSCompressedFileSuffix suffix to the original file name and tries saving the resulting compressed file under the new file name. So it is advisable to give the server write access to Root and to all inner folders in order to minimze CPU usage when serving compressed responses.
fourth is the generateIndexPages (bool) Index pages for directories without files matching IndexNames are automatically generated if set.
Directory index generation may be quite slow for directories with many files (more than 1K), so it is discouraged enabling index pages' generation for such directories.
fifth is the indexNames ([]string) List of index file names to try opening during directory access.
For example:
- index.html
- index.htm
- my-super-index.xml
func ToHandlerFunc ¶
func ToHandlerFunc(handler interface{}) HandlerFunc
ToHandlerFunc converts an http.Handler or http.HandlerFunc to an iris.HandlerFunc
func (HandlerFunc) Serve ¶
func (h HandlerFunc) Serve(ctx *Context)
Serve implements the Handler, is like ServeHTTP but for Iris
type Map ¶
type Map map[string]interface{}
Map is just a conversion for a map[string]interface{} should not be used inside Render when PongoEngine is used.
type Middleware ¶
type Middleware []Handler
Middleware is just a slice of Handler []func(c *Context)
type MuxAPI ¶
type MuxAPI interface { Party(string, ...HandlerFunc) MuxAPI // middleware serial, appending Use(...Handler) UseFunc(...HandlerFunc) // returns itself, because at the most-cases used like .Layout, at the first-line party's declaration Done(...Handler) MuxAPI DoneFunc(...HandlerFunc) MuxAPI // main handlers Handle(string, string, ...Handler) RouteNameFunc HandleFunc(string, string, ...HandlerFunc) RouteNameFunc API(string, HandlerAPI, ...HandlerFunc) // http methods Get(string, ...HandlerFunc) RouteNameFunc Post(string, ...HandlerFunc) RouteNameFunc Put(string, ...HandlerFunc) RouteNameFunc Delete(string, ...HandlerFunc) RouteNameFunc Connect(string, ...HandlerFunc) RouteNameFunc Head(string, ...HandlerFunc) RouteNameFunc Options(string, ...HandlerFunc) RouteNameFunc Patch(string, ...HandlerFunc) RouteNameFunc Trace(string, ...HandlerFunc) RouteNameFunc Any(string, ...HandlerFunc) // static content StaticHandler(string, int, bool, bool, []string) HandlerFunc Static(string, string, int) RouteNameFunc StaticFS(string, string, int) RouteNameFunc StaticWeb(string, string, int) RouteNameFunc StaticServe(string, ...string) RouteNameFunc StaticContent(string, string, []byte) RouteNameFunc StaticEmbedded(string, string, func(string) ([]byte, error), func() []string) RouteNameFunc Favicon(string, ...string) RouteNameFunc // templates Layout(string) MuxAPI // returns itself // errors OnError(int, HandlerFunc) EmitError(int, *Context) }
MuxAPI the visible api for the serveMux
func Done ¶
Done registers Handler 'middleware' the only difference from .Use is that it should be used BEFORE any party route registered or AFTER ALL party's routes have been registered.
returns itself
func DoneFunc ¶
func DoneFunc(handlersFn ...HandlerFunc) MuxAPI
DoneFunc registers HandlerFunc 'middleware' the only difference from .Use is that it should be used BEFORE any party route registered or AFTER ALL party's routes have been registered.
returns itself
func Layout ¶
Layout oerrides the parent template layout with a more specific layout for this Party returns this Party, to continue as normal example: my := iris.Party("/my").Layout("layouts/mylayout.html")
{ my.Get("/", func(ctx *iris.Context) { ctx.MustRender("page1.html", nil) }) }
func Party ¶
func Party(relativePath string, handlersFn ...HandlerFunc) MuxAPI
Party is just a group joiner of routes which have the same prefix and share same middleware(s) also. Party can also be named as 'Join' or 'Node' or 'Group' , Party chosen because it has more fun
type OptionSet ¶
type OptionSet func(c *Configuration)
OptionSet implements the OptionSetter
func (OptionSet) Set ¶
func (o OptionSet) Set(c *Configuration)
Set is the func which makes the OptionSet an OptionSetter, this is used mostly
type OptionSetter ¶
type OptionSetter interface { // Set receives a pointer to the global Configuration type and does the job of filling it Set(c *Configuration) }
OptionSetter sets a configuration field to the main configuration used to help developers to write less and configure only what they really want and nothing else example: iris.New(iris.Configuration{Sessions:iris.SessionConfiguration{Cookie:"mysessionid"}, Websocket: iris.WebsocketConfiguration{Endpoint:"/my_endpoint"}}) now can be done also by using iris.Option$FIELD: iris.New(irisOptionSessionsCookie("mycookieid"),iris.OptionWebsocketEndpoint("my_endpoint")) benefits: 1. user/dev have no worries what option to pass, he/she can just press iris.Option and all options should be shown to her/his editor's autocomplete-popup window 2. can be passed with any order 3. Can override previous configuration
type Plugin ¶
type Plugin interface { }
Plugin just an empty base for plugins A Plugin can be added with: .Add(PreListenFunc(func(*Framework))) and so on... or .Add(myPlugin{},myPlugin2{}) which myPlugin is a struct with any of the methods below or .PostListen(func(*Framework)) and so on...
type PluginContainer ¶
type PluginContainer interface { Add(...Plugin) error Remove(string) error Len() int GetName(Plugin) string GetDescription(Plugin) string GetByName(string) Plugin Printf(string, ...interface{}) Fired(string) int PreLookup(PreLookupFunc) DoPreLookup(Route) PreLookupFired() bool PreBuild(PreBuildFunc) DoPreBuild(*Framework) PreBuildFired() bool PreListen(PreListenFunc) DoPreListen(*Framework) DoPreListenParallel(*Framework) PreListenFired() bool PostListen(PostListenFunc) DoPostListen(*Framework) PostListenFired() bool PreClose(PreCloseFunc) DoPreClose(*Framework) PreCloseFired() bool PreDownload(PreDownloadFunc) DoPreDownload(Plugin, string) PreDownloadFired() bool // GetAll() []Plugin // GetDownloader is the only one module that is used and fire listeners at the same time in this file GetDownloader() PluginDownloadManager } //Note: custom event callbacks, never used internaly by Iris, but if you need them use this: github.com/kataras/go-events
PluginContainer is the interface which the pluginContainer should implements
type PluginDownloadManager ¶
type PluginDownloadManager interface { DirectoryExists(string) bool DownloadZip(string, string) (string, error) Unzip(string, string) (string, error) Remove(string) error // install is just the flow of: downloadZip -> unzip -> removeFile(zippedFile) // accepts 2 parameters // // first parameter is the remote url file zip // second parameter is the target directory // returns a string(installedDirectory) and an error // // (string) installedDirectory is the directory which the zip file had, this is the real installation path, you don't need to know what it's because these things maybe change to the future let's keep it to return the correct path. // the installedDirectory is not empty when the installation is succed, the targetDirectory is not already exists and no error happens // the installedDirectory is empty when the installation is already done by previous time or an error happens Install(remoteFileZip string, targetDirectory string) (string, error) }
PluginDownloadManager is the interface which the DownloadManager should implements
type PostListenFunc ¶
type PostListenFunc func(*Framework)
PostListenFunc implements the simple function listener for the PostListen(*Framework)
func (PostListenFunc) PostListen ¶
func (fn PostListenFunc) PostListen(station *Framework)
PostListen it's being called only one time, AFTER the Server is started (if .Listen called) parameter is the station
type PreBuildFunc ¶
type PreBuildFunc func(*Framework)
PreBuildFunc implements the simple function listener for the PreBuild(*Framework)
func (PreBuildFunc) PreBuild ¶
func (fn PreBuildFunc) PreBuild(station *Framework)
PreBuild it's being called once time, BEFORE the Server is started and before PreListen is used to do work before all other things are ready use this event if you want to add routes to your iris station or make any changes to the iris main configuration receiver is the station
type PreCloseFunc ¶
type PreCloseFunc func(*Framework)
PreCloseFunc implements the simple function listener for the PreClose(*Framework)
func (PreCloseFunc) PreClose ¶
func (fn PreCloseFunc) PreClose(station *Framework)
PreClose it's being called only one time, BEFORE the Iris .Close method any plugin cleanup/clear memory happens here
The plugin is deactivated after this state
type PreDownloadFunc ¶
PreDownloadFunc implements the simple function listener for the PreDownload(plugin,string)
func (PreDownloadFunc) PreDownload ¶
func (fn PreDownloadFunc) PreDownload(pl Plugin, downloadURL string)
PreDownload it's being called every time a plugin tries to download something
first parameter is the plugin second parameter is the download url must return a boolean, if false then the plugin is not permmited to download this file
type PreListenFunc ¶
type PreListenFunc func(*Framework)
PreListenFunc implements the simple function listener for the PreListen(*Framework)
func (PreListenFunc) PreListen ¶
func (fn PreListenFunc) PreListen(station *Framework)
PreListen it's being called only one time, BEFORE the Server is started (if .Listen called) is used to do work at the time all other things are ready to go
parameter is the station
type PreLookupFunc ¶
type PreLookupFunc func(Route)
PreLookupFunc implements the simple function listener for the PreLookup(Route)
func (PreLookupFunc) PreLookup ¶
func (fn PreLookupFunc) PreLookup(r Route)
PreLookup called before register a route
type PreRender ¶
type PreRender func(ctx *Context, filenameOrSource string, binding interface{}, options ...map[string]interface{}) bool
PreRender is typeof func(*iris.Context, string, interface{},...map[string]interface{}) bool PreRenders helps developers to pass middleware between the route Handler and a context.Render (THAT can render 'rest' types also but the PreRender applies ONLY to template rendering(file or source)) call all parameter receivers can be changed before passing it to the actual context's Render so, you can change the filenameOrSource, the page binding, the options, and even add cookies, session value or a flash message through ctx the return value of a PreRender is a boolean, if returns false then the next PreRender will not be executed, keep note that the actual context's Render will be called at any case.
type RenderOptions ¶
type RenderOptions map[string]interface{}
RenderOptions is a helper type for the optional runtime options can be passed by user when Render an example of this is the "layout" or "gzip" option same as Map but more specific name
type Route ¶
type Route interface { // Name returns the name of the route Name() string // Subdomain returns the subdomain,if any Subdomain() string // Method returns the http method Method() string // Path returns the path Path() string // SetPath changes/sets the path for this route SetPath(string) // Middleware returns the slice of Handler([]Handler) registed to this route Middleware() Middleware // SetMiddleware changes/sets the middleware(handler(s)) for this route SetMiddleware(Middleware) }
Route contains some useful information about a route
type RouteNameFunc ¶
type RouteNameFunc func(string)
RouteNameFunc the func returns from the MuxAPi's methods, optionally sets the name of the Route (*route)
func Connect ¶
func Connect(path string, handlersFn ...HandlerFunc) RouteNameFunc
Connect registers a route for the Connect http method
func Delete ¶
func Delete(path string, handlersFn ...HandlerFunc) RouteNameFunc
Delete registers a route for the Delete http method
func Favicon ¶
func Favicon(favPath string, requestPath ...string) RouteNameFunc
Favicon serves static favicon accepts 2 parameters, second is optional favPath (string), declare the system directory path of the __.ico requestPath (string), it's the route's path, by default this is the "/favicon.ico" because some browsers tries to get this by default first, you can declare your own path if you have more than one favicon (desktop, mobile and so on)
this func will add a route for you which will static serve the /yuorpath/yourfile.ico to the /yourfile.ico (nothing special that you can't handle by yourself) Note that you have to call it on every favicon you have to serve automatically (dekstop, mobile and so on)
panics on error
func Get ¶
func Get(path string, handlersFn ...HandlerFunc) RouteNameFunc
Get registers a route for the Get http method
func Handle ¶
func Handle(method string, registedPath string, handlers ...Handler) RouteNameFunc
Handle registers a route to the server's router if empty method is passed then registers handler(s) for all methods, same as .Any, but returns nil as result
func HandleFunc ¶
func HandleFunc(method string, registedPath string, handlersFn ...HandlerFunc) RouteNameFunc
HandleFunc registers and returns a route with a method string, path string and a handler registedPath is the relative url path
func Head ¶
func Head(path string, handlersFn ...HandlerFunc) RouteNameFunc
Head registers a route for the Head http method
func Options ¶
func Options(path string, handlersFn ...HandlerFunc) RouteNameFunc
Options registers a route for the Options http method
func Patch ¶
func Patch(path string, handlersFn ...HandlerFunc) RouteNameFunc
Patch registers a route for the Patch http method
func Post ¶
func Post(path string, handlersFn ...HandlerFunc) RouteNameFunc
Post registers a route for the Post http method
func Put ¶
func Put(path string, handlersFn ...HandlerFunc) RouteNameFunc
Put registers a route for the Put http method
func Static ¶
func Static(reqPath string, systemPath string, stripSlashes int) RouteNameFunc
Static registers a route which serves a system directory this doesn't generates an index page which list all files no compression is used also, for these features look at StaticFS func accepts three parameters first parameter is the request url path (string) second parameter is the system directory (string) third parameter is the level (int) of stripSlashes * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: ""
func StaticContent ¶
func StaticContent(reqPath string, contentType string, content []byte) RouteNameFunc
StaticContent serves bytes, memory cached, on the reqPath a good example of this is how the websocket server uses that to auto-register the /iris-ws.js
func StaticEmbedded ¶
func StaticEmbedded(requestPath string, vdir string, assetFn func(name string) ([]byte, error), namesFn func() []string) RouteNameFunc
StaticEmbedded used when files are distrubuted inside the app executable, using go-bindata mostly First parameter is the request path, the path which the files in the vdir(second parameter) will be served to, for example "/static" Second parameter is the (virtual) directory path, for example "./assets" Third parameter is the Asset function Forth parameter is the AssetNames function
For more take a look at the example: https://github.com/iris-contrib/examples/tree/4.0.0/static_files_embedded
func StaticFS ¶
func StaticFS(reqPath string, systemPath string, stripSlashes int) RouteNameFunc
StaticFS registers a route which serves a system directory this is the fastest method to serve static files generates an index page which list all files if you use this method it will generate compressed files also think this function as small fileserver with http accepts three parameters first parameter is the request url path (string) second parameter is the system directory (string) third parameter is the level (int) of stripSlashes * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: ""
func StaticServe ¶
func StaticServe(systemPath string, requestPath ...string) RouteNameFunc
StaticServe serves a directory as web resource it's the simpliest form of the Static* functions Almost same usage as StaticWeb accepts only one required parameter which is the systemPath ( the same path will be used to register the GET&HEAD routes) if second parameter is empty, otherwise the requestPath is the second parameter it uses gzip compression (compression on each request, no file cache)
func StaticWeb ¶
func StaticWeb(reqPath string, systemPath string, stripSlashes int) RouteNameFunc
StaticWeb same as Static but if index.html exists and request uri is '/' then display the index.html's contents accepts three parameters first parameter is the request url path (string) second parameter is the system directory (string) third parameter is the level (int) of stripSlashes * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: "" * if you don't know what to put on stripSlashes just 1
func Trace ¶
func Trace(path string, handlersFn ...HandlerFunc) RouteNameFunc
Trace registers a route for the Trace http method
type SessionsConfiguration ¶
type SessionsConfiguration sessions.Config
SessionsConfiguration the configuration for sessions has 6 fields first is the cookieName, the session's name (string) ["mysessionsecretcookieid"] second enable if you want to decode the cookie's key also third is the time which the client's cookie expires forth is the cookie length (sessionid) int, Defaults to 32, do not change if you don't have any reason to do fifth is the gcDuration (time.Duration) when this time passes it removes the unused sessions from the memory until the user come back sixth is the DisableSubdomainPersistence which you can set it to true in order dissallow your q subdomains to have access to the session cook
func DefaultSessionsConfiguration ¶
func DefaultSessionsConfiguration() SessionsConfiguration
DefaultSessionsConfiguration the default configs for Sessions
func (SessionsConfiguration) Set ¶
func (s SessionsConfiguration) Set(c *sessions.Config)
Set implements the OptionSetter of the sessions package
type TCPKeepAliveListener ¶
type TCPKeepAliveListener struct {
*net.TCPListener
}
TCPKeepAliveListener sets TCP keep-alive timeouts on accepted connections. Dead TCP connections (e.g. closing laptop mid-download) eventually go away It is not used by default if you want to pass a keep alive listener then just pass the child listener, example: listener := iris.TCPKeepAliveListener{iris.TCP4(":8080").(*net.TCPListener)}
type WebsocketConfiguration ¶
type WebsocketConfiguration struct { // WriteTimeout time allowed to write a message to the connection. // Default value is 15 * time.Second WriteTimeout time.Duration // PongTimeout allowed to read the next pong message from the connection // Default value is 60 * time.Second PongTimeout time.Duration // PingPeriod send ping messages to the connection with this period. Must be less than PongTimeout // Default value is (PongTimeout * 9) / 10 PingPeriod time.Duration // MaxMessageSize max message size allowed from connection // Default value is 1024 MaxMessageSize int64 // BinaryMessages set it to true in order to denotes binary data messages instead of utf-8 text // see https://github.com/kataras/iris/issues/387#issuecomment-243006022 for more // Defaults to false BinaryMessages bool // Endpoint is the path which the websocket server will listen for clients/connections // Default value is empty string, if you don't set it the Websocket server is disabled. Endpoint string // ReadBufferSize is the buffer size for the underline reader ReadBufferSize int // WriteBufferSize is the buffer size for the underline writer WriteBufferSize int // Headers if true then the client's headers are copy to the websocket connection // // Default is true Headers bool // Error specifies the function for generating HTTP error responses. // // The default behavior is to store the reason in the context (ctx.Set(reason)) and fire any custom error (ctx.EmitError(status)) Error func(ctx *Context, status int, reason string) // CheckOrigin returns true if the request Origin header is acceptable. If // CheckOrigin is nil, the host in the Origin header must not be set or // must match the host of the request. // // The default behavior is to allow all origins // you can change this behavior by setting the iris.Config.Websocket.CheckOrigin = iris.WebsocketCheckSameOrigin CheckOrigin func(ctx *Context) bool }
WebsocketConfiguration the config contains options for the Websocket main config field
func DefaultWebsocketConfiguration ¶
func DefaultWebsocketConfiguration() WebsocketConfiguration
DefaultWebsocketConfiguration returns the default config for iris-ws websocket package
type WebsocketConnection ¶
type WebsocketConnection interface { websocket.Connection }
WebsocketConnection is the front-end API that you will use to communicate with the client side
type WebsocketServer ¶
type WebsocketServer struct { websocket.Server // Error specifies the function for generating HTTP error responses. Error func(ctx *Context, status int, reason string) // CheckOrigin returns true if the request Origin header is acceptable. If // CheckOrigin is nil, the host in the Origin header must not be set or // must match the host of the request. CheckOrigin func(ctx *Context) bool // contains filtered or unexported fields }
WebsocketServer is the iris websocket server, expose the websocket.Server the below code is a wrapper and bridge between iris-contrib/websocket and kataras/go-websocket
func NewWebsocketServer ¶
func NewWebsocketServer() *WebsocketServer
NewWebsocketServer returns an empty WebsocketServer, nothing special here.
func (*WebsocketServer) Handler ¶
func (s *WebsocketServer) Handler(ctx *Context)
Handler is the iris Handler to upgrade the request used inside RegisterRoutes
func (*WebsocketServer) OnConnection ¶
func (s *WebsocketServer) OnConnection(connectionListener func(WebsocketConnection))
OnConnection this is the main event you, as developer, will work with each of the websocket connections
func (*WebsocketServer) RegisterTo ¶
func (s *WebsocketServer) RegisterTo(station *Framework, c WebsocketConfiguration)
RegisterTo creates the client side source route and the route path Endpoint with the correct Handler receives the websocket configuration and the iris station
func (*WebsocketServer) Upgrade ¶
func (s *WebsocketServer) Upgrade(ctx *Context) error
Upgrade upgrades the HTTP server connection to the WebSocket protocol.
The responseHeader is included in the response to the client's upgrade request. Use the responseHeader to specify cookies (Set-Cookie) and the application negotiated subprotocol (Sec-Websocket-Protocol).
If the upgrade fails, then Upgrade replies to the client with an HTTP error response.