Categorygithub.com/iris-framework/iris
modulepackage
6.0.0+incompatible
Repository: https://github.com/iris-framework/iris.git
Documentation: pkg.go.dev

# README

Navigate to http://support.iris-go.com

Build Status http://goreportcard.com/report/kataras/iris Iris support forum Examples for new Gophers Docs Chat Buy me a cup of coffee
Iris is an efficient and well-designed, cross-platform, web framework with robust set of features.
Build your own high-performance web applications and APIs powered by unlimited potentials and portability.

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

Feature Overview

  • Focus on high performance
  • Automatically install and serve certificates from https://letsencrypt.org
  • Robust routing and middleware ecosystem
  • Build RESTful APIs
  • Choose your favorite routes' path syntax between httprouter and gorillamux
  • Request-Scoped Transactions
  • Group API's and subdomains with wildcard support
  • Body binding for JSON, XML, Forms, can be extended to use your own custom binders
  • More than 50 handy functions to send HTTP responses
  • View system: supporting more than 6+ template engines, with prerenders. You can still use your favorite
  • Define virtual hosts and (wildcard) subdomains with path level routing
  • Graceful shutdown
  • Limit request body
  • Localization i18N
  • Serve static files
  • Cache
  • Log requests
  • Customizable format and output for the logger
  • Customizable HTTP errors
  • Compression (Gzip)
  • Authentication
  • OAuth, OAuth2 supporting 27+ popular websites
  • JWT
  • Basic Authentication
  • HTTP Sessions
  • Add / Remove trailing slash from the URL with option to redirect
  • Redirect requests
  • HTTP to HTTPS
  • HTTP to HTTPS WWW
  • HTTP to HTTPS non WWW
  • Non WWW to WWW
  • WWW to non WWW
  • Highly scalable rich content render (Markdown, JSON, JSONP, XML...)
  • Websocket-only API similar to socket.io
  • Hot Reload on source code changes
  • Typescript integration + Web IDE
  • Checks for updates at startup
  • Highly customizable
  • Feels like you used iris forever, thanks to its Fluent API
  • And many others...

Table of Contents

Installation

The only requirement is the Go Programming Language, at least 1.8

$ go get gopkg.in/iris-framework/iris.v6

For further installation support, navigate here.

Overview

package main

import (
	"gopkg.in/iris-framework/iris.v6"
	"gopkg.in/iris-framework/iris.v6/adaptors/cors"
	"gopkg.in/iris-framework/iris.v6/adaptors/httprouter"
	"gopkg.in/iris-framework/iris.v6/adaptors/view"
)

func main() {
	// Receives optional iris.Configuration{}, see ./configuration.go
	// for more.
	app := iris.New()

	// Order doesn't matter,
	// You can split it to different .Adapt calls.
	// See ./adaptors folder for more.
	app.Adapt(
		// adapt a logger which prints all errors to the os.Stdout
		iris.DevLogger(),
		// adapt the adaptors/httprouter or adaptors/gorillamux
		httprouter.New(),
		// 5 template engines are supported out-of-the-box:
		//
		// - standard html/template
		// - amber
		// - django
		// - handlebars
		// - pug(jade)
		//
		// Use the html standard engine for all files inside "./views" folder with extension ".html"
		view.HTML("./views", ".html"),
		// Cors wrapper to the entire application, allow all origins.
		cors.New(cors.Options{AllowedOrigins: []string{"*"}}))

	// http://localhost:6300
	// Method: "GET"
	// Render ./views/index.html
	app.Get("/", func(ctx *iris.Context) {
		ctx.Render("index.html", iris.Map{"Title": "Page Title"}, iris.RenderOptions{"gzip": true})
	})

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

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

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

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

	// Start the server at 127.0.0.1:6300
	app.Listen(":6300")
}

func userAPIMiddleware(ctx *iris.Context) {
	// your code here...
	println("Request: " + ctx.Path())
	ctx.Next() // go to the next handler(s)
}

func userNotFoundHandler(ctx *iris.Context) {
	// your code here...
	ctx.HTML(iris.StatusNotFound, "<h1> User page not found </h1>")
}

func getAllHandler(ctx *iris.Context) {
	// your code here...
}

func getByIDHandler(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)
}

func saveUserHandler(ctx *iris.Context) {
	// your code here...
}

Reload on source code changes

$ go get -u github.com/kataras/rizla
$ cd $GOPATH/src/mywebapp
$ rizla main.go

Reload templates on each incoming request

app.Adapt(view.HTML("./views", ".html").Reload(true))

FAQ & Documentation

  1. Getting Started with Go+Iris

  2. Official small but practical examples

  3. Navigate through community examples too

  4. Creating A URL Shortener Service Using Go, Iris, and Bolt

  5. Godocs for deep documentation

  6. HISTORY.md is your best friend, version migrations are released there

I'll be glad to talk with you about your awesome feature requests, open a new discussion, you will be heard!

Third Party Middleware

Iris has its own middleware form of func(ctx *iris.Context) but it's also compatible with all net/http middleware forms using iris.ToHandler, i.e Negroni's middleware form of func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc).

Here is a small list of Iris compatible middleware, I'm sure you can find more:

MiddlewareAuthorDescription
bindingMatt HoltData binding from HTTP requests into structs
cloudwatchColin SteeleAWS cloudwatch metrics middleware
cspAwake NetworksContent Security Policy (CSP) support
delayJeff MartinezAdd delays/latency to endpoints. Useful when testing effects of high latency
New Relic Go AgentYadvendar ChampawatOfficial New Relic Go Agent (currently in beta)
gorelicJingwen Owen OuNew Relic agent for Go runtime
JWT MiddlewareAuth0Middleware checks for a JWT on the Authorization header on incoming requests and decodes it
logrusDan BuchLogrus-based logger
ontheflyAlexander RødsethGenerate TinySVG, HTML and CSS on the fly
permissions2Alexander RødsethCookies, users and permissions
prometheusRene ZbindenEasily create metrics endpoint for the prometheus instrumentation tool
renderCory JacobsenRender JSON, XML and HTML templates
RestGatePrasanga SiripalaSecure authentication for REST API endpoints
secureCory JacobsenMiddleware that implements a few quick security wins
statsFlorent MessaStore information about your web application (response time, etc.)
VanGoHTaylor WrobelConfigurable AWS-Style HMAC authentication middleware
xrequestidAndrea FranzMiddleware that assigns a random X-Request-Id header to each request
digitsBilal AmarniMiddleware that handles Twitter Digits authentication

Feel free to put up a PR your middleware!

Testing

The httptest package is a simple Iris helper for the httpexpect, a new library for End-to-end HTTP and REST API testing for Go.

You can find tests by navigating to the source code, i.e:

A simple test is located to ./_examples/advanced/httptest/main_test.go

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. Iris is routerless which means you can adapt any router you like, httprouter is the fastest, gorillamux has more features. With support for the most used template engines (5), you can quickly craft the perfect application.

License

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

Note that some optional components that you may use with Iris requires different license agreements.

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Functions

CERT returns a listener which contans tls.Config with the provided certificate, use for ssl.
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.
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.
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.
DefaultConfiguration returns the default configuration for an Iris station, fills the main Configuration.
DevLogger returns a new Logger which prints both ProdMode and DevMode messages to the default global logger printer.
LETSENCRYPT returns a new Automatic TLS Listener using letsencrypt.org service receives three parameters, the first is the host of the server, second can be the server name(domain) or empty if skip verification is the expected behavior (not recommended) and the third 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.
New creates and returns a fresh Iris *Framework instance with the default configuration if no 'setters' parameters passed.
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.
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.
ParseHost tries to convert a given string to an address which is compatible with net.Listener and server.
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'.
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'.
ParseScheme returns the scheme based on the host,addr,domain Note: the full scheme not just http*,https* *http:// *https://.
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.Default.Routes().Lookup("theRouteName") you can set a route name as: myRoute := iris.Default.Get("/mypath", handler)("theRouteName") that will set a name to the route and returns its iris.Route instance for further usage.
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.
RouteConflicts checks for route's middleware conflicts.
StaticHandler returns a new Handler which is ready to serve all kind of static files.
StatusText returns a text for the HTTP status code.
StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h.
TCP4 returns a new tcp4 Listener.
TCPKeepAlive returns a new tcp4 keep alive Listener.
TLS returns a new TLS Listener.
ToHandler converts different style of handlers that you used to use (usually with third-party net/http middleware) to an iris.HandlerFunc.
TOML reads Configuration from a toml-compatible document file.
ToNativeHandler converts an iris handler to http.Handler.
UNIX returns a new unix(file) Listener.
YAML reads Configuration from a configuration.yml file.

# Constants

These constants are copied from the standard flate package available Compressors.
These constants are copied from the standard flate package available Compressors.
Does only Huffman encoding.
Default values for base Iris conf.
These constants are copied from the standard flate package available Compressors.
Default values for base Iris conf.
Default values for base Iris conf.
Per-connection buffer size for requests' reading.
DefaultReadTimeout no read client timeout.
DefaultServerHostname returns the default hostname which is 0.0.0.0.
DefaultServerPort returns the default port which is 8080, not used.
DefaultWriteTimeout no serve client timeout.
DevMode is the development level logger write mode, responsible to the rest of the errors, for example if you set a app.Favicon("myfav.ico"..) and that fav doesn't exists in your system, then it printed by DevMode and app.Favicon simple doesn't works.
DynamicSubdomainIndicator where a registered path starts with '*.' then it contains a dynamic subdomain, if subdomain == "*." then its dynamic.
MethodConnect "CONNECT".
MethodDelete "DELETE".
MethodGet "GET".
MethodHead "HEAD".
MethodNone is a Virtual method to store the "offline" routes.
MethodOptions "OPTIONS".
MethodPatch "PATCH".
MethodPost "POST".
MethodPut "PUT".
MethodTrace "TRACE".
These constants are copied from the standard flate package available Compressors.
NoLayout to disable layout for a particular template file.
ProdMode the production level logger write mode, responsible to fatal errors, errors that happen which your app can't continue running.
RouterNameConfigKey is the optional key that is being registered by router adaptor.
SchemeHTTP returns "http://" (full).
SchemeHTTPS returns "https://" (full).
RFC 7231, 6.3.3.
RFC 5842, 7.1.
RFC 7231, 6.6.3.
RFC 7231, 6.5.1.
RFC 7231, 6.5.8.
RFC 7231, 6.2.1.
RFC 7231, 6.3.2.
RFC 7231, 6.5.14.
RFC 4918, 11.4.
RFC 7231, 6.5.3.
RFC 7231, 6.4.3.
RFC 7231, 6.6.5.
RFC 7231, 6.5.9.
RFC 7231, 6.6.6.
RFC 3229, 10.4.1.
RFC 4918, 11.5.
RFC 7231, 6.6.1.
RFC 7231, 6.5.10.
RFC 4918, 11.3.
RFC 5842, 7.2.
RFC 7231, 6.5.5.
RFC 7231, 6.4.2.
RFC 7231, 6.4.1.
RFC 4918, 11.1.
RFC 6585, 6.
RFC 7231, 6.3.5.
RFC 7231, 6.3.4.
RFC 7231, 6.5.6.
RFC 2774, 7.
RFC 7231, 6.5.4.
RFC 7231, 6.6.2.
RFC 7232, 4.1.
RFC 7231, 6.3.1.
RFC 7233, 4.1.
RFC 7231, 6.5.2.
RFC 7538, 3.
RFC 7232, 4.2.
RFC 6585, 3.
RFC 2518, 10.1.
RFC 7235, 3.2.
RFC 7233, 4.4.
RFC 7231, 6.5.11.
RFC 6585, 5.
RFC 7231, 6.5.7.
RFC 7231, 6.5.12.
RFC 7231, 6.3.6.
RFC 7231, 6.4.4.
RFC 7231, 6.6.4.
RFC 7231, 6.2.2.
RFC 7168, 2.3.3.
RFC 7231, 6.4.7.
RFC 6585, 4.
RFC 7235, 3.1.
RFC 7725, 3.
RFC 4918, 11.2.
RFC 7231, 6.5.13.
RFC 7231, 6.5.15.
RFC 7231, 6.4.5.
RFC 2295, 8.1.
conversions TemplateLayoutContextKey same as ViewLayoutContextKey.
Version is the current version number of the Iris web framework.
No description provided by the author
ViewLayoutContextKey is the name of the user values which can be used to set a template layout from a middleware and override the parent's.

# Variables

AllMethods contains all the http valid methods: "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", "PATCH", "OPTIONS", "TRACE".
Default is the field which keeps an empty `Framework` instance with its default configuration (config can change at runtime).
DefaultServerAddr the default server addr which is: 0.0.0.0:8080.
DefaultTimeFormat default time format for any kind of datetime parsing.
ErrPushNotSupported is returned by the Push method to indicate that HTTP/2 Push support is not available.
LimitRequestBodySize is a middleware which sets a request body size limit for all next handlers should be registered before all other handlers.
OptionCharset character encoding for various rendering used for templates and the rest of the responses Defaults to "UTF-8".
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.
OptionDisableBodyConsumptionOnUnmarshal manages the reading behavior of the context's body readers/binders.
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 Defaults to false.
OptionEnablePathEscape when is true then its escapes the path, the named path parameters (if any).
FireMethodNotAllowed if it's true router checks for StatusMethodNotAllowed(405) and fires the 405 error instead of 404 Defaults to false.
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}) Defaults to false.
MaxHeaderBytes controls the maximum number of bytes the server will read parsing the request header's keys and values, including the request line.
Other are the custom, dynamic options, can be empty.
OptionReadTimeout sets the Maximum duration before timing out read of the request.
OptionTimeFormat time format for any kind of datetime parsing.
OptionVHost is the addr or the domain that server listens to, which it's optional When to set VHost manually: 1.
OptionVScheme is the scheme (http:// or https://) putted at the template function '{{url }}' It's an optional field, When to set Scheme manually: 1.
OptionWriteTimeout sets the Maximum duration before timing out write of the response.
ProxyHandler returns a new net/http.Handler which works as 'proxy', maybe doesn't suits you look its code before using that in production.
Recorder the middleware to enable response writer recording ( *responseWriter -> *ResponseRecorder).
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.
ResetDefault resets the `.Default` to an empty *Framework with the default configuration.
StaticCacheDuration expiration duration for INACTIVE file handlers, it's a global configuration field to all iris instances.
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.
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).
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).

# Structs

Configuration the whole configuration for an Iris station instance these can be passed via options also, look at the top of this file(configuration.go).
No description provided by the author
ErrorHandlers contains all custom http errors.
No description provided by the author
Framework is our God |\| Google.Search('Greek mythology Iris').
No description provided by the author
A ResponseRecorder is used mostly by context's transactions in order to record and change if needed the body, status code and headers.
Router the visible api for RESTFUL.
No description provided by the author
No description provided by the author
TCPKeepAliveListener sets TCP keep-alive timeouts on accepted connections.
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..
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.

# Interfaces

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.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
ResponseWriter interface is used by the context to serve an HTTP handler to construct an HTTP response.
No description provided by the author
RouteRepository contains the interface which is used on custom routers contains methods and helpers to find a route by its name, and change its method, path, middleware.
RoutesInfo is the interface which contains the valid actions permitted at RUNTIME.
No description provided by the author
StaticHandlerBuilder is the web file system's Handler builder use that or the iris.StaticHandler/StaticWeb methods.
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.
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 aliases

No description provided by the author
No description provided by the author
LoggerPolicy is a simple interface which is used to log mostly system panics exception for general debugging messages is when the `Framework.Config.IsDevelopment = true`.
LogMode is the type for the LoggerPolicy write mode.
No description provided by the author
MethodChangedListener listener signature fired when route method changes.
No description provided by the author
No description provided by the author
RenderOptions is a helper type for the optional runtime options can be passed by user when Render called.
RenderPolicy is the type which you can adapt custom renderers based on the 'name', simple as that.
No description provided by the author
No description provided by the author
TemplateFuncsPolicy sets or overrides template func map.
TransactionScopeFunc the transaction's scope signature.
UnmarshalerFunc a shortcut for the Unmarshaler interface See 'Unmarshaler' and 'BodyDecoder' for more.