Skip to content

Latest commit

 

History

History
908 lines (653 loc) · 36.5 KB

README.md

File metadata and controls

908 lines (653 loc) · 36.5 KB


Build Status

http://goreportcard.com/report/kataras/iris

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.

Besides the fact that Iris is faster than any alternatives you may met before,
thanks to its fluent API, you don't have to be an expert to work with it.

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

Feature Overview

  • Focus on high performance
  • Highly customizable
  • HTTP/2 full support
  • Hot Reload on source code changes
  • Compatible with all net/http handlers
  • Automatically install and serve certificates from https://letsencrypt.org
  • Robust routing and middleware ecosystem
  • Build RESTful APIs
  • Context 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, directories and streams
  • Fast Cache System
  • Customizable format and output for the logger
  • Customizable HTTP errors
  • Compression (Gzip)
  • Authentication
  • OAuth, OAuth2 supporting 27+ popular websites
  • JWT
  • Basic Authentication
  • HTTP Sessions and flash messages
  • Add / Remove trailing slash from the URL with option to redirect
  • Redirect any request
  • Highly scalable rich content render (Markdown, JSON, JSONP, XML...)
  • Websocket API similar to socket.io
  • Typescript integration + Web IDE
  • Optional updater
  • Feels like you used iris forever, thanks to its Fluent API
  • And more...

Quick Start

go get -u github.com/kataras/iris
cat hellojson.go
package main

import "github.com/kataras/iris"

func main(){

  // http://localhost:5700/api/user/42
  // Method: "GET"
  iris.Get("/api/user/:id", 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)

  })

  iris.Listen("localhost:5900")
}
$ go run hellojson.go

Open your browser or any other http client at http://localhost:5700/api/user/42.

New

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

app.Listen(....)

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

app.Listen(...)

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

// Default station with custom configuration
// view the whole configuration at: ./configuration.go
iris.Config.IsDevelopment = true
iris.Config.Charset = "UTF-8"

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, cacheFileOptional ...string)

iris.ListenLETSENCRYPT("mydomain.com")
iris.Serve(iris.LETSENCRYPTPROD("myproductionwebsite.com"))

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

name value
name Gerasimos Maropoulos
email kataras2006@homail.com
func save(ctx *iris.Context) {
	// Get name and email
	name := ctx.FormValue("name")
	email := ctx.FormValue("email")
}

Form multipart/form-data

POST /save

name value
name Gerasimos Maropoulos
email kataras2006@hotmail.com
avatar avatar
func save(ctx *iris.Context)  {
	// Get name and email
	name := ctx.FormValue("name")
	email := ctx.FormValue("email")
	// Get avatar
	avatar, info, err := ctx.FormFile("avatar")
	if err != nil {
       ctx.EmitError(iris.StatusInternalServerError)
       return
	}

	defer avatar.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, avatar); 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)
})
Name Description Usage
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
Text Text 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.Writef("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.Writef("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 StaticWeb(reqPath string, systemPath string).

// 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
Favicon(favPath string, requestPath ...string) RouteNameFunc

// StaticHandler returns a new Handler which serves static files
StaticHandler(reqPath string, systemPath string, showList bool, enableGzip bool) HandlerFunc

// 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)
StaticWeb(reqPath string, systemPath string) RouteNameFunc

// StaticEmbedded  used when files are distrubuted inside the app executable, using go-bindata mostly
// First parameter is the request path, the path which the files in the vdir will be served to, for example "/static"
// Second parameter is the (virtual) directory path, for example "./assets"
// Third parameter is the Asset function
// Forth parameter is the AssetNames function
//
// For more take a look at the
// example: https://github.com/iris-contrib/examples/tree/master/static_files_embedded
StaticEmbedded(requestPath string, vdir string, assetFn func(name string) ([]byte, error), namesFn func() []string) 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
StaticContent(reqPath string, cType string, content []byte) 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 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.StaticWeb("/public", "./static/assets/")
//-> /public/assets/favicon.ico
iris.StaticWeb("/","./my_static_html_website")
context.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
context.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"})
}
Name Description Usage
HTML/Default Engine HTML Template Engine (Default) example , book section
Django Engine Django Template Engine example , book section
Pug/Jade Engine Pug Template Engine example , book section
Handlebars Engine Handlebars Template Engine example , book section
Amber Engine Amber Template Engine example , book section
Markdown Engine Markdown Template Engine example , 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")
})
Name Description Usage
Basicauth Middleware HTTP Basic authentication example 1, example 2, book section
JWT Middleware JSON Web Tokens example , book section
Cors Middleware Cross Origin Resource Sharing W3 specification how to use
Secure Middleware Facilitates some quick security wins example
I18n Middleware Simple internationalization example, book section
Recovery Middleware Safety recover the station from panic example
Logger Middleware Logs every request example, book section
LoggerZap Middleware Logs every request using zap example, book section
Profile Middleware Http profiling for debugging example
Editor Plugin Alm-tools, a typescript online IDE/Editor book section
Typescript Plugin Auto-compile client-side typescript files book section
OAuth,OAuth2 Plugin User Authentication was never be easier, supports >27 providers example, book section
Iris control Plugin Basic (browser-based) control over your Iris station example, book section

NOTE: All net/http handlers and middleware that already created by other go developers are also compatible with Iris, even if they are not be documented here, read more here.

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.Writef("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.Writef("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.Writef("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.Writef("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")
  • iris.DestroySessionByID(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.
DestroySessionByID(string)
  • iris.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.
DestroyAllSessions()

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.Host()})
    })

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

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. You can find Iris examples here, here and here.

Versioning

Current: v6.0.5

Stable: v5/fasthttp

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

People

The author of Iris is @kataras.

If you're willing to donate and you can afford the cost, feel free to navigate to the DONATIONS PAGE.

Contributing

Iris is the work of hundreds of the community's feature requests and reports. I appreciate your help!

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

Depends on:

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:

License

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