Socket
Socket
Sign inDemoInstall

github.com/codehakase/iris

Package Overview
Dependencies
0
Alerts
File Explorer

Install Socket

Detect and block malicious and high-risk dependencies

Install

    github.com/codehakase/iris

Package iris provides a beautifully expressive and easy to use foundation for your next website, API, or distributed app. Source code and other details for the project are available at GitHub: 8.4.4 The only requirement is the Go Programming Language, at least version 1.8 but 1.9 is highly recommended. Example code: You can start the server(s) listening to any type of `net.Listener` or even `http.Server` instance. The method for initialization of the server should be passed at the end, via `Run` function. Below you'll see some useful examples: UNIX and BSD hosts can take advandage of the reuse port feature. Example code: That's all with listening, you have the full control when you need it. Let's continue by learning how to catch CONTROL+C/COMMAND+C or unix kill command and shutdown the server gracefully. In order to manually manage what to do when app is interrupted, we have to disable the default behavior with the option `WithoutInterruptHandler` and register a new interrupt handler (globally, across all possible hosts). Example code: Access to all hosts that serve your application can be provided by the `Application#Hosts` field, after the `Run` method. But the most common scenario is that you may need access to the host before the `Run` method, there are two ways of gain access to the host supervisor, read below. First way is to use the `app.NewHost` to create a new host and use one of its `Serve` or `Listen` functions to start the application via the `iris#Raw` Runner. Note that this way needs an extra import of the `net/http` package. Example Code: Second, and probably easier way is to use the `host.Configurator`. Note that this method requires an extra import statement of "github.com/kataras/iris/core/host" when using go < 1.9, if you're targeting on go1.9 then you can use the `iris#Supervisor` and omit the extra host import. All common `Runners` we saw earlier (`iris#Addr, iris#Listener, iris#Server, iris#TLS, iris#AutoTLS`) accept a variadic argument of `host.Configurator`, there are just `func(*host.Supervisor)`. Therefore the `Application` gives you the rights to modify the auto-created host supervisor through these. Example Code: Read more about listening and gracefully shutdown by navigating to: All HTTP methods are supported, developers can also register handlers for same paths for different methods. The first parameter is the HTTP Method, second parameter is the request path of the route, third variadic parameter should contains one or more iris.Handler executed by the registered order when a user requests for that specific resouce path from the server. Example code: In order to make things easier for the user, iris provides functions for all HTTP Methods. The first parameter is the request path of the route, second variadic parameter should contains one or more iris.Handler executed by the registered order when a user requests for that specific resouce path from the server. Example code: A set of routes that are being groupped by path prefix can (optionally) share the same middleware handlers and template layout. A group can have a nested group too. `.Party` is being used to group routes, developers can declare an unlimited number of (nested) groups. Example code: iris developers are able to register their own handlers for http statuses like 404 not found, 500 internal server error and so on. Example code: With the help of iris's expressionist router you can build any form of API you desire, with safety. Example code: Iris has first-class support for the MVC pattern, you'll not find these stuff anywhere else in the Go world. Example Code: Iris web framework supports Request data, Models, Persistence Data and Binding with the fastest possible execution. Characteristics: All HTTP Methods are supported, for example if want to serve `GET` then the controller should have a function named `Get()`, you can define more than one method function to serve in the same Controller struct. Persistence data inside your Controller struct (share data between requests) via `iris:"persistence"` tag right to the field or Bind using `app.Controller("/" , new(myController), theBindValue)`. Models inside your Controller struct (set-ed at the Method function and rendered by the View) via `iris:"model"` tag right to the field, i.e User UserModel `iris:"model" name:"user"` view will recognise it as `{{.user}}`. If `name` tag is missing then it takes the field's name, in this case the `"User"`. Access to the request path and its parameters via the `Path and Params` fields. Access to the template file that should be rendered via the `Tmpl` field. Access to the template data that should be rendered inside the template file via `Data` field. Access to the template layout via the `Layout` field. Access to the low-level `iris.Context` via the `Ctx` field. Get the relative request path by using the controller's name via `RelPath()`. Get the relative template path directory by using the controller's name via `RelTmpl()`. Flow as you used to, `Controllers` can be registered to any `Party`, including Subdomains, the Party's begin and done handlers work as expected. Optional `BeginRequest(ctx)` function to perform any initialization before the method execution, useful to call middlewares or when many methods use the same collection of data. Optional `EndRequest(ctx)` function to perform any finalization after any method executed. Inheritance, recursively, see for example our `mvc.SessionController/iris.SessionController`, it has the `mvc.Controller/iris.Controller` as an embedded field and it adds its logic to its `BeginRequest`. Source file: https://github.com/kataras/iris/blob/master/mvc/session_controller.go. Read access to the current route via the `Route` field. Support for more than one input arguments (map to dynamic request path parameters). Register one or more relative paths and able to get path parameters, i.e By creating components that are independent of one another, developers are able to reuse components quickly and easily in other applications. The same (or similar) view for one application can be refactored for another application with different data because the view is simply handling how the data is being displayed to the user. If you're new to back-end web development read about the MVC architectural pattern first, a good start is that wikipedia article: https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller. Follow the examples below, - Hello world: https://github.com/kataras/iris/blob/master/_examples/mvc/hello-world/main.go - Session Controller usage: https://github.com/kataras/iris/blob/master/_examples/mvc/session-controller/main.go - A simple but featured Controller with model and views: https://github.com/kataras/iris/tree/master/_examples/mvc/controller-with-model-and-view At the previous example, we've seen static routes, group of routes, subdomains, wildcard subdomains, a small example of parameterized path with a single known parameter and custom http errors, now it's time to see wildcard parameters and macros. iris, like net/http std package registers route's handlers by a Handler, the iris' type of handler is just a func(ctx iris.Context) where context comes from github.com/kataras/iris/context. Iris has the easiest and the most powerful routing process you have ever meet. At the same time, iris has its own interpeter(yes like a programming language) for route's path syntax and their dynamic path parameters parsing and evaluation, We call them "macros" for shortcut. How? It calculates its needs and if not any special regexp needed then it just registers the route with the low-level path syntax, otherwise it pre-compiles the regexp and adds the necessary middleware(s). Standard macro types for parameters: if type is missing then parameter's type is defaulted to string, so {param} == {param:string}. If a function not found on that type then the "string"'s types functions are being used. i.e: Besides the fact that iris provides the basic types and some default "macro funcs" you are able to register your own too!. Register a named path parameter function: at the func(argument ...) you can have any standard type, it will be validated before the server starts so don't care about performance here, the only thing it runs at serve time is the returning func(paramValue string) bool. Example Code: A path parameter name should contain only alphabetical letters, symbols, containing '_' and numbers are NOT allowed. If route failed to be registered, the app will panic without any warnings if you didn't catch the second return value(error) on .Handle/.Get.... Last, do not confuse ctx.Values() with ctx.Params(). Path parameter's values goes to ctx.Params() and context's local storage that can be used to communicate between handlers and middleware(s) goes to ctx.Values(), path parameters and the rest of any custom values are separated for your own good. Run Static Files Example code: More examples can be found here: https://github.com/kataras/iris/tree/master/_examples/beginner/file-server Middleware is just a concept of ordered chain of handlers. Middleware can be registered globally, per-party, per-subdomain and per-route. Example code: iris is able to wrap and convert any external, third-party Handler you used to use to your web application. Let's convert the https://github.com/rs/cors net/http external middleware which returns a `next form` handler. Example code: Iris supports 5 template engines out-of-the-box, developers can still use any external golang template engine, as `context/context#ResponseWriter()` is an `io.Writer`. All of these five template engines have common features with common API, like Layout, Template Funcs, Party-specific layout, partial rendering and more. Example code: View engine supports bundled(https://github.com/jteeuwen/go-bindata) template files too. go-bindata gives you two functions, asset and assetNames, these can be setted to each of the template engines using the `.Binary` func. Example code: A real example can be found here: https://github.com/kataras/iris/tree/master/_examples/view/embedding-templates-into-app. Enable auto-reloading of templates on each request. Useful while developers are in dev mode as they no neeed to restart their app on every template edit. Example code: Note: In case you're wondering, the code behind the view engines derives from the "github.com/kataras/iris/view" package, access to the engines' variables can be granded by "github.com/kataras/iris" package too. Each one of these template engines has different options located here: https://github.com/kataras/iris/tree/master/view . This example will show how to store and access data from a session. You don’t need any third-party library, but If you want you can use any session manager compatible or not. In this example we will only allow authenticated users to view our secret message on the /secret page. To get access to it, the will first have to visit /login to get a valid session cookie, which logs him in. Additionally he can visit /logout to revoke his access to our secret message. Example code: Running the example: Sessions persistence can be achieved using one (or more) `sessiondb`. Example Code: More examples: In this example we will create a small chat between web sockets via browser. Example Server Code: Example Client(javascript) Code: Running the example: But you should have a basic idea of the framework by now, we just scratched the surface. If you enjoy what you just saw and want to learn more, please follow the below links: Examples: Middleware: Home Page: Book (in-progress):


Version published

Readme

Source

Iris is a fast, simple and efficient micro web framework for Go. It provides a beautifully expressive and easy to use foundation for your next website, API, or distributed app.

We have no doubt you will able to find other web frameworks written in Go and even put up a real fight to learn and use them for quite some time but make no mistake, sooner or later you will be using Iris, not because of the ergonomic, high-performant solution that it provides but its well-documented unique features, as these will transform you to a real rockstar geek.

No matter what you're trying to build, Iris covers every type of application, from micro services to large monolithic web applications. It's actually the best piece of software for back-end web developers you can find online.

Iris may have reached version 8, but we're not stopping there. We have many feature ideas on our board that we're anxious to add and other innovative web development solutions that we're planning to build into Iris.

Iris was built on top of the the net/http package, we own many thanks to Brad Fitzpatrick for that.

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

Accelerated by KeyCDN, A Simple, Fast and Reliable CDN.

We are developing this project using the best code editor for Golang; Visual Studio Code supported by Microsoft.

Star and watch this github repository to stay up to date.

build status report card github issues github closed issues release view examples chat

Iris vs .NET Core(C#) vs Node.js (Express)

Benchmarks from third-party source over the rest web frameworks

Comparison with other frameworks

Updated at: Friday, 29 September 2017

🎗️ Legends

Help this project to continue deliver awesome and unique features with the higher code quality as possible by donating any amount via PayPal!

NameAmountMembership
Juan Sebastián Suárez Valencia20 EURBronze
Bob Lee20 EURBronze
Celso Luiz50 EURSilver
Ankur Srivastava20 EURBronze
Damon Zhao20 EURBronze
Exponity - Tech Company30 EURBronze
Thomas Fritz25 EURBronze
Thanos V.20 EURBronze
George Opritescu20 EURBronze
Lex Tang20 EURBronze
Bill Q.600 EURGold
Conrad Steenberg25 EURBronze

📑 Table of contents

🚀 Installation

The only requirement is the Go Programming Language, at least version 1.8 but 1.9 is highly recommended.

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

iris takes advantage of the vendor directory feature. You get truly reproducible builds, as this method guards against upstream renames and deletes.

// file: main.go
package main
import "github.com/kataras/iris"

func main() {
    app := iris.New()
    // Load all templates from the "./views" folder
    // where extension is ".html" and parse them
    // using the standard `html/template` package.
    app.RegisterView(iris.HTML("./views", ".html"))

    // Method:    GET
    // Resource:  http://localhost:8080
    app.Get("/", func(ctx iris.Context) {
        // Bind: {{.message}} with "Hello world!"
        ctx.ViewData("message", "Hello world!")
        // Render template file: ./views/hello.html
        ctx.View("hello.html")
    })

    // Method:    GET
    // Resource:  http://localhost:8080/user/42
    app.Get("/user/{id:long}", func(ctx iris.Context) {
        userID, _ := ctx.Params().GetInt64("id")
        ctx.Writef("User ID: %d", userID)
    })

    // Start the server using a network address.
    app.Run(iris.Addr(":8080"))
}
<!-- file: ./views/hello.html -->
<html>
<head>
    <title>Hello Page</title>
</head>
<body>
    <h1>{{.message}}</h1>
</body>
</html>
$ go run main.go
> Now listening on: http://localhost:8080
> Application started. Press CTRL+C to shut down.

Examples and docs are updated to Go 1.9, please refer to that section before anything else.

Hello World with Go 1.8

Iris declares all of its type alias at the same file in order to be easy to be discovered.

If you just upgraded to go 1.9 from 1.8 you can always search for a compatible type alias at the context.go file and opposite, if you use go 1.8 and you're new to Iris you can see that file to see the compatible packages.

If Go 1.8 remains the basic host for your go apps then you should declare and use the github.com/kataras/iris/context package on your source file's imports statement.

package main

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

func main() {
	app := iris.New()
	app.RegisterView(iris.HTML("./templates", ".html"))

	app.Get("/", func(ctx context.Context) {
		ctx.ViewData("message", "Hello world!")
		ctx.View("hello.html")
	})

	app.Run(iris.Addr(":8080"))
}
Fan of the MVC Architectural Pattern? Click here
package main

import "github.com/kataras/iris"

func main() {
    app := iris.New()
    app.RegisterView(iris.HTML("./views", ".html"))

    app.Controller("/", new(Controller))

    app.Run(iris.Addr(":8080"))
}

type Controller struct {
    iris.Controller
}

// Method:    GET
// Resource:  http://localhost:8080
func (c *Controller) Get() {
    c.Data["message"] = "Hello world!"
    c.Tmpl = "hello.html"
}

// Method:    GET
// Resource:  http://localhost:8080/user/42
func (c *Controller) GetUserBy(id int64) {
    c.Ctx.Writef("User ID: %d", id)
}
Why a new web framework

Why

Go is a great technology stack for building scalable, web-based, back-end systems for web applications.

When you think about building web applications and web APIs, or simply building HTTP servers in Go, does your mind go to the standard net/http package? Then you have to deal with some common situations like dynamic routing (a.k.a parameterized), security and authentication, real-time communication and many other issues that net/http doesn't solve.

The net/http package is not complete enough to quickly build well-designed back-end web systems. When you realize this, you might be thinking along these lines:

  • Ok, the net/http package doesn't suit me, but there are so many frameworks, which one will work for me?!
  • Each one of them tells me that it is the best. I don't know what to do!
The truth

I did some deep research and benchmarks with 'wrk' and 'ab' in order to choose which framework would suit me and my new project. The results, sadly, were really disappointing to me.

I started wondering if golang wasn't as fast on the web as I had read... but, before I let Golang go and continued to develop with nodejs, I told myself:

'Makis, don't lose hope, give at least a chance to Golang. Try to build something totally new without basing it off the "slow" code you saw earlier; learn the secrets of this language and make others follow your steps!'.

These are the words I told myself that day [13 March 2016].

The same day, later the night, I was reading a book about Greek mythology. I saw an ancient goddess' name and was inspired immediately to give a name to this new web framework (which I had already started writing) - Iris.

I'm still here because Iris has succeed in being the fastest go web framework


iris is easy, it has a familiar API while in the same has far more features than Gin or Martini.

You own your code —it will never generate (unfamiliar) code for you, like Beego, Revel and Buffalo do.

It's not just-another-router but its overall performance is equivalent with something like httprouter.

Unlike fasthttp, iris provides full HTTP/2 support for free.

Compared to the rest open source projects, this one is very active and you get answers almost immediately.

🔥 Hot Features

  • Focus on high performance
  • Easy Fluent API
  • Highly customizable
  • Robust routing and middleware ecosystem
    • Build RESTful APIs with iris unique expressionist path interpreter
    • Dynamic path parameterized or wildcard routes are not conflict with static routes
    • Remove trailing slash from the URL with option to redirect
    • Virtual hosts and subdomains made easy
    • Group API's and static or even dynamic subdomains
    • MVC NEW
    • net/http and negroni-like handlers are compatible via iris.FromStd
    • Register custom handlers for any HTTP error
    • Transactions and rollback when you need it
    • Cache the response when you need it
    • A single function to serve your embedded assets, always compatible with go-bindata
    • HTTP to HTTPS
    • HTTP to HTTPS WWW
    • learn the reasons that differ from what you've seen so far
  • Context
    • Highly scalable rich content render (Markdown, JSON, JSONP, XML...)
    • Body binders and handy functions to send HTTP responses
    • Limit request body
    • Serve static resources or embedded assets
    • Localization i18N
    • Compression (Gzip is built'n)
  • Authentication
    • Basic Authentication
    • OAuth, OAuth2 supporting 27+ popular websites
    • JWT
  • Server
    • Automatically install and serve certificates from https://letsencrypt.org when serving via TLS
    • Gracefully shutdown by-default
    • Register on shutdown, error or interrupt events
    • Attach more than one server, fully compatible with net/http#Server
  • View system: supporting 5 template engines. Fully compatible with html/template
  • HTTP Sessions library [you can still use your favorite if you want to]
  • Websocket library, its API similar to socket.io [you can still use your favorite if you want to]
  • Hot Reload on source code changes*
  • Typescript integration + Web IDE
  • And many other things that will surprise you

📖 Learn

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 apache+nginx itself.

iris does not force you to use any specific ORM. With support for the most popular template engines, websocket server and a fast sessions manager you can quickly craft your perfect application.

The awesome iris community is always adding new examples, _examples is a great place to get started!

Read the godocs for a better understanding.

👥 Community

Join the welcoming community of fellow iris developers in rocket.chat

  • Post a feature request or report a bug
  • :star: and watch the public repository, will keep you up to date
  • :earth_americas: publish an article or share a tweet about your personal experience with iris.

The most useful community repository for iris developers is the iris-contrib/middleware which contains some HTTP handlers that can help you finish a lot of your tasks even easier. Feel free to push your own middleware there!

$ go get -u github.com/iris-contrib/middleware/...
📈 One and a half years...

total used by

Iris exceeded all expectations, started as one-man project.

  • 7300 github stars
  • 778 github forks
  • 1m total views at its documentation
  • ~819$ at donations, small amount for the work we put here but it's a good start
  • ~557 reported bugs fixed
  • ~30 community feature requests have been implemented

📌 Version

Current: VERSION

Each new release is pushed to the master. It stays there until the next version. When a next version is released then the previous version goes to its own branch with gopkg.in as its import path (and its own vendor folder), in order to keep it working "for-ever".

Changelog of the current version can be found at the HISTORY file.

Should I upgrade my iris?

Developers are not forced to use the latest iris version, they can use any version in production, they can update at any time they want.

Testers should upgrade immediately, if you're willing to use iris in production you can wait a little more longer, transaction should be as safe as possible.

Where can I find older versions?

Previous versions can be found at releases page.

🥇 People

The original author of Iris is @kataras, you can reach him via

List of all Authors

List of all Contributors

Help this project to continue deliver awesome and unique features with the higher code quality as possible by donating any amount via PayPal!

License

This software is licensed under the open-source 3-Clause BSD.

You can find the license file here, for any questions regarding the license please contact us.

FAQs

Last updated on 01 Oct 2017

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc