Categorygithub.com/pavelz/iris
modulepackage
4.5.0+incompatible
Repository: https://github.com/pavelz/iris.git
Documentation: pkg.go.dev

# README


Build Status

https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg

Platforms

License

Built with GoLang


Releases

Examples

Practical Guide/Docs

Chat

The fastest back-end web framework written in Go.
Easy to learn, while it's highly customizable.
Ideally suited for both experienced and novice Developers.

News

Feature Overview

  • Focus on high performance
  • Automatically install TLS certificates from https://letsencrypt.org
  • Robust routing and middleware ecosystem
  • Build RESTful APIs
  • Group API's and subdomains
  • Body binding for JSON, XML, and any form element
  • More than 40 handy functions to send HTTP responses
  • Database Communication with any ORM
  • Define virtual hosts and (wildcard) subdomains with path level routing
  • Graceful shutdown
  • Limit request body
  • Localization i18N
  • Serve static files
  • Log requests
  • Define your format and output for the logger
  • Define custom HTTP errors handlers
  • Gzip response
  • 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
  • View system supporting more than six template engines, you can still use anything you like
  • Highly scalable rich render (Markdown, JSON, JSONP, XML...)
  • Websocket API similar to socket.io
  • Hot Reload
  • Typescript integration + Web IDE
  • Checks for updates at startup
  • Highly customizable

Quick Start

Installation

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

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

Hello, World!

$ cat helloworld.go
package main

import "github.com/kataras/iris"

func main(){

  iris.Get("/", func(ctx *iris.Context){
    ctx.Write("Hello, %s", "World!")
  })

  iris.Get("/myjson", func(ctx *iris.Context){
    ctx.JSON(iris.StatusOK, iris.Map{
      "Name": "Iris",
      "Released": "13 March 2016",
      "Stars": 5281,
    })
  })

  iris.Listen(":8080")
}

$ go run helloworld.go

Navigate to http://localhost:8080 and you should see Hello, World!

New

// New with default configuration
app := iris.New()

app.Listen(....)

// New with configuration struct
app := iris.New(iris.Configuration{ DisablePathEscape: true})

app.Listen(...)

// Default station
iris.Listen(...)

// Default station with custom configuration
iris.Config.DisablePathEscape = true

iris.Listen(...)

Listening

Serve(ln net.Listener) error

ln, err := net.Listen("tcp4", ":8080")
if err := iris.Serve(ln); err != nil {
   panic(err)
}

Listen(addr string)

iris.Listen(":8080")

ListenTLS(addr string, certFile, keyFile string)

iris.ListenTLS(":8080", "./ssl/mycert.cert", "./ssl/mykey.key")

ListenLETSENCRYPT(addr string)

iris.ListenLETSENCRYPT(":8080")

And

ListenUNIX(addr string, mode os.FileMode)
Close() error
Reserve() error
IsRunning() bool

Routing

iris.Get("/products/:id", getProduct)
iris.Post("/products", saveProduct)
iris.Put("products/:id", editProduct)
iris.Delete("/products/:id", deleteProduct)

And

iris.Patch("", ...)
iris.Connect("", ...)
iris.Options("", ...)
iris.Trace("", ...)

Path Parameters

func getProduct(ctx *iris.Context){
  // Get id from path '/products/:id'
  id := ctx.Param("id")
}

Query Parameters

/details?color=blue&weight=20

func details(ctx *iris.Context){
  color:= ctx.URLParam("color")
  weight:= ctx.URLParamInt("weight")
}

Form application/x-www-form-urlencoded

METHOD: POST | PATH: /save

namevalue
nameGerasimos Maropoulos
email[email protected]
func save(ctx *iris.Context) {
	// Get name and email
	name := ctx.FormValueString("name")
	email := ctx.FormValueString("email")
}

Form multipart/form-data

POST /save

namevalue
nameGerasimos Maropoulos
email[email protected]
avataravatar
func save(ctx *iris.Context)  {
	// Get name and email
	name := ctx.FormValueString("name")
	email := ctx.FormValueString("email")
	// Get avatar
	avatar, err := ctx.FormFile("avatar")
	if err != nil {
       ctx.EmitError(iris.StatusInternalServerError)
       return
	}

	// Source
	src, err := avatar.Open()
	if err != nil {
       ctx.EmitError(iris.StatusInternalServerError)
       return
	}
	defer src.Close()

	// Destination
	dst, err := os.Create(avatar.Filename)
	if err != nil {
       ctx.EmitError(iris.StatusInternalServerError)
       return
	}
	defer dst.Close()

	// Copy
	if _, err = io.Copy(dst, src); err != nil {
       ctx.EmitError(iris.StatusInternalServerError)
       return
	}

	ctx.HTML(iris.StatusOK, "<b>Thanks!</b>")
}

Handling Request

  • Bind JSON or XML or form payload into Go struct based on Content-Type request header.
  • Render response as JSON or XML with status code.
type User struct {
	Name  string `json:"name" xml:"name" form:"name"`
	Email string `json:"email" xml:"email" form:"email"`
}

iris.Post("/users", func(ctx *iris.Context) {
	u := new(User)
	if err := ctx.ReadJSON(u); err != nil {
       ctx.EmitError(iris.StatusInternalServerError)
       return
	}
	ctx.JSON(iris.StatusCreated, u)
   // or
   // ctx.XML(iris.StatusCreated, u)
   // ctx.JSONP(...)
   // ctx.HTML(iris.StatusCreated, "<b>Hi "+u.Name+"</b>")
   // ctx.Markdown(iris.StatusCreated, "## Name: "+u.Name)
})
NameDescriptionUsage
JSON JSON Serializer (Default)example 1,example 2, book section
JSONP JSONP Serializer (Default)example 1,example 2, book section
XML XML Serializer (Default)example 1,example 2, book section
Markdown Markdown Serializer (Default)example 1,example 2, book section
TextText Serializer (Default)example 1, book section
Binary Data Binary Data Serializer (Default)example 1, book section

HTTP Errors

You can define your own handlers when http error occurs.

package main

import (
	"github.com/kataras/iris"
)

func main() {

	iris.OnError(iris.StatusInternalServerError, func(ctx *iris.Context) {
        ctx.Write("CUSTOM 500 INTERNAL SERVER ERROR PAGE")
		// or ctx.Render, ctx.HTML any render method you want
		ctx.Log("http status: 500 happened!")
	})

	iris.OnError(iris.StatusNotFound, func(ctx *iris.Context) {
		ctx.Write("CUSTOM 404 NOT FOUND ERROR PAGE")
		ctx.Log("http status: 404 happened!")
	})

	// emit the errors to test them
	iris.Get("/500", func(ctx *iris.Context) {
		ctx.EmitError(iris.StatusInternalServerError) // ctx.Panic()
	})

	iris.Get("/404", func(ctx *iris.Context) {
		ctx.EmitError(iris.StatusNotFound) // ctx.NotFound()
	})

	iris.Listen(":80")

}


Static Content

Serve files or directories, use the correct for your case, if you don't know which one, just use the Static(relative string, systemPath string, stripSlashes int).

// StaticHandler returns a HandlerFunc to serve static system directory
// Accepts 5 parameters
//
// first param is the systemPath (string)
// Path to the root directory to serve files from.
//
// second is the stripSlashes (int) level
// * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar"
// * stripSlashes = 1, original path: "/foo/bar", result: "/bar"
// * stripSlashes = 2, original path: "/foo/bar", result: ""
//
// third is the compress (bool)
// Transparently compresses responses if set to true.
//
// The server tries minimizing CPU usage by caching compressed files.
// It adds FSCompressedFileSuffix suffix to the original file name and
// tries saving the resulting compressed file under the new file name.
// So it is advisable to give the server write access to Root
// and to all inner folders in order to minimze CPU usage when serving
// compressed responses.
//
// fourth is the generateIndexPages (bool)
// Index pages for directories without files matching IndexNames
// are automatically generated if set.
//
// Directory index generation may be quite slow for directories
// with many files (more than 1K), so it is discouraged enabling
// index pages' generation for such directories.
//
// fifth is the indexNames ([]string)
// List of index file names to try opening during directory access.
//
// For example:
//
//     * index.html
//     * index.htm
//     * my-super-index.xml
//
StaticHandler(systemPath string, stripSlashes int, compress bool,
                  generateIndexPages bool, indexNames []string) HandlerFunc

// Static registers a route which serves a system directory
// this doesn't generates an index page which list all files
// no compression is used also, for these features look at StaticFS func
// accepts three parameters
// first parameter is the request url path (string)
// second parameter is the system directory (string)
// third parameter is the level (int) of stripSlashes
// * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar"
// * stripSlashes = 1, original path: "/foo/bar", result: "/bar"
// * stripSlashes = 2, original path: "/foo/bar", result: ""
Static(relative string, systemPath string, stripSlashes int)

// StaticFS registers a route which serves a system directory
// generates an index page which list all files
// uses compression which file cache, if you use this method it will generate compressed files also
// think this function as small fileserver with http
// accepts three parameters
// first parameter is the request url path (string)
// second parameter is the system directory (string)
// third parameter is the level (int) of stripSlashes
// * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar"
// * stripSlashes = 1, original path: "/foo/bar", result: "/bar"
// * stripSlashes = 2, original path: "/foo/bar", result: ""
StaticFS(relative string, systemPath string, stripSlashes int)

// StaticWeb same as Static but if index.html e
// xists and request uri is '/' then display the index.html's contents
// accepts three parameters
// first parameter is the request url path (string)
// second parameter is the system directory (string)
// third parameter is the level (int) of stripSlashes
// * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar"
// * stripSlashes = 1, original path: "/foo/bar", result: "/bar"
// * stripSlashes = 2, original path: "/foo/bar", result: ""
StaticWeb(relative string, systemPath string, stripSlashes int)

// 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 the second parameter is empty, otherwise the requestPath is the second parameter
// it uses gzip compression (compression on each request, no file cache)
StaticServe(systemPath string, requestPath ...string)

iris.Static("/public", "./static/assets/", 1)
//-> /public/assets/favicon.ico
iris.StaticFS("/ftp", "./myfiles/public", 1)
iris.StaticWeb("/","./my_static_html_website", 1)
StaticServe(systemPath string, requestPath ...string)

Manual static file serving

// ServeFile serves a view file, to send a file
// 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
ServeFile(filename string, gzipCompression bool) error

Serve static individual file


iris.Get("/txt", func(ctx *iris.Context) {
    ctx.ServeFile("./myfolder/staticfile.txt", false)
}

Templates

HTML Template Engine, defaulted

<!-- file ./templates/hi.html -->

<html>
<head>
<title>Hi Iris</title>
</head>
<body>
	<h1>Hi {{.Name}}
</body>
</html>
// file ./main.go
package main

import "github.com/kataras/iris"

func main() {
	iris.Config.IsDevelopment = true // this will reload the templates on each request
	iris.Get("/hi", hi)
	iris.Listen(":8080")
}

func hi(ctx *iris.Context) {
	ctx.MustRender("hi.html", struct{ Name string }{Name: "iris"})
}

NameDescriptionUsage
HTML/Default Engine HTML Template Engine (Default)example , book section
Django Engine Django Template Engineexample , book section
Pug/Jade Engine Pug Template Engineexample , book section
Handlebars Engine Handlebars Template Engineexample , book section
Amber Engine Amber Template Engineexample , book section
Markdown Engine Markdown Template Engineexample , book section

Each section of the README has its own - more advanced - subject on the book, so be sure to check book for any further research

Read more

Middleware ecosystem


import (
  "github.com/iris-contrib/middleware/logger"
  "github.com/iris-contrib/middleware/cors"
  "github.com/iris-contrib/middleware/basicauth"
)
// Root level middleware
iris.Use(logger.New())
iris.Use(cors.Default())

// Group level middleware
authConfig := basicauth.Config{
    Users:      map[string]string{"myusername": "mypassword", "mySecondusername": "mySecondpassword"},
    Realm:      "Authorization Required", // if you don't set it it's "Authorization Required"
    ContextKey: "mycustomkey",            // if you don't set it it's "user"
    Expires:    time.Duration(30) * time.Minute,
}

authentication := basicauth.New(authConfig)

g := iris.Party("/admin")
g.Use(authentication)

// Route level middleware
logme := func(ctx *iris.Context)  {
		println("request to /products")
		ctx.Next()
}
iris.Get("/products", logme, func(ctx *iris.Context) {
	 ctx.Text(iris.StatusOK, "/products")
})
NameDescriptionUsage
Basicauth Middleware HTTP Basic authenticationexample 1, example 2, book section
JWT Middleware JSON Web Tokensexample , book section
Cors Middleware Cross Origin Resource Sharing W3 specificationhow to use
Secure Middleware Facilitates some quick security winsexample
I18n Middleware Simple internationalizationexample, book section
Recovery Middleware Safety recover the station from panicexample
Logger Middleware Logs every requestexample, book section
Profile Middleware Http profiling for debuggingexample
Editor PluginAlm-tools, a typescript online IDE/Editorbook section
Typescript PluginAuto-compile client-side typescript filesbook section
OAuth,OAuth2 PluginUser Authentication was never be easier, supports >27 providersexample, book section
Iris control PluginBasic (browser-based) control over your Iris stationexample, book section

Sessions

If you notice a bug or issue post it here.

  • Cleans the temp memory when a session is idle, and re-allocates it to the temp memory when it's necessary. The most used sessions are optimized to be in the front of the memory's list.

  • Supports any type of database, currently only Redis and LevelDB.

A session can be defined as a server-side storage of information that is desired to persist throughout the user's interaction with the web application.

Instead of storing large and constantly changing data via cookies in the user's browser (i.e. CookieStore), only a unique identifier is stored on the client side called a "session id". This session id is passed to the web server on every request. The web application uses the session id as the key for retrieving the stored data from the database/memory. The session data is then available inside the iris.Context.

iris.Get("/", func(ctx *iris.Context) {
		ctx.Write("You should navigate to the /set, /get, /delete, /clear,/destroy instead")
	})

	iris.Get("/set", func(ctx *iris.Context) {

		//set session values
		ctx.Session().Set("name", "iris")

		//test if setted here
		ctx.Write("All ok session setted to: %s", ctx.Session().GetString("name"))
	})

	iris.Get("/get", func(ctx *iris.Context) {
		// get a specific key as a string.
		// returns an empty string if the key was not found.
		name := ctx.Session().GetString("name")

		ctx.Write("The name on the /set was: %s", name)
	})

	iris.Get("/delete", func(ctx *iris.Context) {
		// delete a specific key
		ctx.Session().Delete("name")
	})

	iris.Get("/clear", func(ctx *iris.Context) {
		// removes all entries
		ctx.Session().Clear()
	})

	iris.Get("/destroy", func(ctx *iris.Context) {
		// destroy/removes the entire session and cookie
		ctx.SessionDestroy()
		ctx.Log("You have to refresh the page to completely remove the session (on browsers), so the name should NOT be empty NOW, is it?\n ame: %s\n\nAlso check your cookies in your browser's cookies, should be no field for localhost/127.0.0.1 (or whatever you use)", ctx.Session().GetString("name"))
		ctx.Write("You have to refresh the page to completely remove the session (on browsers), so the name should NOT be empty NOW, is it?\nName: %s\n\nAlso check your cookies in your browser's cookies, should be no field for localhost/127.0.0.1 (or whatever you use)", ctx.Session().GetString("name"))
	})

	iris.Listen(":8080")

Each section of the README has its own - more advanced - subject on the book, so be sure to check book for any further research

Read more

Websockets

// file ./main.go
package main

import (
    "fmt"
    "github.com/kataras/iris"
)

type clientPage struct {
    Title string
    Host  string
}

func main() {
    iris.Static("/js", "./static/js", 1)

    iris.Get("/", func(ctx *iris.Context) {
        ctx.Render("client.html", clientPage{"Client Page", ctx.HostString()})
    })

    // the path at which the websocket client should register itself to
    iris.Config.Websocket.Endpoint = "/my_endpoint"

    var myChatRoom = "room1"
    iris.Websocket.OnConnection(func(c iris.WebsocketConnection) {

        c.Join(myChatRoom)

        c.On("chat", func(message string) {
            // to all except this connection ->
            //c.To(iris.Broadcast).Emit("chat", "Message from: "+c.ID()+"-> "+message)

            // to the client ->
            //c.Emit("chat", "Message from myself: "+message)

            // send the message to the whole room,
            // all connections which are inside this room will receive this message
            c.To(myChatRoom).Emit("chat", "From: "+c.ID()+": "+message)
        })

        c.OnDisconnect(func() {
            fmt.Printf("\nConnection with ID: %s has been disconnected!", c.ID())
        })
    })

    iris.Listen(":8080")
}

// file js/chat.js
var messageTxt;
var messages;

$(function () {

    messageTxt = $("#messageTxt");
    messages = $("#messages");


    ws = new Ws("ws://" + HOST + "/my_endpoint");
    ws.OnConnect(function () {
        console.log("Websocket connection enstablished");
    });

    ws.OnDisconnect(function () {
        appendMessage($("<div><center><h3>Disconnected</h3></center></div>"));
    });

    ws.On("chat", function (message) {
        appendMessage($("<div>" + message + "</div>"));
    })

    $("#sendBtn").click(function () {
        //ws.EmitMessage(messageTxt.val());
        ws.Emit("chat", messageTxt.val().toString());
        messageTxt.val("");
    })

})


function appendMessage(messageDiv) {
    var theDiv = messages[0]
    var doScroll = theDiv.scrollTop == theDiv.scrollHeight - theDiv.clientHeight;
    messageDiv.appendTo(messages)
    if (doScroll) {
        theDiv.scrollTop = theDiv.scrollHeight - theDiv.clientHeight;
    }
}
<!-- file templates/client.html -->
<html>

<head>
    <title>My iris-ws</title>
</head>

<body>
    <div id="messages" style="border-width:1px;border-style:solid;height:400px;width:375px;">

    </div>
    <input type="text" id="messageTxt" />
    <button type="button" id="sendBtn">Send</button>
    <script type="text/javascript">
        var HOST = {{.Host}}
    </script>
    <script src="js/vendor/jquery-2.2.3.min.js" type="text/javascript"></script>
    <!-- /iris-ws.js is served automatically by the server -->
    <script src="/iris-ws.js" type="text/javascript"></script>
    <!-- -->
    <script src="js/chat.js" type="text/javascript"></script>
</body>

</html>

View a working example by navigating here and if you need more than one websocket server click here.

Each section of the README has its own - more advanced - subject on the book, so be sure to check book for any further research

Read more

Need help?

FAQ

Explore these questions or navigate to the community chat.

Support

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
  • Donate
  • :earth_americas: spread the word
  • Contribute to the project

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, you can quickly craft the perfect application.

Benchmarks

This Benchmark test aims to compare the whole HTTP request processing between Go web frameworks.

Benchmark Wizzard July 21, 2016- Processing Time Horizontal Graph

The results have been updated on July 21, 2016

The second is an article I just found(3 October 2016) which compares Iris vs Nginx vs Nodejs express, it was written in Thai, so I used google to translate it to english.

Iris vs Nginx vs Nodejs express

The results showed that the req / sec iris do best at around 70k-50k, followed by nginx and nginx-php-fpm and nodejs respectively. The error golang-iris and nginx work equally, followed by the final nginx and php-fpm at a ratio of 1: 1.

You can read the full article here.

Testing

I recommend writing your API tests using this new library, httpexpect which supports Iris and fasthttp now, after my request here. You can find Iris examples here, here and here.

Versioning

Current: v4.5.0

Iris is an active project

Read more about Semantic Versioning 2.0.0

Todo

Iris is a Community-Driven Project, waiting for your suggestions and feature requests!

People

The big thanks goes to all people who help building this framework with feature-requests & bug reports!

The author of Iris is @kataras. If you're willing to donate, feel free to navigate to the DONATIONS PAGE.

Contributing

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

License

This project is licensed under the MIT License, Copyright (c) 2016 Gerasimos Maropoulos.

# Packages

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

# Functions

AcquireCtx gets an Iris' Context from pool see .ReleaseCtx & .Serve.
Any registers a route for ALL of the http methods (Get,Post,Put,Head,Patch,Options,Connect,Delete).
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.
Build builds the whole framework's parts together DO NOT CALL IT MANUALLY IF YOU ARE NOT: SERVE IRIS BEHIND AN EXTERNAL CUSTOM fasthttp.Server, CAN BE CALLED ONCE PER IRIS INSTANCE FOR YOUR SAFETY.
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.
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()).
Connect registers a route for the Connect http method.
DecodeFasthttpURL returns the path decoded as url useful when you want to pass something to a database and be valid to retrieve it via context.Param use it only for special cases, when the default behavior doesn't suits you.
DecodeURL returns the uri parameter as url (string) useful when you want to pass something to a database and be valid to retrieve it via context.Param use it only for special cases, when the default behavior doesn't suits you.
DefaultConfiguration returns the default configuration for an Iris station, fills the main Configuration.
DefaultSessionsConfiguration the default configs for Sessions.
DefaultTesterConfiguration returns the default configuration for a tester.
DefaultWebsocketConfiguration returns the default config for iris-ws websocket package.
Delete registers a route for the Delete http method.
DisableKeepalive whether to disable keep-alive connections.
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.
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.
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.
Favicon serves static favicon accepts 2 parameters, second is optional favPath (string), declare the system directory path of the __.ico requestPath (string), it's the route's path, by default this is the "/favicon.ico" because some browsers tries to get this by default first, you can declare your own path if you have more than one favicon (desktop, mobile and so on) this func will add a route for you which will static serve the /yuorpath/yourfile.ico to the /yourfile.ico (nothing special that you can't handle by yourself) Note that you have to call it on every favicon you have to serve automatically (dekstop, mobile and so on) panics on error.
Get registers a route for the Get http method.
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.
HandleFunc registers and returns a route with a method string, path string and a handler registedPath is the relative url path.
Head registers a route for the Head http method.
IsRunning returns true if server is running.
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) }) } .
LETSENCRYPT returns a new Automatic TLS Listener using letsencrypt.org service.
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.
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' example: https://github.com/iris-contrib/examples/blob/master/letsencyrpt/main.go.
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").
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).
Lookup returns a registed route by its name.
Lookups returns all registed routes.
Must panics on error, it panics on registed iris' logger.
New creates and returns a new Iris instance.
NewLoggerHandler is a basic Logger middleware/Handler (not an Entry Parser).
NewSSHServer returns a new empty SSHServer.
NewTester Prepares and returns a new test framework based on the api is useful when you need to have more than one test framework for the same iris insttance, otherwise you can use the iris.Tester(t *testing.T)/variable.Tester(t *testing.T).
NewWebsocketServer returns an empty WebsocketServer, nothing special here.
OnError registers a custom http error handler.
Options registers a route for the Options http method.
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'.
ParseParams receives a string and returns PathParameters (slice of PathParameter) received string must have this form: key1=value1,key2=value2...
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://.
Party is just a group joiner of routes which have the same prefix and share same middleware(s) also.
Patch registers a route for the Patch http method.
Path used to check arguments with the route's named parameters and return the correct url if parse failed returns empty string.
Post
Post registers a route for the Post http method.
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.
Put registers a route for the Put http method.
ReleaseCtx puts the Iris' Context back to the pool in order to be re-used see .AcquireCtx & .Serve.
Reserve re-starts the server using the last .Serve's listener.
RouteConflicts checks for route's middleware conflicts.
SerializeToString returns the string of a serializer, does not render it to the client returns empty string on error.
Serve serves incoming connections from the given listener.
Set sets an option aka configuration field to the default iris instance.
Static registers a route which serves a system directory this doesn't generates an index page which list all files no compression is used also, for these features look at StaticFS func accepts three parameters first parameter is the request url path (string) second parameter is the system directory (string) third parameter is the level (int) of stripSlashes * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: "".
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.
StaticFS registers a route which serves a system directory this is the fastest method to serve static files generates an index page which list all files if you use this method it will generate compressed files also think this function as small fileserver with http accepts three parameters first parameter is the request url path (string) second parameter is the system directory (string) third parameter is the level (int) of stripSlashes * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: "".
StaticHandler returns a Handler to serve static system directory Accepts 5 parameters first is the systemPath (string) Path to the root directory to serve files from.
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).
StaticWeb same as Static but if index.html exists and request uri is '/' then display the index.html's contents accepts three parameters first parameter is the request url path (string) second parameter is the system directory (string) third parameter is the level (int) of stripSlashes * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: "" * if you don't know what to put on stripSlashes just 1.
StatusText returns a text for the HTTP status code.
TCP4 returns a new tcp4 Listener *tcp6 has some bugs in some operating systems, as reported by Go Community*.
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.
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.
Tester returns the test framework for this default insance.
TLS returns a new TLS Listener.
ToHandler converts an http.Handler or http.HandlerFunc to an iris.Handler.
ToHandlerFastHTTP converts an fasthttp.RequestHandler to an iris.Handler.
ToHandlerFunc converts an http.Handler or http.HandlerFunc to an iris.HandlerFunc.
Trace registers a route for the Trace http method.
UNIX returns a new unix(file) Listener.
URL returns the subdomain+ host + Path(...optional named parameters if route is dynamic) returns an empty string if parse is failed.
Use registers Handler middleware.
UseFunc registers HandlerFunc middleware.
UseGlobal registers Handler middleware to the beginning, prepends them instead of append Use it when you want to add a global middleware to all parties, to all routes in all subdomains It can be called after other, (but before .Listen of course).
UseGlobalFunc registers HandlerFunc middleware to the beginning, prepends them instead of append Use it when you want to add a global middleware to all parties, to all routes in all subdomains It can be called after other, (but before .Listen of course).
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.
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.
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.
UseTemplate adds a template engine to the iris view system it does not build/load them yet.

# Constants

All is the string which the Emmiter use to send a message to all.
Broadcast is the string which the Emmiter use to send a message to all except this websocket.Connection, same as 'NotMe'.
Default values for base Iris conf.
DefaultCookieLength is the default Session Manager's CookieLength, which is 32.
DefaultCookieName the secret cookie's name for sessions.
Default values for base Iris conf.
Default values for base Iris conf.
Default values for base Iris conf.
DefaultMaxMessageSize 1024.
DefaultMaxRequestBodySize is 8MB.
DefaultPingPeriod (DefaultPongTimeout * 9) / 10.
DefaultPongTimeout 60 * time.Second.
Per-connection buffer size for requests' reading.
DefaultServerHostname returns the default hostname which is 0.0.0.0.
DefaultServerPort returns the default port which is 8080, not used.
DefaultSessionGcDuration is the default Session Manager's GCDuration , which is 2 hours.
Per-connection buffer size for responses' writing.
DefaultWriteTimeout 15 * time.Second.
MethodConnect "CONNECT".
MethodDelete "DELETE".
MethodGet "GET".
MethodHead "HEAD".
MethodOptions "OPTIONS".
MethodPatch "PATCH".
MethodPost "POST".
MethodPut "PUT".
MethodTrace "TRACE".
NoLayout to disable layout for a particular template file.
NotMe is the string which the Emmiter use to send a message to all except this websocket.Connection.
SchemeHTTP returns "http://" (full).
SchemeHTTPS returns "https://" (full).
StatusAccepted http status '202'.
StatusBadGateway http status '502'.
StatusBadRequest http status '400'.
StatusConflict http status '409'.
StatusContinue http status '100'.
StatusCreated http status '201'.
StatusExpectationFailed http status '417'.
StatusForbidden http status '403'.
StatusFound http status '302'.
StatusGatewayTimeout http status '504'.
StatusGone http status '410'.
StatusHTTPVersionNotSupported http status '505'.
StatusInternalServerError http status '500'.
StatusLengthRequired http status '411'.
StatusMethodNotAllowed http status '405'.
StatusMovedPermanently http status '301'.
StatusMultipleChoices http status '300'.
StatusNetworkAuthenticationRequired http status '511'.
StatusNoContent http status '204'.
StatusNonAuthoritativeInfo http status '203'.
StatusNotAcceptable http status '406'.
StatusNotFound http status '404'.
StatusNotImplemented http status '501'.
StatusNotModified http status '304'.
StatusOK http status '200'.
StatusPartialContent http status '206'.
StatusPaymentRequired http status '402'.
StatusPreconditionFailed http status '412'.
StatusPreconditionRequired http status '428'.
StatusProxyAuthRequired http status '407'.
StatusRequestedRangeNotSatisfiable http status '416'.
StatusRequestEntityTooLarge http status '413'.
StatusRequestHeaderFieldsTooLarge http status '431'.
StatusRequestTimeout http status '408'.
StatusRequestURITooLong http status '414'.
StatusResetContent http status '205'.
StatusSeeOther http status '303'.
StatusServiceUnavailable http status '503'.
StatusSwitchingProtocols http status '101'.
StatusTeapot http status '418'.
StatusTemporaryRedirect http status '307'.
StatusTooManyRequests http status '429'.
StatusUnauthorized http status '401'.
StatusUnavailableForLegalReasons http status '451'.
StatusUnsupportedMediaType http status '415'.
StatusUseProxy http status '305'.
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.
Version is the current version of the Iris web framework.

# Variables

AllMethods "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", "PATCH", "OPTIONS", "TRACE".
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.
CompressedFileSuffix is the suffix to add to the name of cached compressed file when using the .StaticFS function.
Default iris instance entry and its public fields, use it with iris.$anyPublicFuncOrField.
CookieExpireNever the default cookie's life for sessions, unlimited (23 years).
Default iris instance entry and its public fields, use it with iris.$anyPublicFuncOrField.
DefaultLoggerOut is the default logger's output.
DefaultServerAddr the default server addr which is: 0.0.0.0:8080.
DefaultServerName the response header of the 'Server' value when writes to the client.
DefaultSSHKeyPath used if SSH.KeyPath is empty.
DefaultTimeFormat default time format for any kind of datetime parsing.
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.
DefaultWebsocketError is the default method to manage the handshake websocket errors.
if you want colors in your console then you should use this https://github.com/iris-contrib/logger instead.
MethodConnectBytes "CONNECT".
MethodDeleteBytes "DELETE".
MethodGetBytes "GET".
MethodHeadBytes "HEAD".
MethodOptionsBytes "OPTIONS".
MethodPatchBytes "PATCH".
MethodPostBytes "POST".
MethodPutBytes "PUT".
MethodTraceBytes "TRACE".
OptionCharset character encoding for various rendering used for templates and the rest of the responses Default is "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.
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.
OptionDisableBanner outputs the iris banner at startup Default is false.
OptionDisablePathCorrection corrects and redirects the requested path to the registed path for example, if /home/ path is requested but no handler for this Route found, then the Router checks if /home handler exists, if yes, (permant)redirects the client to the correct path /home Default is false.
OptionDisablePathEscape when is false then its escapes the path, the named parameters (if any).
OptionDisableTemplateEngines set to true to disable loading the default template engine (html/template) and disallow the use of iris.UseEngine Default is 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 globaly, you could just use the third parameter on context.Render("myfileOrResponse", structBinding{}, iris.RenderOptions{"gzip": true}) Default is false.
OptionIsDevelopment iris will act like a developer, for example If true then re-builds the templates on each request Default is false.
OptionLoggerOut is the destination for output Default is os.Stdout.
OptionLoggerPreffix is the logger's prefix to write at beginning of each line Default is [IRIS].
OptionMaxConnsPerIP Maximum number of concurrent client connections allowed per IP.
OptionMaxRequestBodySize Maximum request body size.
OptionMaxRequestsPerConn Maximum number of requests served per connection.
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.
Per-connection buffer size for requests' reading.`` This also limits the maximum header size.
Maximum duration for reading the full request (including body).
OptionSessionsCookie string, the session's client cookie name, for example: "qsessionid".
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.
OptionSessionsDecodeCookie set it to true to decode the cookie key with base64 URLEncoding Defaults to false.
OptionSessionsDisableSubdomainPersistence set it to true in order dissallow your q subdomains to have access to the session cookie defaults to false.
OptionSessionsExpires the duration of which the cookie must expires (created_time.Add(Expires)).
OptionSessionsGcDuration every how much duration(GcDuration) the memory should be clear for unused cookies (GcDuration) for example: time.Duration(2)*time.Hour.
OptionTesterDebug if true then debug messages from the httpexpect will be shown when a test runs Default is false.
OptionTesterExplicitURL If true then the url (should) be prepended manually, useful when want to test subdomains Default is false.
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.
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.
OptionWebsocketCheckOrigin returns true if the request Origin header is acceptable.
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.
OptionWebsocketError specifies the function for generating HTTP error responses.
OptionWebsocketHeaders if true then the client's headers are copy to the websocket connection.
OptionWebsocketMaxMessageSize max message size allowed from connection Default value is 1024.
OptionWebsocketPingPeriod send ping messages to the connection with this period.
OptionWebsocketPongTimeout allowed to read the next pong message from the connection Default value is 60 * time.Second.
OptionWebsocketReadBufferSize is the buffer size for the underline reader.
OptionWebsocketWriteBufferSize is the buffer size for the underline writer.
OptionWebsocketWriteTimeout time allowed to write a message to the connection.
Per-connection buffer size for responses' writing.
Maximum duration for writing the full response (including body).
Default iris instance entry and its public fields, use it with iris.$anyPublicFuncOrField.
Default iris instance entry and its public fields, use it with iris.$anyPublicFuncOrField.
Look ssh.go for this field's configuration example: https://github.com/iris-contrib/examples/blob/master/ssh/main.go.
SSHBanner is the banner goes on top of the 'ssh help message' it can be changed, defaults is the Iris's banner.
StaticCacheDuration expiration duration for INACTIVE file handlers, it's a global configuration field to all iris instances.
Default iris instance entry and its public fields, use it with iris.$anyPublicFuncOrField.
WebsocketCheckSameOrigin returns true if the origin is not set or is equal to the request host.

# Structs

Command contains the registered SSH commands contains a Name which is the payload string Description which is the description of the command shows to the admin/user Action is the particular command's handler.
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.
No description provided by the author
No description provided by the author
No description provided by the author
SSHServer : Simple SSH interface for Iris web framework, does not implements the most secure options and code, but its should works use it at your own risk.
TCPKeepAliveListener sets TCP keep-alive timeouts on accepted connections.
TesterConfiguration configuration used inside main config field 'Tester'.
WebsocketConfiguration the config contains options for the Websocket main config field.
No description provided by the author

# 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
------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- ----------------------------------MuxAPI implementation------------------------------ ------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
WebsocketConnection is the front-end API that you will use to communicate with the client side.

# Type aliases

Action the command's handler.
Commands the SSH Commands, it's just a type of []Command.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- ----------------------------------MuxAPI implementation------------------------------ ------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------.
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.
Users SSH.Users field, it's just map[string][]byte (username:password).