iris

package module
v0.0.0-...-fee71ff Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2017 License: MIT Imports: 39 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README


Build Status

Built with GoLang

Cross framework

Donation


CHANGELOG/HISTORY

Examples

Practical Guide/Docs

Chat

Iris is the fastest HTTP/2 web framework written in Go.
Easy to learn while it's highly customizable, ideally suited for
both experienced and novice developers.

If you're coming from Node.js world, this is the expressjs for the Go Programming Language.

What people say What people say

Installation

The only requirement is the Go Programming Language, at least v1.7.

$ go get -u github.com/kataras/iris/iris

Overview

package main

import (
    "github.com/kataras/iris"
	"github.com/kataras/go-template/html"
)

func main(){

   // 6 template engines are supported out-of-the-box:
   //
   // - standard html/template
   // - amber
   // - django
   // - handlebars
   // - pug(jade)
   // - markdown
   //
   // Use the html standard engine for all files inside "./views" folder with extension ".html"
   iris.UseTemplate(html.New()).Directory("./views", ".html")

  // http://localhost:6111
  // Method: "GET"
  // Render ./views/index.html
  iris.Get("/", func(ctx *iris.Context){
      ctx.Render("index.html", nil)
  })

  // Group routes, optionally: share middleware, template layout and custom http errors.
  userAPI := iris.Party("/users", userAPIMiddleware).
			 Layout("layouts/userLayout.html")
     {
	   // Fire userNotFoundHandler when Not Found
	   // inside http://localhost:6111/users/*anything
	   userAPI.OnError(404, userNotFoundHandler)

       // http://localhost:6111/users
       // Method: "GET"
       userAPI.Get("/", getAllHandler)

	   // http://localhost:6111/users/42
       // Method: "GET"
	   userAPI.Get("/:id", getByIDHandler)

	   // http://localhost:6111/users
       // Method: "POST"
	   userAPI.Post("/", saveUserHandler)
     }

	 getByIDHandler := func(ctx *iris.Context){
	     // take the :id from the path, parse to integer
		// and set it to the new userID local variable.
		userID,_ := ctx.ParamInt("id")

		// userRepo, imaginary database service <- your only job.
		user := userRepo.GetByID(userID)

		// send back a response to the client,
		// .JSON: content type as application/json; charset="utf-8"
		// iris.StatusOK: with 200 http status code.
		//
		// send user as it is or make use of any json valid golang type,
		// like the iris.Map{"username" : user.Username}.
		ctx.JSON(iris.StatusOK, user)
	 }

  // Start the server at 0.0.0.0:6111
  iris.Listen(":6111")
}

Documentation

Testing

You can find RESTFUL test examples by navigating to the following links:

FAQ

Explore these questions and join to our community chat!

Philosophy

The Iris philosophy is to provide robust tooling for HTTP, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs. Keep note that, today, iris is faster than nginx itself.

Iris does not force you to use any specific ORM or template engine. With support for the most used template engines (6+), you can quickly craft the perfect application.

People & Support

The author of Iris is @kataras.

The Success of Iris belongs to YOU with your bug reports and feature requests that made this Framework so Unique.

Who is kataras?

Hi, my name is Gerasimos Maropoulos and I'm the author of this project, let me put a few words about me.

I started to design Iris the night of the 13 March 2016, some weeks later, iris started to became famous and I have to fix many issues and implement new features, but I didn't have time to work on Iris because I had a part time job and the (software engineering) colleague which I studied.

I wanted to make iris' users proud of the framework they're using, so I decided to interrupt my studies and colleague, two days later I left from my part time job also.

Today I spend all my days and nights coding for Iris, and I'm happy about this, therefore I have zero incoming value.

  • Star the project, will help you to follow the upcoming features.
  • Donate, if you can afford any cost.
  • Write an article about Iris or even post a Tweet.

If you are interested in contributing to the Iris project, please see the document CONTRIBUTING.

Contact

Besides the fact that we have a community chat for questions or reports and ideas, stackoverflow section for generic go+iris questions and the github issues for bug reports and feature requests, you can also contact with me, as a person who is always open to help you:

Versioning

Current: v6.1.3

v5: https://github.com/kataras/iris/tree/5.0.0

License

Unless otherwise noted, the source files are distributed under the MIT License found in the LICENSE file.

Documentation

Overview

Package iris the fastest go web framework in (this) Earth.

Basic usage ----------------------------------------------------------------------

package main

import "github.com/kataras/iris"

func main() {
    iris.Get("/hi_json", func(ctx *iris.Context) {
        ctx.JSON(iris.StatusOK, iris.Map{
            "Name": "Iris",
            "Released":  "13 March 2016",
						"Stars": "5883",
        })
    })
    iris.ListenLETSENCRYPT("mydomain.com")
}

----------------------------------------------------------------------

package main

import "github.com/kataras/iris"

func main() {
	s1 := iris.New()
	s1.Get("/hi_json", func(ctx *iris.Context) {
		ctx.JSON(iris.StatusOK, iris.Map{
			"Name": "Iris",
			"Released":  "13 March 2016",
			"Stars": "5883",
		})
	})

	s2 := iris.New()
	s2.Get("/hi_raw_html", func(ctx *iris.Context) {
		ctx.HTML(iris.StatusOK, "<b> Iris </b> welcomes <h1>you!</h1>")
	})

	go s1.Listen(":8080")
	s2.Listen(":1993")
}

----------------------------------------------------------------------

For middleware, template engines, response engines, sessions, websockets, mails, subdomains, dynamic subdomains, routes, party of subdomains & routes and more

visit https://docs.iris-go.com

Index

Constants

View Source
const (
	DefaultDisablePathCorrection = false
	DefaultEnablePathEscape      = false
	DefaultCharset               = "UTF-8"
	DefaultLoggerPreffix         = "[IRIS] "
	// 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
	DefaultMaxHeaderBytes = 8096

	// DefaultReadTimeout no read client timeout
	DefaultReadTimeout = 0
	// DefaultWriteTimeout no serve client timeout
	DefaultWriteTimeout = 0
)

Default values for base Iris conf

View Source
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
)
View Source
const (
	// DefaultWebsocketWriteTimeout 15 * time.Second
	DefaultWebsocketWriteTimeout = 15 * time.Second
	// DefaultWebsocketPongTimeout 60 * time.Second
	DefaultWebsocketPongTimeout = 60 * time.Second
	// DefaultWebsocketPingPeriod (DefaultPongTimeout * 9) / 10
	DefaultWebsocketPingPeriod = (DefaultWebsocketPongTimeout * 9) / 10
	// DefaultWebsocketMaxMessageSize 1024
	DefaultWebsocketMaxMessageSize = 1024
)
View Source
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

View Source
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"
	// MethodNone is a Virtual method
	// to store the "offline" routes
	// in the mux's tree
	MethodNone = "NONE"
)
View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

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

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

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

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

HTTP status codes.

View Source
const (
	// SchemeHTTPS returns "https://" (full)
	SchemeHTTPS = "https://"
	// SchemeHTTP returns "http://" (full)
	SchemeHTTP = "http://"
)
View Source
const (
	// IsLongTermSupport flag is true when the below version number is a long-term-support version
	IsLongTermSupport = false
	// Version is the current version number of the Iris web framework
	Version = "6.1.3"
)
View Source
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"
)
View Source
const (
	// All is the string which the Emitter use to send a message to all
	All = websocket.All
	// NotMe is the string which the Emitter use to send a message to all except this websocket.Connection
	NotMe = websocket.NotMe
	// Broadcast is the string which the Emitter use to send a message to all except this websocket.Connection, same as 'NotMe'
	Broadcast = websocket.Broadcast
)

conversionals

Variables

View Source
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 net/http 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
		}
	}
	// maximum duration before timing out read of the request
	OptionReadTimeout = func(val time.Duration) OptionSet {
		return func(c *Configuration) {
			c.ReadTimeout = val
		}
	}
	// maximum duration before timing out write of the response
	OptionWriteTimeout = func(val time.Duration) OptionSet {
		return func(c *Configuration) {
			c.WriteTimeout = val
		}
	}

	// MaxHeaderBytes controls the maximum number of bytes the
	// server will read parsing the request header's keys and
	// values, including the request line. It does not limit the
	// size of the request body.
	// If zero, DefaultMaxHeaderBytes(8MB) is used.
	OptionMaxHeaderBytes = func(val int) OptionSet {
		return func(c *Configuration) {
			c.MaxHeaderBytes = val
		}
	}

	// TLSNextProto optionally specifies a function to take over
	// ownership of the provided TLS connection when an NPN/ALPN
	// protocol upgrade has occurred. The map key is the protocol
	// name negotiated. The Handler argument should be used to
	// handle HTTP requests and will initialize the Request's TLS
	// and RemoteAddr if not already set. The connection is
	// automatically closed when the function returns.
	// If TLSNextProto is nil, HTTP/2 support is enabled automatically.
	OptionTLSNextProto = func(val map[string]func(*http.Server, *tls.Conn, http.Handler)) OptionSet {
		return func(c *Configuration) {
			c.TLSNextProto = val
		}
	}

	// ConnState specifies an optional callback function that is
	// called when a client connection changes state. See the
	// ConnState type and associated constants for details.
	OptionConnState = func(val func(net.Conn, http.ConnState)) OptionSet {
		return func(c *Configuration) {
			c.ConnState = 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 registered path
	// for example, if /home/ path is requested but no handler for this Route found,
	// then the Router checks if /home handler exists, if yes,
	// (permant)redirects the client to the correct path /home
	//
	// Default is false
	OptionDisablePathCorrection = func(val bool) OptionSet {
		return func(c *Configuration) {
			c.DisablePathCorrection = val
		}

	}

	// OptionEnablePathEscape when is true then its escapes the path, the named path parameters (if any).
	OptionEnablePathEscape = func(val bool) OptionSet {
		return func(c *Configuration) {
			c.EnablePathEscape = 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
		}
	}

	// OptionDisableBodyConsumptionOnUnmarshal manages the reading behavior of the context's body readers/binders.
	// If setted to true then it
	// disables the body consumption by the `context.UnmarshalBody/ReadJSON/ReadXML`.
	//
	// By-default io.ReadAll` is used to read the body from the `context.Request.Body which is an `io.ReadCloser`,
	// if this field setted to true then a new buffer will be created to read from and the request body.
	// The body will not be changed and existing data before the context.UnmarshalBody/ReadJSON/ReadXML will be not consumed.
	OptionDisableBodyConsumptionOnUnmarshal = func(val bool) OptionSet {
		return func(c *Configuration) {
			c.DisableBodyConsumptionOnUnmarshal = 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 globally, 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

View Source
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
)
View Source
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
		}
	}
)
View Source
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
		}
	}

	// OptionWebsocketError specifies the function for generating HTTP error responses.
	OptionWebsocketError = func(val func(*Context, int, error)) 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(*http.Request) bool) OptionSet {
		return func(c *Configuration) {
			c.Websocket.CheckOrigin = val
		}
	}

	// OptionWebsocketIDGenerator used to create (and later on, set)
	// an ID for each incoming websocket connections (clients).
	// If empty then the ID is generated by the result of 64
	// random combined characters
	OptionWebsocketIDGenerator = func(val func(*http.Request) string) OptionSet {
		return func(c *Configuration) {
			c.Websocket.IDGenerator = val
		}
	}
)
View Source
var (
	// DefaultWebsocketError is the default method to manage the handshake websocket errors
	DefaultWebsocketError = func(ctx *Context, status int, reason error) {
		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(r *http.Request) bool {
		return true
	}
	// WebsocketCheckSameOrigin returns true if the origin is not set or is equal to the request host
	WebsocketCheckSameOrigin = func(r *http.Request) bool {
		origin := r.Header.Get("origin")
		if len(origin) == 0 {
			return true
		}
		u, err := url.Parse(origin)
		if err != nil {
			return false
		}
		return u.Host == r.Host
	}
)
View Source
var (
	TranslateLanguageContextKey = "language"
	TranslateFunctionContextKey = "translate"
)

TranslateLanguageContextKey & TranslateFunctionContextKey are used by i18n handlers/middleware currently we have only one: https://github.com/iris-contrib/middleware/tree/master/i18n but you can use these keys to override the i18n's cookie name (TranslateLanguageContextKey) or to store new translate function by using the ctx.Set(iris.TranslateFunctionContextKey, theTrFunc)

View Source
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 field holds the main http.Handler which can be changed.
	// if you want to get benefit with iris' context make use of:
	// ctx:= iris.AcquireCtx(http.ResponseWriter, *http.Request) 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.
	//
	// Want to change the default Router's behavior to something else like Gorilla's Mux?
	// See more: https://github.com/iris-contrib/plugin/tree/master/gorillamux
	Router    http.Handler
	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

View Source
var (
	// AllMethods contains all the http valid methods:
	// "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", "PATCH", "OPTIONS", "TRACE"
	AllMethods = [...]string{MethodGet, MethodPost, MethodPut, MethodDelete, MethodConnect, MethodHead, MethodPatch, MethodOptions, MethodTrace}
)
View Source
var (
	// CookieExpireNever the default cookie's life for sessions, unlimited (23 years)
	CookieExpireNever = time.Now().AddDate(23, 0, 0)
)
View Source
var (
	// DefaultLoggerOut is the default logger's output
	DefaultLoggerOut = os.Stdout
)
View Source
var (
	// DefaultServerAddr the default server addr which is: 0.0.0.0:8080
	DefaultServerAddr = DefaultServerHostname + ":" + strconv.Itoa(DefaultServerPort)
)
View Source
var LimitRequestBodySize = func(maxRequestBodySizeBytes int64) HandlerFunc {
	return func(ctx *Context) {
		ctx.SetMaxRequestBodySize(maxRequestBodySizeBytes)
		ctx.Next()
	}
}

LimitRequestBodySize is a middleware which sets a request body size limit for all next handlers should be registered before all other handlers

View Source
var ProxyHandler = func(redirectSchemeAndHost string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		redirectTo := redirectSchemeAndHost
		fakehost := r.URL.Host
		path := r.URL.EscapedPath()
		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
					http.Redirect(w, r, redirectTo, StatusMovedPermanently)
					return
				}
			}
		}
		if path != "/" {
			redirectTo += path
		}
		if redirectTo == r.URL.String() {
			return
		}

		http.Redirect(w, r, redirectTo, StatusMovedPermanently)
	}
}

ProxyHandler returns a new net/http.Handler which works as 'proxy', maybe doesn't suits you look its code before using that in production

View Source
var Recorder = HandlerFunc(func(ctx *Context) {
	ctx.Record()
	ctx.Next()
})

Recorder the middleware to enable response writer recording ( *responseWriter -> *ResponseRecorder)

View Source
var RequestTransactionScope = TransactionScopeFunc(func(maybeErr TransactionErrResult, ctx *Context) bool {
	if maybeErr.IsFailure() {

		ctx.ResponseWriter.SetBeforeFlush(func() {

			w := ctx.ResponseWriter.(*ResponseRecorder)
			if maybeErr.Reason != "" {

				w.SetBodyString(maybeErr.Reason)
				w.WriteHeader(maybeErr.StatusCode)
				w.SetContentType(maybeErr.ContentType)
			} else {

				ctx.EmitError(maybeErr.StatusCode)
			}
		})

		return false
	}

	return true
})

RequestTransactionScope explanation:

if scope fails (if transaction.IsFailure() == true) then the rest of the context's response (transaction or normal flow) is not written to the client, and an error status code is written instead.

View Source
var TransientTransactionScope = TransactionScopeFunc(func(maybeErr TransactionErrResult, ctx *Context) bool {
	if maybeErr.IsFailure() {
		ctx.Recorder().Reset()
	}
	return true
})

TransientTransactionScope explanation:

independent 'silent' scope, if transaction fails (if transaction.IsFailure() == true) then its response is not written to the real context no error is provided to the user. useful for the most cases.

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 registered 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(registeredPath 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 net/http.Server, CAN BE CALLED ONCE PER IRIS INSTANCE FOR YOUR SAFETY

func CERT

func CERT(addr string, cert tls.Certificate) (net.Listener, error)

CERT returns a listener which contans tls.Config with the provided certificate, use for ssl

func ChangeRouteState

func ChangeRouteState(r Route, HTTPMethod string) bool

ChangeRouteState changes the state of the route. iris.MethodNone for offline and iris.MethodGet/MethodPost/MethodPut/MethodDelete /MethodConnect/MethodOptions/MethodHead/MethodTrace/MethodPatch for online it re-builds the router

returns true if state was actually changed

see context.ExecRoute(routeName), iris.None(...) and iris.SetRouteOnline/SetRouteOffline For more details look: https://github.com/kataras/iris/issues/585

Example: https://github.com/iris-contrib/examples/tree/master/route_state

func ChangeRouter

func ChangeRouter(h http.Handler)

ChangeRouter force-changes the pre-defined iris' router while RUNTIME this function can be used to wrap the existing router with other. You can already do all these things with plugins, this function is a sugar for the craziest among us.

Example of its only usage: https://github.com/iris-contrib/plugin/blob/master/cors/plugin.go#L22 https://github.com/iris-contrib/plugin/blob/master/cors/plugin.go#L25 https://github.com/iris-contrib/plugin/blob/master/cors/plugin.go#L28

It's recommended that you use Plugin.PreBuild to change the router BEFORE the BUILD state.

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 DecodeQuery

func DecodeQuery(path string) string

DecodeQuery returns the uri parameter as url (string) useful when you want to pass something to a database and be valid to retrieve it via context.Param use it only for special cases, when the default behavior doesn't suits you.

http://www.blooberry.com/indexdot/html/topics/urlencoding.htm it uses just the url.QueryUnescape

func DecodeURL

func DecodeURL(uri string) string

DecodeURL returns the decoded uri useful when you want to pass something to a database and be valid to retrieve it via context.Param use it only for special cases, when the default behavior doesn't suits you.

http://www.blooberry.com/indexdot/html/topics/urlencoding.htm it uses just the url.Parse

func DestroyAllSessions

func DestroyAllSessions()

DestroyAllSessions removes all sessions from the server-side memory (and database if registered). Client's session cookie will still exist but it will be reseted on the next request.

func DestroySessionByID

func DestroySessionByID(sid string)

DestroySessionByID removes the session entry from the server-side memory (and database if registered). Client's session cookie will still exist but it will be reseted on the next request.

It's safe to use it even if you are not sure if a session with that id exists.

func EmitError

func EmitError(statusCode int, ctx *Context)

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

func HTMLEscape(s string) string

HTMLEscape returns a string which has no valid html code

func IsRunning

func IsRunning() bool

IsRunning returns true if server is running

func LETSENCRYPT

func LETSENCRYPT(addr string, cacheFileOptional ...string) (net.Listener, error)

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

func LETSENCRYPTPROD(addr string, cacheDirOptional ...string) (net.Listener, error)

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

func ListenLETSENCRYPT(addr string, cacheFileOptional ...string)

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

func ListenTLS(addr string, certFile string, keyFile string)

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

func ListenUNIX(addr string, mode os.FileMode)

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 Must

func Must(err error)

Must panics on error, it panics on registered iris' logger

func OnError

func OnError(statusCode int, handlerFn HandlerFunc)

OnError registers a custom http error handler

func ParseHost

func ParseHost(addr string) string

ParseHost tries to convert a given string to an address which is compatible with net.Listener and server

func ParseHostname

func ParseHostname(addr string) string

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

func ParsePort(addr string) int

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

func ParseScheme(domain string) string

ParseScheme returns the scheme based on the host,addr,domain Note: the full scheme not just http*,https* *http:// *https://

func Path

func Path(routeName string, args ...interface{}) string

Path used to check arguments with the route's named parameters and return the correct url if parse failed returns empty string

func Proxy

func Proxy(proxyAddr string, redirectSchemeAndHost string) func() error

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 Reserve

func Reserve() error

Reserve re-starts the server using the last .Serve's listener

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

func RouteConflicts(r *route, with string) bool

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

func Serve(ln net.Listener) error

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 SetRouteOffline

func SetRouteOffline(r Route) bool

SetRouteOffline sets the state of the route to "offline" and re-builds the router

returns true if state was actually changed

see context.ExecRoute(routeName), iris.None(...) and iris.SetRouteOnline/SetRouteOffline For more details look: https://github.com/kataras/iris/issues/585

Example: https://github.com/iris-contrib/examples/tree/master/route_state

func SetRouteOnline

func SetRouteOnline(r Route, HTTPMethod string) bool

SetRouteOnline sets the state of the route to "online" with a specific http method it re-builds the router

returns true if state was actually changed

see context.ExecRoute(routeName), iris.None(...) and iris.SetRouteOnline/SetRouteOffline For more details look: https://github.com/kataras/iris/issues/585

Example: https://github.com/iris-contrib/examples/tree/master/route_state

func StatusText

func StatusText(code int) string

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

func TCP4

func TCP4(addr string) (net.Listener, error)

TCP4 returns a new tcp4 Listener

func TCPKeepAlive

func TCPKeepAlive(addr string) (net.Listener, error)

TCPKeepAlive returns a new tcp keep alive Listener

func TLS

func TLS(addr, certFile, keyFile string) (net.Listener, error)

TLS returns a new TLS Listener

func TemplateSourceString

func TemplateSourceString(src string, pageContext interface{}) string

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 ToNativeHandler

func ToNativeHandler(station *Framework, h Handler) http.Handler

ToNativeHandler converts an iris handler to http.Handler

func UNIX

func UNIX(addr string, mode os.FileMode) (net.Listener, error)

UNIX returns a new unix(file) Listener

func URL

func URL(routeName string, args ...interface{}) (url string)

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 should be called right before Listen functions

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 should be called right before Listen functions

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.

Example: https://github.com/iris-contrib/examples/tree/master/template_engines/template_prerender

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

func UseTemplateFunc

func UseTemplateFunc(functionName string, function interface{})

UseTemplateFunc sets or replaces a TemplateFunc from the shared available TemplateFuncMap defaults are the iris.URL and iris.Path, all the template engines supports the following: {{ url "mynamedroute" "pathParameter_ifneeded"} } {{ urlpath "mynamedroute" "pathParameter_ifneeded" }} {{ render "header.html" }} {{ render_r "header.html" }} // partial relative path to current page {{ yield }} {{ current }}

See more https:/github.com/iris-contrib/examples/tree/master/template_engines/template_funcmap

Types

type BodyDecoder

type BodyDecoder interface {
	Decode(data []byte) error
}

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 net/http 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

	ReadTimeout  time.Duration // maximum duration before timing out read of the request
	WriteTimeout time.Duration // maximum duration before timing out write of the response

	// MaxHeaderBytes controls the maximum number of bytes the
	// server will read parsing the request header's keys and
	// values, including the request line. It does not limit the
	// size of the request body.
	// If zero, DefaultMaxHeaderBytes is used.
	MaxHeaderBytes int

	// TLSNextProto optionally specifies a function to take over
	// ownership of the provided TLS connection when an NPN/ALPN
	// protocol upgrade has occurred. The map key is the protocol
	// name negotiated. The Handler argument should be used to
	// handle HTTP requests and will initialize the Request's TLS
	// and RemoteAddr if not already set. The connection is
	// automatically closed when the function returns.
	// If TLSNextProto is nil, HTTP/2 support is enabled automatically.
	TLSNextProto map[string]func(*http.Server, *tls.Conn, http.Handler)

	// ConnState specifies an optional callback function that is
	// called when a client connection changes state. See the
	// ConnState type and associated constants for details.
	ConnState func(net.Conn, http.ConnState)

	// 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 registered path
	// for example, if /home/ path is requested but no handler for this Route found,
	// then the Router checks if /home handler exists, if yes,
	// (permant)redirects the client to the correct path /home
	//
	// Default is false
	DisablePathCorrection bool

	// EnablePathEscape when is true then its escapes the path, the named parameters (if any).
	// Change to false it if you want something like this https://github.com/kataras/iris/issues/135 to work
	//
	// When do you need to Disable(false) it:
	// accepts parameters with slash '/'
	// Request: http://localhost:8080/details/Project%2FDelta
	// ctx.Param("project") returns the raw named parameter: Project%2FDelta
	// which you can escape it manually with net/url:
	// projectName, _ := url.QueryUnescape(c.Param("project").
	// Look here: https://github.com/kataras/iris/issues/135 for more
	//
	// Default is false
	EnablePathEscape 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

	// DisableBodyConsumptionOnUnmarshal manages the reading behavior of the context's body readers/binders.
	// If setted to true then it
	// disables the body consumption by the `context.UnmarshalBody/ReadJSON/ReadXML`.
	//
	// By-default io.ReadAll` is used to read the body from the `context.Request.Body which is an `io.ReadCloser`,
	// if this field setted to true then a new buffer will be created to read from and the request body.
	// The body will not be changed and existing data before the context.UnmarshalBody/ReadJSON/ReadXML will be not consumed.
	DisableBodyConsumptionOnUnmarshal bool

	// 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 globally, 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 {
	ResponseWriter // *responseWriter by default, when record is on then *ResponseRecorder
	Request        *http.Request

	//keep track all registered middleware (handlers)
	Middleware Middleware //  exported because is useful for debugging

	// Pos is the position number of the Context, look .Next to understand
	Pos int // 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(w http.ResponseWriter, r *http.Request) *Context

AcquireCtx gets an Iris' Context from pool see .ReleaseCtx & .Serve

func (*Context) BeginTransaction

func (ctx *Context) BeginTransaction(pipe func(transaction *Transaction))

BeginTransaction starts a scoped transaction.

Can't say a lot here because it will take more than 200 lines to write about. You can search third-party articles or books on how Business Transaction works (it's quite simple, especially here).

Note that this is unique and new (=I haver never seen any other examples or code in Golang on this subject, so far, as with the most of iris features...) it's not covers all paths, such as databases, this should be managed by the libraries you use to make your database connection, this transaction scope is only for context's response. Transactions have their own middleware ecosystem also, look iris.go:UseTransaction.

See https://github.com/iris-contrib/examples/tree/master/transactions for more

func (*Context) Data

func (ctx *Context) Data(status int, v []byte) error

Data writes out the raw bytes as binary data.

func (*Context) Deadline

func (ctx *Context) Deadline() (deadline time.Time, ok bool)

Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.

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) Done

func (ctx *Context) Done() <-chan struct{}

Done returns a channel that's closed when work done on behalf of this context should be canceled. Done may return nil if this context can never be canceled. Successive calls to Done return the same value.

WithCancel arranges for Done to be closed when cancel is called; WithDeadline arranges for Done to be closed when the deadline expires; WithTimeout arranges for Done to be closed when the timeout elapses.

Done is provided for use in select statements:

// Stream generates values with DoSomething and sends them to out
// until DoSomething returns an error or ctx.Done is closed.
func Stream(ctx context.Context, out chan<- Value) error {
	for {
		v, err := DoSomething(ctx)
		if err != nil {
			return err
		}
		select {
		case <-ctx.Done():
			return ctx.Err()
		case out <- v:
		}
	}
}

See http://blog.golang.org/pipelines for more examples of how to use a Done channel for cancelation.

func (*Context) EmitError

func (ctx *Context) EmitError(statusCode int)

EmitError executes the custom error by the http status code passed to the function

func (*Context) Err

func (ctx *Context) Err() error

Err returns a non-nil error value after Done is closed. Err returns Canceled if the context was canceled or DeadlineExceeded if the context's deadline passed. No other values for Err are defined. After Done is closed, successive calls to Err return the same value.

func (*Context) ExecRoute

func (ctx *Context) ExecRoute(r Route) *Context

ExecRoute calls any route (mostly "offline" route) like it was requested by the user, but it is not. Offline means that the route is registered to the iris and have all features that a normal route has BUT it isn't available by browsing, its handlers executed only when other handler's context call them it can validate paths, has sessions, path parameters and all.

You can find the Route by iris.Lookup("theRouteName") you can set a route name as: myRoute := iris.Get("/mypath", handler)("theRouteName") that will set a name to the route and returns its iris.Route instance for further usage.

It doesn't changes the global state, if a route was "offline" it remains offline.

see ExecRouteAgainst(routeName, againstRequestPath string), iris.None(...) and iris.SetRouteOnline/SetRouteOffline For more details look: https://github.com/kataras/iris/issues/585

Example: https://github.com/iris-contrib/examples/tree/master/route_state

func (*Context) ExecRouteAgainst

func (ctx *Context) ExecRouteAgainst(r Route, againstRequestPath string) *Context

ExecRouteAgainst calls any iris.Route against a 'virtually' request path like it was requested by the user, but it is not. Offline means that the route is registered to the iris and have all features that a normal route has BUT it isn't available by browsing, its handlers executed only when other handler's context call them it can validate paths, has sessions, path parameters and all.

You can find the Route by iris.Lookup("theRouteName") you can set a route name as: myRoute := iris.Get("/mypath", handler)("theRouteName") that will set a name to the route and returns its iris.Route instance for further usage.

It doesn't changes the global state, if a route was "offline" it remains offline.

see ExecRoute(routeName), iris.None(...) and iris.SetRouteOnline/SetRouteOffline For more details look: https://github.com/kataras/iris/issues/585

Example: https://github.com/iris-contrib/examples/tree/master/route_state

func (*Context) FormFile

func (ctx *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile returns the first file for the provided form key. FormFile calls ctx.Request.ParseMultipartForm and ParseForm if necessary.

same as Request.FormFile

func (*Context) FormValue

func (ctx *Context) FormValue(name string) string

FormValue returns a single form value by its name/key

func (*Context) FormValues

func (ctx *Context) FormValues() map[string][]string

FormValues returns all post data values with their keys form data, get, post & put query arguments

NOTE: A check for nil is necessary for zero results

func (*Context) Framework

func (ctx *Context) Framework() *Framework

Framework returns the Iris instance, containing the configuration and all other fields

func (*Context) Get

func (ctx *Context) Get(key string) interface{}

Get returns the user's value from a key if doesn't exists returns nil

func (*Context) GetCookie

func (ctx *Context) GetCookie(name string) string

GetCookie returns cookie's value by it's name returns empty string if nothing was found

func (*Context) GetHandlerName

func (ctx *Context) GetHandlerName() string

GetHandlerName as requested returns the stack-name of the function which the Middleware is setted from

func (*Context) GetInt

func (ctx *Context) GetInt(key string) (int, error)

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) GetString

func (ctx *Context) GetString(key string) string

GetString same as Get but returns the value as string if nothing founds returns empty string ""

func (*Context) HTML

func (ctx *Context) HTML(status int, htmlContents string)

HTML writes html string with a http status

func (*Context) Host

func (ctx *Context) Host() string

Host returns the host part of the current url

func (*Context) IsAjax

func (ctx *Context) IsAjax() bool

IsAjax returns true if this request is an 'ajax request'( XMLHttpRequest)

Read more at: http://www.w3schools.com/ajax/

func (*Context) IsRecording

func (ctx *Context) IsRecording() (*ResponseRecorder, bool)

IsRecording returns the response recorder and a true value when the response writer is recording the status code, body, headers and so on, else returns nil and false

func (*Context) IsStopped

func (ctx *Context) IsStopped() bool

IsStopped checks and returns true if the current position of the Context is 255, means that the StopExecution has called

func (*Context) JSON

func (ctx *Context) JSON(status int, v interface{}) error

JSON marshals the given interface object and writes the JSON response.

func (*Context) JSONP

func (ctx *Context) JSONP(status int, callback string, v interface{}) error

JSONP marshals the given interface object and writes the JSON response.

func (*Context) Log

func (ctx *Context) Log(format string, a ...interface{})

Log logs to the iris defined logger

func (*Context) Markdown

func (ctx *Context) Markdown(status int, markdown string)

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

func (ctx *Context) MarkdownString(markdownText string) string

MarkdownString parses the (dynamic) markdown string and returns the converted html string

func (*Context) MaxAge

func (ctx *Context) MaxAge() int64

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) Method

func (ctx *Context) Method() string

Method returns the http request method same as *http.Request.Method

func (*Context) MustRender

func (ctx *Context) MustRender(name string, binding interface{}, options ...map[string]interface{})

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

func (ctx *Context) Param(key string) string

Param returns the string representation of the key's path named parameter's value same as GetString

func (*Context) ParamDecoded

func (ctx *Context) ParamDecoded(key string) string

ParamDecoded returns a url-query-decoded path parameter's value

func (*Context) ParamInt

func (ctx *Context) ParamInt(key string) (int, error)

ParamInt returns the int representation of the key's path named parameter's value same as GetInt

func (*Context) ParamInt64

func (ctx *Context) ParamInt64(key string) (int64, error)

ParamInt64 returns the int64 representation of the key's path named parameter's value

func (*Context) ParamsLen

func (ctx *Context) ParamsLen() (n int)

ParamsLen tries to return all the stored values which values are string, probably most of them will be the path parameters

func (*Context) ParamsSentence

func (ctx *Context) ParamsSentence() string

ParamsSentence returns a string implementation of all parameters that this context keeps hasthe form of key1=value1,key2=value2...

func (*Context) Path

func (ctx *Context) Path() string

Path returns the full escaped path as string for unescaped use: ctx.RequestCtx.RequestURI() or RequestPath(escape bool)

func (*Context) PostValue

func (ctx *Context) PostValue(name string) string

PostValue returns a form's only-post value by its name same as Request.PostFormValue

func (*Context) ReadForm

func (ctx *Context) ReadForm(formObject interface{}) error

ReadForm binds the formObject with the form data it supports any kind of struct

func (*Context) ReadJSON

func (ctx *Context) ReadJSON(jsonObject interface{}) error

ReadJSON reads JSON from request's body and binds it to a value of any json-valid type

func (*Context) ReadXML

func (ctx *Context) ReadXML(xmlObject interface{}) error

ReadXML reads XML from request's body and binds it to a value of any xml-valid type

func (*Context) Record

func (ctx *Context) Record()

Record transforms the context's basic and direct responseWriter to a ResponseRecorder which can be used to reset the body, reset headers, get the body, get & set the status code at any time and more

func (*Context) Recorder

func (ctx *Context) Recorder() *ResponseRecorder

Recorder returns the context's ResponseRecorder if not recording then it starts recording and returns the new context's ResponseRecorder

func (*Context) Redirect

func (ctx *Context) Redirect(urlToRedirect string, statusHeader ...int)

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

func (ctx *Context) RedirectTo(routeName string, args ...interface{})

RedirectTo does the same thing as Redirect but instead of receiving a uri or path it receives a route name

func (*Context) RemoteAddr

func (ctx *Context) RemoteAddr() string

RemoteAddr tries to return the real client's request IP

func (*Context) RemoveCookie

func (ctx *Context) RemoveCookie(name string)

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

func (ctx *Context) RequestHeader(k string) string

RequestHeader returns the request header's value accepts one parameter, the key of the header (string) returns string

func (*Context) RequestPath

func (ctx *Context) RequestPath(escape bool) string

RequestPath returns the requested path

func (*Context) SendFile

func (ctx *Context) SendFile(filename string, destinationName string)

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

func (ctx *Context) ServeFile(filename string, gzipCompression bool) error

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 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) ServerHost

func (ctx *Context) ServerHost() string

ServerHost returns the server host taken by *http.Request.Host

func (*Context) Session

func (ctx *Context) Session() sessions.Session

Session returns the current session ( && flash messages )

func (*Context) SessionDestroy

func (ctx *Context) SessionDestroy()

SessionDestroy destroys the whole session, calls the provider's destroy and remove the cookie

func (*Context) Set

func (ctx *Context) Set(key string, value interface{})

Set sets a value to a key in the values map

func (*Context) SetClientCachedBody

func (ctx *Context) SetClientCachedBody(status int, bodyContent []byte, cType string, modtime time.Time)

SetClientCachedBody like SetBody but it sends with an expiration datetime which is managed by the client-side (all major browsers supports this feature)

func (*Context) SetContentType

func (ctx *Context) SetContentType(s string)

SetContentType sets the response writer's header key 'Content-Type' to a given value(s)

func (*Context) SetCookie

func (ctx *Context) SetCookie(cookie *http.Cookie)

SetCookie adds a cookie

func (*Context) SetCookieKV

func (ctx *Context) SetCookieKV(name, value string)

SetCookieKV adds a cookie, receives just a key(string) and a value(string)

Expires on 2 hours by default(unchable) use ctx.SetCookie or http.SetCookie instead for more control.

func (*Context) SetHeader

func (ctx *Context) SetHeader(k string, v string)

SetHeader write to the response writer's header to a given key the given value

func (*Context) SetMaxRequestBodySize

func (ctx *Context) SetMaxRequestBodySize(limitOverBytes int64)

SetMaxRequestBodySize sets a limit to the request body size should be called before reading the request body from the client

func (*Context) SetStatusCode

func (ctx *Context) SetStatusCode(statusCode int)

SetStatusCode sets the status code header to the response

same as .WriteHeader, iris takes cares of your status code seriously

func (*Context) SkipTransactions

func (ctx *Context) SkipTransactions()

SkipTransactions if called then skip the rest of the transactions or all of them if called before the first transaction

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) StreamWriter

func (ctx *Context) StreamWriter(writer func(w io.Writer) bool)

StreamWriter registers the given stream writer for populating response body.

Access to context's and/or its' members is forbidden from writer.

This function may be used in the following cases:

  • if response body is too big (more than iris.LimitRequestBodySize(if setted)).
  • if response body is streamed from slow external sources.
  • if response body must be streamed to the client in chunks. (aka `http server push`).

receives a function which receives the response writer and returns false when it should stop writing, otherwise true in order to continue

func (*Context) Subdomain

func (ctx *Context) Subdomain() (subdomain string)

Subdomain returns the subdomain (string) of this request, if any

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) Text

func (ctx *Context) Text(status int, v string) error

Text writes out a string as plain text.

func (*Context) TransactionsSkipped

func (ctx *Context) TransactionsSkipped() bool

TransactionsSkipped returns true if the transactions skipped or canceled at all.

func (*Context) Translate

func (ctx *Context) Translate(format string, args ...interface{}) string

Translate is the i18n (localization) middleware's function, it just calls the ctx.getFmt("translate"). "translate" is the key of the i18n middlweare for more plaese look: https://github.com/iris-contrib/examples/tree/master/middleware_internationalization_i18n

func (*Context) TryWriteGzip

func (ctx *Context) TryWriteGzip(b []byte) (int, error)

TryWriteGzip accepts bytes, which are compressed to gzip format and sent to the client. If client does not supprots gzip then the contents are written as they are, uncompressed.

func (*Context) URLParam

func (ctx *Context) URLParam(key string) string

URLParam returns the get parameter from a request , if any

func (*Context) URLParamInt

func (ctx *Context) URLParamInt(key string) (int, error)

URLParamInt returns the url query parameter as int value from a request , returns error on parse fail

func (*Context) URLParamInt64

func (ctx *Context) URLParamInt64(key string) (int64, error)

URLParamInt64 returns the url query parameter as int64 value from a request , returns error on parse fail

func (*Context) URLParams

func (ctx *Context) URLParams() map[string]string

URLParams returns a map of GET query parameters separated by comma if more than one it returns an empty map if nothing founds

func (*Context) URLParamsAsMulti

func (ctx *Context) URLParamsAsMulti() map[string][]string

URLParamsAsMulti returns a map of list contains the url get parameters

func (*Context) UnmarshalBody

func (ctx *Context) UnmarshalBody(v interface{}, unmarshaler Unmarshaler) error

UnmarshalBody reads the request's body and binds it to a value or pointer of any type Examples of usage: context.ReadJSON, context.ReadXML

func (*Context) Value

func (ctx *Context) Value(key interface{}) interface{}

Value returns the value associated with this context for key, or nil if no value is associated with key. Successive calls to Value with the same key returns the same result.

Use context values only for request-scoped data that transits processes and API boundaries, not for passing optional parameters to functions.

A key identifies a specific value in a Context. Functions that wish to store values in Context typically allocate a key in a global variable then use that key as the argument to context.WithValue and Context.Value. A key can be any type that supports equality; packages should define keys as an unexported type to avoid collisions.

Packages that define a Context key should provide type-safe accessors for the values stores using that key:

// Package user defines a User type that's stored in Contexts.
package user

import "golang.org/x/net/context"

// User is the type of value stored in the Contexts.
type User struct {...}

// key is an unexported type for keys defined in this package.
// This prevents collisions with keys defined in other packages.
type key int

// userKey is the key for user.User values in Contexts.  It is
// unexported; clients use user.NewContext and user.FromContext
// instead of using this key directly.
var userKey key = 0

// NewContext returns a new Context that carries value u.
func NewContext(ctx context.Context, u *User) context.Context {
	return context.WithValue(ctx, userKey, u)
}

// FromContext returns the User value stored in ctx, if any.
func FromContext(ctx context.Context) (*User, bool) {
	u, ok := ctx.Value(userKey).(*User)
	return u, ok
}

func (*Context) ValuesLen

func (ctx *Context) ValuesLen() (n int)

ValuesLen returns the total length of the user values storage, some of them maybe path parameters

func (*Context) VirtualHostname

func (ctx *Context) VirtualHostname() string

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

func (ctx *Context) VisitAllCookies(visitor func(key string, value string))

VisitAllCookies takes a visitor which loops on each (request's) cookie key and value

func (*Context) VisitValues

func (ctx *Context) VisitValues(visitor func(string, interface{}))

VisitValues calls visitor for each existing context's temp values.

visitor must not retain references to key and value after returning. Make key and/or value copies if you need storing them after returning.

func (*Context) WriteGzip

func (ctx *Context) WriteGzip(b []byte) (int, error)

WriteGzip accepts bytes, which are compressed to gzip format and sent to the client. returns the number of bytes written and an error ( if the client doesn' supports gzip compression)

func (*Context) XML

func (ctx *Context) XML(status int, v interface{}) error

XML marshals the given interface object and writes the XML response.

type Framework

type Framework struct {
	Available chan bool
	//
	// Router field holds the main http.Handler which can be changed.
	// if you want to get benefit with iris' context make use of:
	// ctx:= iris.AcquireCtx(http.ResponseWriter, *http.Request) 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.
	//
	// Want to change the default Router's behavior to something else like Gorilla's Mux?
	// See more: https://github.com/iris-contrib/plugin/tree/master/gorillamux
	Router http.Handler

	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 registered 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(w http.ResponseWriter, r *http.Request) *Context

AcquireCtx gets an Iris' Context from pool see .ReleaseCtx & .Serve

func (Framework) Any

func (api Framework) Any(registeredPath 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 nethttp.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) ChangeRouteState

func (s *Framework) ChangeRouteState(r Route, HTTPMethod string) bool

ChangeRouteState changes the state of the route. iris.MethodNone for offline and iris.MethodGet/MethodPost/MethodPut/MethodDelete /MethodConnect/MethodOptions/MethodHead/MethodTrace/MethodPatch for online it re-builds the router

returns true if state was actually changed

func (*Framework) ChangeRouter

func (s *Framework) ChangeRouter(h http.Handler)

ChangeRouter force-changes the pre-defined iris' router while RUNTIME this function can be used to wrap the existing router with other. You can already do all these things with plugins, this function is a sugar for the craziest among us.

Example of its only usage: https://github.com/iris-contrib/plugin/blob/master/cors/plugin.go#L22 https://github.com/iris-contrib/plugin/blob/master/cors/plugin.go#L25 https://github.com/iris-contrib/plugin/blob/master/cors/plugin.go#L28

It's recommended that you use Plugin.PreBuild to change the router BEFORE the BUILD state.

func (*Framework) CheckForUpdates

func (s *Framework) 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. Note: exported func CheckForUpdates exists because of the reason that an update can be executed while Iris is running

func (*Framework) Close

func (s *Framework) 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 (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) DestroyAllSessions

func (s *Framework) DestroyAllSessions()

DestroyAllSessions removes all sessions from the server-side memory (and database if registered). Client's session cookie will still exist but it will be reseted on the next request.

func (*Framework) DestroySessionByID

func (s *Framework) DestroySessionByID(sid string)

DestroySessionByID removes the session entry from the server-side memory (and database if registered). Client's session cookie will still exist but it will be reseted on the next request.

It's safe to use it even if you are not sure if a session with that id exists.

func (Framework) Done

func (api Framework) Done(handlers ...Handler) MuxAPI

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

func (api Framework) EmitError(statusCode int, ctx *Context)

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 (desktop, 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, registeredPath 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, registeredPath string, handlersFn ...HandlerFunc) RouteNameFunc

HandleFunc registers and returns a route with a method string, path string and a handler registeredPath 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) IsRunning

func (s *Framework) IsRunning() bool

IsRunning returns true if server is running

func (Framework) Layout

func (api Framework) Layout(tmplLayoutFile string) MuxAPI

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

func (s *Framework) 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 (*Framework) ListenLETSENCRYPT

func (s *Framework) ListenLETSENCRYPT(addr string, cacheFileOptional ...string)

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

func (s *Framework) ListenTLS(addr string, certFile, keyFile string)

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

func (s *Framework) ListenUNIX(addr string, mode os.FileMode)

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) Lookup

func (s *Framework) Lookup(routeName string) Route

Lookup returns a registered route by its name

func (*Framework) Lookups

func (s *Framework) Lookups() (routes []Route)

Lookups returns all registered routes

func (*Framework) Must

func (s *Framework) Must(err error)

Must panics on error, it panics on registered iris' logger

func (Framework) None

func (api Framework) None(path string, handlersFn ...HandlerFunc) RouteNameFunc

None registers an "offline" route see context.ExecRoute(routeName), iris.None(...) and iris.SetRouteOnline/SetRouteOffline For more details look: https://github.com/kataras/iris/issues/585

Example: https://github.com/iris-contrib/examples/tree/master/route_state

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

func (s *Framework) Path(routeName string, args ...interface{}) string

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

func (s *Framework) ReleaseCtx(ctx *Context)

ReleaseCtx puts the Iris' Context back to the pool in order to be re-used see .AcquireCtx & .Serve

func (*Framework) Reserve

func (s *Framework) Reserve() error

Reserve re-starts the server using the last .Serve's listener

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

func (s *Framework) Serve(ln net.Listener) error

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) SetRouteOffline

func (s *Framework) SetRouteOffline(r Route) bool

SetRouteOffline sets the state of the route to "offline" and re-builds the router

returns true if state was actually changed

func (*Framework) SetRouteOnline

func (s *Framework) SetRouteOnline(r Route, HTTPMethod string) bool

SetRouteOnline sets the state of the route to "online" with a specific http method it re-builds the router

returns true if state was actually changed

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 distributed 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/master/static_files_embedded

func (Framework) StaticHandler

func (api Framework) StaticHandler(reqPath string, systemPath string, showList bool, enableGzip bool, exceptRoutes ...Route) HandlerFunc

StaticHandler returns a new Handler which serves static files

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, exceptRoutes ...Route) RouteNameFunc

StaticWeb returns a handler that serves HTTP requests with the contents of the file system rooted at directory.

first parameter: the route path second parameter: the system directory third OPTIONAL parameter: the exception routes

(= give priority to these routes instead of the static handler)

for more options look iris.StaticHandler.

iris.StaticWeb("/static", "./static")

As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html".

StaticWeb calls the StaticHandler(reqPath, systemPath, listingDirectories: false, gzip: false ).

func (*Framework) TemplateSourceString

func (s *Framework) TemplateSourceString(src string, pageContext interface{}) string

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

func (s *Framework) URL(routeName string, args ...interface{}) (url string)

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) MuxAPI

Use registers Handler middleware returns itself

func (Framework) UseFunc

func (api Framework) UseFunc(handlersFn ...HandlerFunc) MuxAPI

UseFunc registers HandlerFunc middleware returns itself

func (*Framework) UseGlobal

func (s *Framework) 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 should be called right before Listen functions

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 should be called right before Listen functions

func (*Framework) UsePreRender

func (s *Framework) 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.

Example: https://github.com/iris-contrib/examples/tree/master/template_engines/template_prerender

func (*Framework) UseSerializer

func (s *Framework) 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 (*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

func (*Framework) UseTemplateFunc

func (s *Framework) UseTemplateFunc(functionName string, function interface{})

UseTemplateFunc sets or replaces a TemplateFunc from the shared available TemplateFuncMap defaults are the iris.URL and iris.Path, all the template engines supports the following: {{ url "mynamedroute" "pathParameter_ifneeded"} } {{ urlpath "mynamedroute" "pathParameter_ifneeded" }} {{ render "header.html" }} {{ render_r "header.html" }} // partial relative path to current page {{ yield }} {{ current }}

See more https:/github.com/iris-contrib/examples/tree/master/template_engines/template_funcmap

type FrameworkAPI

type FrameworkAPI interface {
	MuxAPI
	Set(options ...OptionSetter)
	Must(err error)

	Build()
	Serve(ln net.Listener) error
	Listen(addr string)
	ListenTLS(addr string, certFilePath string, keyFilePath string)
	ListenLETSENCRYPT(addr string, cacheOptionalStoreFilePath ...string)
	ListenUNIX(fileOrAddr string, fileMode os.FileMode)
	Close() error
	Reserve() error

	AcquireCtx(w http.ResponseWriter, r *http.Request) *Context
	ReleaseCtx(ctx *Context)

	CheckForUpdates(check bool)

	UseSessionDB(sessDB sessions.Database)
	DestroySessionByID(sid string)
	DestroyAllSessions()

	UseSerializer(contentType string, serializerEngine serializer.Serializer)
	UsePreRender(prerenderFunc PreRender)
	UseTemplateFunc(functionName string, function interface{})
	UseTemplate(tmplEngine template.Engine) *template.Loader

	UseGlobal(middleware ...Handler)
	UseGlobalFunc(middleware ...HandlerFunc)

	ChangeRouter(http.Handler)
	Lookup(routeName string) Route
	Lookups() []Route
	SetRouteOnline(r Route, HTTPMethod string) bool
	SetRouteOffline(r Route) bool
	ChangeRouteState(r Route, HTTPMethod string) bool

	Path(routeName string, optionalPathParameters ...interface{}) (routePath string)
	URL(routeName string, optionalPathParameters ...interface{}) (routeURL string)

	TemplateString(file string, binding interface{}, options ...map[string]interface{}) (parsedTemplate string)
	TemplateSourceString(src string, binding interface{}) (parsedTemplate string)
	SerializeToString(string, interface{}, ...map[string]interface{}) (serializedContent string)

	Cache(handlerToCache HandlerFunc, expiration time.Duration) (cachedHandler HandlerFunc)
}

FrameworkAPI contains the main Iris Public API

type Handler

type Handler interface {
	Serve(ctx *Context) // iris-specific
}

Handler the main Iris Handler interface.

type HandlerAPI

type HandlerAPI interface{}

HandlerAPI empty interface used for .API

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 <=2 seconds 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 Prioritize

func Prioritize(r Route) HandlerFunc

Prioritize is a middleware which executes a route against this path when the request's Path has a prefix of the route's STATIC PART is not executing ExecRoute to determinate if it's valid, for performance reasons if this function is not enough for you and you want to test more than one parameterized path then use the: if c := ExecRoute(r); c == nil { /* move to the next, the route is not valid */ }

You can find the Route by iris.Lookup("theRouteName") you can set a route name as: myRoute := iris.Get("/mypath", handler)("theRouteName") that will set a name to the route and returns its iris.Route instance for further usage.

if the route found then it executes that and don't continue to the next handler if not found then continue to the next handler

func StaticHandler

func StaticHandler(reqPath string, systemPath string, showList bool, enableGzip bool) HandlerFunc

StaticHandler returns a new Handler which serves static files

func StripPrefix

func StripPrefix(prefix string, h HandlerFunc) HandlerFunc

StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error.

func ToHandler

func ToHandler(handler interface{}) HandlerFunc

ToHandler converts an http.Handler/HandlerFunc to iris.Handler(Func)

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(reqRelativeRootPath string, middleware ...HandlerFunc) MuxAPI
	// middleware serial, appending
	Use(middleware ...Handler) MuxAPI
	UseFunc(middleware ...HandlerFunc) MuxAPI
	Done(middleware ...Handler) MuxAPI
	DoneFunc(middleware ...HandlerFunc) MuxAPI

	// main handlers
	Handle(method string, reqPath string, middleware ...Handler) RouteNameFunc
	HandleFunc(method string, reqPath string, middleware ...HandlerFunc) RouteNameFunc
	API(reqRelativeRootPath string, api HandlerAPI, middleware ...HandlerFunc)

	// virtual method for "offline" routes new feature
	None(reqRelativePath string, Middleware ...HandlerFunc) RouteNameFunc
	// http methods
	Get(reqRelativePath string, middleware ...HandlerFunc) RouteNameFunc
	Post(reqRelativePath string, middleware ...HandlerFunc) RouteNameFunc
	Put(reqRelativePath string, middleware ...HandlerFunc) RouteNameFunc
	Delete(reqRelativePath string, middleware ...HandlerFunc) RouteNameFunc
	Connect(reqRelativePath string, middleware ...HandlerFunc) RouteNameFunc
	Head(reqRelativePath string, middleware ...HandlerFunc) RouteNameFunc
	Options(reqRelativePath string, middleware ...HandlerFunc) RouteNameFunc
	Patch(reqRelativePath string, middleware ...HandlerFunc) RouteNameFunc
	Trace(reqRelativePath string, middleware ...HandlerFunc) RouteNameFunc
	Any(reqRelativePath string, middleware ...HandlerFunc)

	// static content
	StaticServe(systemFilePath string, optionalReqRelativePath ...string) RouteNameFunc
	StaticContent(reqRelativePath string, contentType string, contents []byte) RouteNameFunc
	StaticEmbedded(reqRelativePath string, contentType string, assets func(string) ([]byte, error), assetsNames func() []string) RouteNameFunc
	Favicon(systemFilePath string, optionalReqRelativePath ...string) RouteNameFunc
	// static file system
	StaticHandler(reqRelativePath string, systemPath string, showList bool, enableGzip bool, exceptRoutes ...Route) HandlerFunc
	StaticWeb(reqRelativePath string, systemPath string, exceptRoutes ...Route) RouteNameFunc

	// party layout for template engines
	Layout(layoutTemplateFileName string) MuxAPI

	// errors
	OnError(statusCode int, handler HandlerFunc)
	EmitError(statusCode int, ctx *Context)
}

MuxAPI the visible api for the serveMux

func Done

func Done(handlers ...Handler) MuxAPI

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

func Layout(tmplLayoutFile string) MuxAPI

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

func Use

func Use(handlers ...Handler) MuxAPI

Use registers Handler middleware

func UseFunc

func UseFunc(handlersFn ...HandlerFunc) MuxAPI

UseFunc registers HandlerFunc middleware

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
	PostInterrupt(PostInterruptFunc)
	DoPostInterrupt(*Framework)
	PostInterruptFired() 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 PostInterruptFunc

type PostInterruptFunc func(*Framework)

PostInterruptFunc implements the simple function listener for the PostInterrupt(*Framework)

Read more here: https://github.com/kataras/iris/blob/master/HISTORY.md#608---609 Example: https://github.com/iris-contrib/examples/tree/master/os_interrupt

func (PostInterruptFunc) PostInterrupt

func (fn PostInterruptFunc) PostInterrupt(station *Framework)

PostInterrupt it's being called only one time, when os.Interrupt system event catched graceful shutdown can be done here

Read more here: https://github.com/kataras/iris/blob/master/HISTORY.md#608---609 Example: https://github.com/iris-contrib/examples/tree/master/os_interrupt

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

type PreDownloadFunc func(Plugin, string)

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.

Example: https://github.com/iris-contrib/examples/tree/master/template_engines/template_prerender

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 ResponseRecorder

type ResponseRecorder struct {
	// contains filtered or unexported fields
}

A ResponseRecorder is used mostly by context's transactions in order to record and change if needed the body, status code and headers.

You are NOT limited to use that too: just call context.ResponseWriter.Recorder()/Record() and response writer will act like context.ResponseWriter.(*iris.ResponseRecorder)

func (*ResponseRecorder) Body

func (w *ResponseRecorder) Body() []byte

Body returns the body tracked from the writer so far do not use this for edit.

func (ResponseRecorder) CloseNotify

func (w ResponseRecorder) CloseNotify() <-chan bool

CloseNotify returns a channel that receives at most a single value (true) when the client connection has gone away.

CloseNotify may wait to notify until Request.Body has been fully read.

After the Handler has returned, there is no guarantee that the channel receives a value.

If the protocol is HTTP/1.1 and CloseNotify is called while processing an idempotent request (such a GET) while HTTP/1.1 pipelining is in use, the arrival of a subsequent pipelined request may cause a value to be sent on the returned channel. In practice HTTP/1.1 pipelining is not enabled in browsers and not seen often in the wild. If this is a problem, use HTTP/2 or only use CloseNotify on methods such as POST.

func (ResponseRecorder) ContentType

func (w ResponseRecorder) ContentType() string

ContentType returns the content type, if not setted returns empty string

func (*ResponseRecorder) Flush

func (w *ResponseRecorder) Flush()

Flush sends any buffered data to the client.

func (*ResponseRecorder) Header

func (w *ResponseRecorder) Header() http.Header

Header returns the header map that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example). To suppress implicit response headers, set their value to nil.

func (ResponseRecorder) Hijack

func (w ResponseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack lets the caller take over the connection. After a call to Hijack(), the HTTP server library will not do anything else with the connection.

It becomes the caller's responsibility to manage and close the connection.

The returned net.Conn may have read or write deadlines already set, depending on the configuration of the Server. It is the caller's responsibility to set or clear those deadlines as needed.

func (*ResponseRecorder) Reset

func (w *ResponseRecorder) Reset()

Reset resets the response body, headers and the status code header

func (*ResponseRecorder) ResetBody

func (w *ResponseRecorder) ResetBody()

ResetBody resets the response body

func (*ResponseRecorder) ResetHeaders

func (w *ResponseRecorder) ResetHeaders()

ResetHeaders clears the temp headers

func (ResponseRecorder) SetBeforeFlush

func (w ResponseRecorder) SetBeforeFlush(cb func())

SetBeforeFlush registers the unique callback which called exactly before the response is flushed to the client

func (*ResponseRecorder) SetBody

func (w *ResponseRecorder) SetBody(b []byte)

SetBody overrides the body and sets it to a slice of bytes value

func (*ResponseRecorder) SetBodyString

func (w *ResponseRecorder) SetBodyString(s string)

SetBodyString overrides the body and sets it to a string value

func (ResponseRecorder) SetContentType

func (w ResponseRecorder) SetContentType(cType string)

SetContentType sets the content type header

func (ResponseRecorder) StatusCode

func (w ResponseRecorder) StatusCode() int

StatusCode returns the status code header value

func (*ResponseRecorder) Write

func (w *ResponseRecorder) Write(contents []byte) (int, error)

Adds the contents to the body reply, it writes the contents temporarily to a value in order to be flushed at the end of the request, this method give us the opportunity to reset the body if needed.

If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType.

Depending on the HTTP protocol version and the client, calling Write or WriteHeader may prevent future reads on the Request.Body. For HTTP/1.x requests, handlers should read any needed request body data before writing the response. Once the headers have been flushed (due to either an explicit Flusher.Flush call or writing enough data to trigger a flush), the request body may be unavailable. For HTTP/2 requests, the Go HTTP server permits handlers to continue to read the request body while concurrently writing the response. However, such behavior may not be supported by all HTTP/2 clients. Handlers should read before writing if possible to maximize compatibility.

func (ResponseRecorder) WriteHeader

func (w ResponseRecorder) WriteHeader(statusCode int)

WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.

func (*ResponseRecorder) WriteString

func (w *ResponseRecorder) WriteString(s string) (n int, err error)

WriteString writes a simple string to the response.

Returns the number of bytes written and any write error encountered

func (*ResponseRecorder) Writef

func (w *ResponseRecorder) Writef(format string, a ...interface{}) (n int, err error)

Writef formats according to a format specifier and writes to the response.

Returns the number of bytes written and any write error encountered

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	http.Hijacker
	http.CloseNotifier

	Writef(format string, a ...interface{}) (n int, err error)
	WriteString(s string) (n int, err error)
	SetContentType(cType string)
	ContentType() string
	StatusCode() int
	SetBeforeFlush(cb func())
	// contains filtered or unexported methods
}

ResponseWriter interface is used by the context to serve an HTTP handler to construct an HTTP response.

A ResponseWriter may not be used after the Handler.ServeHTTP method has returned.

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
	// SetMethod sets the route's method
	// requires re-build of the iris.Router
	SetMethod(string)

	// Path returns the path
	Path() string

	// staticPath returns the static part of the path
	StaticPath() string

	// SetPath changes/sets the path for this route
	SetPath(string)
	// Middleware returns the slice of Handler([]Handler) registered to this route
	Middleware() Middleware
	// SetMiddleware changes/sets the middleware(handler(s)) for this route
	SetMiddleware(Middleware)
	// IsOnline returns true if the route is marked as "online" (state)
	IsOnline() bool
}

Route contains some useful information about a route

func Lookup

func Lookup(routeName string) Route

Lookup returns a registered route by its name

func Lookups

func Lookups() []Route

Lookups returns all registered routes

type RouteNameFunc

type RouteNameFunc func(customRouteName string) Route

RouteNameFunc the func returns from the MuxAPi's methods, optionally sets the name of the Route (*route)

You can find the Route by iris.Lookup("theRouteName") you can set a route name as: myRoute := iris.Get("/mypath", handler)("theRouteName") that will set a name to the route and returns its iris.Route instance for further usage.

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 (desktop, 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, registeredPath 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, registeredPath string, handlersFn ...HandlerFunc) RouteNameFunc

HandleFunc registers and returns a route with a method string, path string and a handler registeredPath is the relative url path

func Head(path string, handlersFn ...HandlerFunc) RouteNameFunc

Head registers a route for the Head http method

func None

func None(path string, handlersFn ...HandlerFunc) RouteNameFunc

None registers an "offline" route see context.ExecRoute(routeName), iris.None(...) and iris.SetRouteOnline/SetRouteOffline For more details look: https://github.com/kataras/iris/issues/585

Example: https://github.com/iris-contrib/examples/tree/master/route_state

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 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 distributed 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/master/static_files_embedded

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, exceptRoutes ...Route) RouteNameFunc

StaticWeb returns a handler that serves HTTP requests with the contents of the file system rooted at directory.

first parameter: the route path second parameter: the system directory third OPTIONAL parameter: the exception routes

(= give priority to these routes instead of the static handler)

for more options look iris.StaticHandler.

iris.StaticWeb("/static", "./static")

As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html".

StaticWeb calls the StaticHandler(reqPath, systemPath, listingDirectories: false, gzip: false ).

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

Set implements the OptionSetter of the sessions package

type StaticHandlerBuilder

type StaticHandlerBuilder interface {
	Path(requestRoutePath string) StaticHandlerBuilder
	Gzip(enable bool) StaticHandlerBuilder
	Listing(listDirectoriesOnOff bool) StaticHandlerBuilder
	StripPath(yesNo bool) StaticHandlerBuilder
	Except(r ...Route) StaticHandlerBuilder
	Build() HandlerFunc
}

StaticHandlerBuilder is the web file system's Handler builder use that or the iris.StaticHandler/StaticWeb methods

func NewStaticHandlerBuilder

func NewStaticHandlerBuilder(dir string) StaticHandlerBuilder

NewStaticHandlerBuilder returns a new Handler which serves static files supports gzip, no listing and much more Note that, this static builder returns a Handler it doesn't cares about the rest of your iris configuration.

Use the iris.StaticHandler/StaticWeb in order to serve static files on more automatic way this builder is used by people who have more complicated application structure and want a fluent api to work on.

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)}

func (TCPKeepAliveListener) Accept

func (ln TCPKeepAliveListener) Accept() (c net.Conn, err error)

Accept implements the listener and sets the keep alive period which is 3minutes

type Transaction

type Transaction struct {
	Context *Context
	// contains filtered or unexported fields
}

Transaction gives the users the opportunity to code their route handlers cleaner and safier it receives a scope which is decided when to send an error to the user, recover from panics stop the execution of the next transactions and so on...

it's default scope is the TransientTransactionScope which is silently skips the current transaction's response if transaction.Complete accepts a non-empty error.

Create and set custom transactions scopes with transaction.SetScope.

For more information please view the tests

func (*Transaction) Complete

func (t *Transaction) Complete(err error)

Complete completes the transaction rollback and send an error when the error is not empty. The next steps depends on its Scope.

The error can be a type of NewTransactionErrResult()

func (*Transaction) SetScope

func (t *Transaction) SetScope(scope TransactionScope)

SetScope sets the current transaction's scope iris.RequestTransactionScope || iris.TransientTransactionScope (default)

type TransactionErrResult

type TransactionErrResult struct {
	StatusCode int
	// if reason is empty then the already relative registered (custom or not)
	// error will be executed if the scope allows that.
	Reason      string
	ContentType string
}

TransactionErrResult could be named also something like 'MaybeError', it is useful to send it on transaction.Complete in order to execute a custom error mesasge to the user.

in simple words it's just a 'traveler message' between the transaction and its scope. it is totally optional

func NewTransactionErrResult

func NewTransactionErrResult() TransactionErrResult

NewTransactionErrResult returns a new transaction result with the given error message, it can be empty too, but if not then the transaction's scope is decided what to do with that

func (TransactionErrResult) Error

func (err TransactionErrResult) Error() string

Error returns the reason given by the user or an empty string

func (TransactionErrResult) IsFailure

func (err TransactionErrResult) IsFailure() bool

IsFailure returns true if this is an actual error

type TransactionScope

type TransactionScope interface {
	// EndTransaction returns if can continue to the next transactions or not (false)
	// called after Complete, empty or not empty error
	EndTransaction(maybeErr TransactionErrResult, ctx *Context) bool
}

TransactionScope is the manager of the transaction's response, can be resseted and skipped from its parent context or execute an error or skip other transactions

type TransactionScopeFunc

type TransactionScopeFunc func(maybeErr TransactionErrResult, ctx *Context) bool

TransactionScopeFunc the transaction's scope signature

func (TransactionScopeFunc) EndTransaction

func (tsf TransactionScopeFunc) EndTransaction(maybeErr TransactionErrResult, ctx *Context) bool

EndTransaction ends the transaction with a callback to itself, implements the TransactionScope interface

type Unmarshaler

type Unmarshaler interface {
	Unmarshal(data []byte, v interface{}) error
}

Unmarshaler is the interface implemented by types that can unmarshal any raw data TIP INFO: Any v object which implements the BodyDecoder can be override the unmarshaler

type UnmarshalerFunc

type UnmarshalerFunc func(data []byte, v interface{}) error

UnmarshalerFunc a shortcut for the Unmarshaler interface

See 'Unmarshaler' and 'BodyDecoder' for more

func (UnmarshalerFunc) Unmarshal

func (u UnmarshalerFunc) Unmarshal(data []byte, v interface{}) error

Unmarshal parses the X-encoded data and stores the result in the value pointed to by v. Unmarshal uses the inverse of the encodings that Marshal uses, allocating maps, slices, and pointers as necessary.

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
	// 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 error)
	// 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(r *http.Request) bool
	// IDGenerator used to create (and later on, set)
	// an ID for each incoming websocket connections (clients).
	// If empty then the ID is generated by the result of 64
	// random combined characters
	IDGenerator func(r *http.Request) string
}

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

	// Config:
	// if endpoint is not empty then this configuration is used instead of the station's
	// useful when the user/dev wants more than one websocket server inside one iris instance.
	Config WebsocketConfiguration
	// 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(station *Framework) *WebsocketServer

NewWebsocketServer returns a new empty unitialized websocket server it runs on first OnConnection

func (*WebsocketServer) OnConnection

func (ws *WebsocketServer) OnConnection(connectionListener func(WebsocketConnection))

OnConnection this is the main event you, as developer, will work with each of the websocket connections

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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