iris

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

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

Go to latest
Published: Apr 2, 2016 License: BSD-3-Clause Imports: 26 Imported by: 0

README

Iris Web Framework

[![Build Status](https://travis-ci.org/kataras/iris.svg?branch=development&style=flat-square)](https://travis-ci.org/kataras/iris) [![Go Report Card](https://goreportcard.com/badge/github.com/kataras/iris?style=flat-square)](https://goreportcard.com/report/github.com/kataras/iris) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/kataras/iris?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![GoDoc](https://godoc.org/github.com/kataras/iris?status.svg)](https://godoc.org/github.com/kataras/iris) [![License](https://img.shields.io/badge/license-BSD3-blue.svg?style=flat-square)](LICENSE)

The fastest go web framework which provides robust set of features for building modern & shiny web applications.

Hi Iris GIF

Features

  • Context: Iris uses Context for storing route params, sharing variables between middlewares and render rich content to the client.
  • Plugins: You can build your own plugins to inject the Iris framework*.
  • Full API: All http methods are supported, you can group routes and sharing resources together*.
  • Zero allocations: Iris generates zero garbage*.
  • Multi server instances: Besides the fact that Iris has a default main server. You can declare as many as you need*.
  • Compatible: Iris is compatible with the native net/http package.
Q: What makes iris significantly faster?
A: These are the QNIQUE features that Iris brings
  • Iris uses the same algorithm as the BSD's kernel does for routing (call it Trie)

  • Iris has 5 different types of Routers, which are optimized and auto-selected before the server listen

  • The more you use it, more faster it becomes. Because Iris (can) use cache for routing, it's optional. If you disable it it stills the fastest but only with a small difference from other routers/frameworks

  • Iris can detect how much cores the machine using at runtime and optimize itself

  • Middlewares and Plugins are 'light' and that is, a principle.

Table of Contents

Install

Iris is still in development status, in order to have the latest version update the package one per week

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

Introduction

The name of this framework came from Greek mythology, Iris was the name of the Greek goddess of the rainbow. Iris is a very minimal but flexible golang http middleware & standalone web application framework, providing a robust set of features for building single & multi-page, web applications.

package main

import "github.com/kataras/iris"

func main() {
	iris.Get("/hello", func(c *iris.Context) {
		c.HTML("<b> Hello </b>")
	})
	iris.Listen(":8080")
}

Note: for macOS, If you are having problems on .Listen then pass only the port "8080" without ':'

Listening
//1  defaults to tcp 8080
iris.Listen()
//2
log.Fatal(iris.Listen(":8080"))
//3
http.ListenAndServe(":8080",iris.Serve())
//4
log.Fatal(http.ListenAndServe(":8080",iris.Serve()))

TLS

TLS for https:// and http2:

ListenTLS(fulladdr string, certFile, keyFile string) error
//1
iris.ListenTLS(":8080", "myCERTfile.cert", "myKEYfile.key")
//2
log.Fatal(iris.ListenTLS(":8080", "myCERTfile.cert", "myKEYfile.key"))

Handlers

Handlers should implement the Handler interface:

type Handler interface {
	Serve(*Context)
}
Using Handlers

type myHandlerGet struct {
}

func (m myHandlerGet) Serve(c *iris.Context) {
    c.Write("From %s",c.Request.URL.Path)
}

//and so on


iris.Handle("GET", "/get", myHandlerGet)
iris.Handle("POST", "/post", post)
iris.Handle("PUT", "/put", put)
iris.Handle("DELETE", "/delete", del)
Using HandlerFuncs

HandlerFuncs should implement the Serve(*Context) func. HandlerFunc is most simple method to register a route or a middleware, but under the hoods it's acts like a Handler. It's implements the Handler interface as well:

type HandlerFunc func(*Context)

func (h HandlerFunc) Serve(c *Context) {
	h(c)
}

HandlerFuncs shoud have this function signature:

func handlerFunc(c *iris.Context)  {
	c.Write("Hello")
}


iris.HandleFunc("GET","/letsgetit",handlerFunc)
//OR
iris.Get("/get", handlerFunc)
iris.Post("/post", handlerFunc)
iris.Put("/put", handlerFunc)
iris.Delete("/delete", handlerFunc)
Using Annotated

Implements the Handler interface

///file: userhandler.go
import "github.com/kataras/iris"

type UserHandler struct {
	iris.Handler `get:"/profile/user/:userId"`
}

func (u *UserHandler) Serve(c *iris.Context) {
	defer c.Close()
	userId := c.Param("userId")
	c.RenderFile("user.html", struct{ Message string }{Message: "Hello User with ID: " + userId})
}

///file: main.go
//...cache the html files
iris.Templates("src/iristests/templates/**/*.html")
//...register the handler
iris.HandleAnnotated(&UserHandler{})
//...continue writing your wonderful API

Using native http.Handler

Note that using native http handler you cannot access url params.


type nativehandler struct {}

func (_ nativehandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {

}

func main() {
	iris.Handle("", "/path", iris.ToHandler(nativehandler{}))
	//"" means ANY(GET,POST,PUT,DELETE and so on)
}


Using native http.Handler via iris.ToHandlerFunc()
iris.Get("/letsget", iris.ToHandlerFunc(nativehandler{}))
iris.Post("/letspost", iris.ToHandlerFunc(nativehandler{}))
iris.Put("/letsput", iris.ToHandlerFunc(nativehandler{}))
iris.Delete("/letsdelete", iris.ToHandlerFunc(nativehandler{}))

Middlewares

Middlewares in Iris are not complicated, imagine them as simple Handlers. They should implement the Handler interface as well:

type Handler interface {
	Serve(*Context)
}
type Middleware []Handler

Handler middleware example:


type myMiddleware struct {}

func (m *myMiddleware) Serve(c *iris.Context){
	shouldContinueToTheNextHandler := true

	if shouldContinueToTheNextHandler {
		c.Next()
	}else{
	    c.SendStatus(403,"Forbidden !!")
	}

}

iris.Use(&myMiddleware{})

iris.Get("/home", func (c *iris.Context){
	c.HTML("<h1>Hello from /home </h1>")
})

iris.Listen()

HandlerFunc middleware example:


func myMiddleware(c *iris.Context){
	c.Next()
}

iris.UseFunc(myMiddleware)

HandlerFunc middleware for a specific route:


func mySecondMiddleware(c *iris.Context){
	c.Next()
}

iris.Get("/dashboard", func(c *iris.Context) {
    loggedIn := true
    if loggedIn {
        c.Next()
    }
}, mySecondMiddleware, func (c *iris.Context){
    c.Write("The last HandlerFunc is the main handler, all before that are the middlewares for this route /dashboard")
})

iris.Listen(":8080")

Uses one of build'n Iris middlewares, view practical examples here

package main

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

type Page struct {
	Title string
}

iris.Templates("./yourpath/templates/*")

iris.Use(gzip.Gzip(gzip.DefaultCompression))

iris.Get("/", func(c *iris.Context) {
		c.RenderFile("index.html", Page{"My Index Title"})
})

iris.Listen(":8080") // .Listen() listens to TCP port 8080 by default

API

Use of GET, POST, PUT, DELETE, HEAD, PATCH & OPTIONS

package main

import "github.com/kataras/iris"

func main() {
	iris.Get("/home", testGet)
	iris.Post("/login",testPost)
	iris.Put("/add",testPut)
	iris.Delete("/remove",testDelete)
	iris.Head("/testHead",testHead)
	iris.Patch("/testPatch",testPatch)
	iris.Options("/testOptions",testOptions)

	iris.Listen(":8080")
}

func testGet(c *iris.Context) {
	//...
}
func testPost(c *iris.Context) {
	//...
}

//and so on....

Declaration

Let's make a pause,

  • Q: Other frameworks needs more lines to start a server, why Iris is different?
  • A: Iris gives you the freedom to choose between three methods/ways to use Iris
  1. global iris.
  2. set a new iris with variable = iris**.New()**
  3. set a new iris with custom options with variable = iris**.Custom(options)**
import "github.com/kataras/iris"

// 1.
func methodFirst() {

	iris.Get("/home",func(c *iris.Context){})
	iris.Listen(":8080")
	//iris.ListenTLS(":8080","yourcertfile.cert","yourkeyfile.key"
}
// 2.
func methodSecond() {

	api := iris.New()
	api.Get("/home",func(c *iris.Context){})
	api.Listen(":8080")
}
// 3.
func methodThree() {
	//these are the default options' values
	options := iris.StationOptions{
		Profile:            false,
		ProfilePath:        iris.DefaultProfilePath,
		Cache:              true,
		CacheMaxItems:      0,
		CacheResetDuration: 5 * time.Minute,
		PathCorrection: 	true, //explanation at the end of this chapter
	}//these are the default values that you can change
	//DefaultProfilePath = "/debug/pprof"

	api := iris.Custom(options)
	api.Get("/home",func(c *iris.Context){})
	api.Listen(":8080")
}

Note that with 2. & 3. you can define and use more than one Iris container in the same app, when it's necessary.

As you can see there are some options that you can chage at your iris declaration, you cannot change them after. If an option value not passed then it considers to be false if bool or the default if string.

For example if we do that...

import "github.com/kataras/iris"
func main() {
	options := iris.StationOptions{
		Cache:				true,
		Profile:            true,
		ProfilePath:        "/mypath/debug",
	}

	api := iris.Custom(options)
	api.Listen(":8080")
}

run it, then you can open your browser, type 'localhost:8080/mypath/debug/profile' at the location input field and you should see a webpage shows you informations about CPU.

For profiling & debug there are seven (7) generated pages ('/debug/pprof/' is the default profile path, which on previous example we changed it to '/mypath/debug'):

  1. /debug/pprof/cmdline
  2. /debug/pprof/profile
  3. /debug/pprof/symbol
  4. /debug/pprof/goroutine
  5. /debug/pprof/heap
  6. /debug/pprof/threadcreate
  7. /debug/pprof/pprof/block

PathCorrection 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, redirects the client to the correct path /home and VICE - VERSA if /home/ is registed but /home is requested then it redirects to /home/ (Default is true)

Party

Let's party with Iris web framework!

func main() {

    //log everything middleware

    iris.UseFunc(func(c *iris.Context) {
		println("[Global log] the requested url path is: ", c.Request.URL.Path)
		c.Next()
	})

    // manage all /users
    users := iris.Party("/users")
    {
  	    // provide a  middleware
		users.UseFunc(func(c *iris.Context) {
			println("LOG [/users...] This is the middleware for: ", c.Request.URL.Path)
			c.Next()
		})
		users.Post("/login", loginHandler)
        users.Get("/:userId", singleUserHandler)
        users.Delete("/:userId", userAccountRemoveUserHandler)
    }



    // Party inside an existing Party example:

    beta:= iris.Party("/beta")

    admin := beta.Party("/admin")
    {
		/// GET: /beta/admin/
		admin.Get("/", func(c *iris.Context){})
		/// POST: /beta/admin/signin
        admin.Post("/signin", func(c *iris.Context){})
		/// GET: /beta/admin/dashboard
        admin.Get("/dashboard", func(c *iris.Context){})
		/// PUT: /beta/admin/users/add
        admin.Put("/users/add", func(c *iris.Context){})
    }



    iris.Listen(":8080")
}

Named Parameters

Named parameters are just custom paths to your routes, you can access them for each request using context's c.Param("nameoftheparameter"). Get all, as array ({Key,Value}) using c.Params property.

No limit on how long a path can be.

Usage:

package main

import "github.com/kataras/iris"

func main() {
	// MATCH to /hello/anywordhere  (if PathCorrection:true match also /hello/anywordhere/)
	// NOT match to /hello or /hello/ or /hello/anywordhere/something
	iris.Get("/hello/:name", func(c *iris.Context) {
		name := c.Param("name")
		c.Write("Hello %s", name)
	})

	// MATCH to /profile/iris/friends/42  (if PathCorrection:true matches also /profile/iris/friends/42/ ,otherwise not match)
	// NOT match to /profile/ , /profile/something ,
	// NOT match to /profile/something/friends,  /profile/something/friends ,
	// NOT match to /profile/anything/friends/42/something
	iris.Get("/profile/:fullname/friends/:friendId",
		func(c *iris.Context){
			name:= c.Param("fullname")
			//friendId := c.ParamInt("friendId")
			c.HTML("<b> Hello </b>"+name)
		})

	iris.Listen(":8080")
	//or
	//log.Fatal(http.ListenAndServe(":8080", iris.Serve()))
}

Match anything and the Static serve handler

####Catch all

// Will match any request which url's preffix is "/anything/" and has content after that
iris.Get("/anything/*randomName", func(c *iris.Context) { } )
// Match: /anything/whateverhere/whateveragain , /anything/blablabla
// c.Params("randomName") will be /whateverhere/whateveragain, blablabla
// Not Match: /anything , /anything/ , /something
Static handler using iris.Static("./path/to/the/resources/directory/", "path_to_strip_or_nothing")
iris.Get("/public/*assets", iris.Static("./static/resources/","/public/"))
// Visible URL-> /public/assets/favicon.ico

Custom HTTP Errors

You can define your own handlers for http errors, which can render an html file for example. e.g for for 404 not found:

package main

import "github.com/kataras/iris"
func main() {
	iris.OnError(404,func (c *iris.Context){
		c.HTML("<h1> The page you looking doesn't exists </h1>")
		c.Status(404)
	})
	//or OnNotFound(func (c *iris.Context){})... for 404 only.
	//or OnPanic(func (c *iris.Context){})... for 500 only.

	//...
}

We saw how to declare a custom error for a http status code, now let's look for how to send/emit an error to the client manually , for example let's emit the 404 we defined before, simple:


iris.Get("/thenotfound",func (c *iris.Context) {
	c.EmitError(404)
	//or c.NotFound() for 404 only.
	//and c.Panic() for 500 only.
})

Context

Variables

  1. ResponseWriter
    • The ResponseWriter is the exactly the same as you used to use with the standar http library.
  2. Request
    • The Request is the pointer of the *Request, is the exactly the same as you used to use with the standar http library.
  3. Params
    • Contains the Named path Parameters, imagine it as a map[string]string which contains all parameters of a request.

Functions

  1. Clone()

    • Returns a clone of the Context, useful when you want to use the context outscoped for example in goroutines.
  2. Write(contents string)

    • Writes a pure string to the ResponseWriter and sends to the client.
  3. Param(key string) returns string

    • Returns the string representation of the key's named parameter's value. Registed path= /profile/:name) Requested url is /profile/something where the key argument is the named parameter's key, returns the value which is 'something' here.
  4. ParamInt(key string) returns integer, error

    • Returns the int representation of the key's named parameter's value, if something goes wrong the second return value, the error is not nil.
  5. URLParam(key string) returns string

    • Returns the string representation of a requested url parameter (?key=something) where the key argument is the name of, something is the returned value.
  6. URLParamInt(key string) returns integer, error

    • Returns the int representation of a requested url parameter
  7. SetCookie(name string, value string)

    • Adds a cookie to the request.
  8. GetCookie(name string) returns string

    • Get the cookie value, as string, of a cookie.
  9. ServeFile(path string)

    • This just calls the http.ServeFile, which serves a file given by the path argument to the client.
  10. NotFound()

    • Sends a http.StatusNotFound with a custom template you defined (if any otherwise the default template is there) to the client. --- Note: We will learn all about Custom Error Handlers later.
  11. Close()

    • Calls the Request.Body.Close().
  12. WriteHTML(status int, contents string) & HTML(contents string)

    • WriteHTML: Writes html string with a given http status to the client, it sets the Header with the correct content-type.
    • HTML: Same as WriteHTML but you don't have to pass a status, it's defaulted to http.StatusOK (200).
  13. WriteData(status int, binaryData []byte) & Data(binaryData []byte)

    • WriteData: Writes binary data with a given http status to the client, it sets the Header with the correct content-type.
    • Data : Same as WriteData but you don't have to pass a status, it's defaulted to http.StatusOK (200).
  14. WriteText(status int, contents string) & Text(contents string)

    • WriteText: Writes plain text with a given http status to the client, it sets the Header with the correct content-type.
    • Text: Same as WriteTextbut you don't have to pass a status, it's defaulted to http.StatusOK (200).
  15. ReadJSON(jsonObject interface{}) error

    • ReadJSON: reads the request's body content and parses it, assigning the result into jsonObject passed by argument. Don't forget to pass the argument as reference.
  16. WriteJSON(status int, jsonObject interface{}) & JSON(jsonObject interface{}) returns error

    • WriteJSON: Writes json which is converted from structed object(s) with a given http status to the client, it sets the Header with the correct content-type. If something goes wrong then it's returned value which is an error type is not nil. No indent.
  17. RenderJSON(jsonObjects ...interface{}) returns error - RenderJSON: Same as WriteJSON & JSON but with Indent (formated json) - JSON: Same as WriteJSON but you don't have to pass a status, it's defaulted to http.StatusOK (200).

  18. ReadXML(xmlObject interface{}) error

    • ReadXML: reads the request's body and parses it, assigin the result into xmlObject passed by argument.
  19. WriteXML(status int, xmlBytes []byte) & XML(xmlBytes []byte) returns error

    • WriteXML: Writes writes xml which is converted from []byte( usualy string) with a given http status to the client, it sets the Header with the correct content-type. If something goes wrong then it's returned value which is an error type is not nil.
    • XML: Same as WriteXML but you don't have to pass a status, it's defaulted to http.StatusOK (200).
  20. RenderFile(file string, pageContext interface{}) returns error

    • RenderFile: Renders a file by its name (which a file is saved to the template cache) and a page context passed to the function, default http status is http.StatusOK(200) if the template was found, otherwise http.StatusNotFound(404). If something goes wrong then it's returned value which is an error type is not nil.
  21. Render(pageContext interface{}) returns error

    • Render: Renders the root file template and a context passed to the function, default http status is http.StatusOK(200) if the template was found, otherwise http.StatusNotFound(404). If something goes wrong then it's returned value which is an error type is not nil. --- Note: We will learn how to add templates at the next chapters.
  22. Next()

    • Next: calls all the next handler from the middleware stack, it used inside a middleware.
  23. SendStatus(statusCode int, message string)

    • SendStatus: writes a http statusCode with a text/plain message.
  24. Redirect(url string, statusCode...int) - Redirect: redirects the client to a specific relative path, if statusCode is empty then 302 is used (temporary redirect).

  25. EmitError(statusCode int)

    • EmitError: sends the custom error to the client by it's status code ( see Custom HTTP Errors chapter).
  26. Panic()

    • Panic: sends the 500 internal server (custom) error to the client.

[[TODO chapters: Register custom error handlers, cache templates , create & use middleware]]

Inside the examples branch you will find practical examples

Plugins

Plugins are modules that you can build to inject the Iris' flow. Think it like a middleware for the Iris framework itself, not only the requests. Middleware starts it's actions after the server listen, Plugin on the other hand starts working when you registed them, from the begin, to the end. Look how it's interface looks:

type (
	// IPlugin is the interface which all Plugins must implement.
	//
	// A Plugin can register other plugins also from it's Activate state
	IPlugin interface {
		// GetName has to returns the name of the plugin, a name is unique
		// name has to be not dependent from other methods of the plugin,
		// because it is being called even before the Activate
		GetName() string
		// GetDescription has to returns the description of what the plugins is used for
		GetDescription() string

		// Activate called BEFORE the plugin being added to the plugins list,
		// if Activate returns none nil error then the plugin is not being added to the list
		// it is being called only one time
		//
		// PluginContainer parameter used to add other plugins if that's necessary by the plugin
		Activate(IPluginContainer) error
	}

	IPluginPreHandle interface {
		// PreHandle it's being called every time BEFORE a Route is registed to the Router
		//
		//  parameter is the Route
		PreHandle(IRoute)
	}

	IPluginPostHandle interface {
		// PostHandle it's being called every time AFTER a Route successfully registed to the Router
		//
		// parameter is the Route
		PostHandle(IRoute)
	}

	IPluginPreListen interface {
		// PreListen it's being called only one time, BEFORE the Server is started (if .Listen called)
		// is used to do work at the time all other things are ready to go
		//  parameter is the station
		PreListen(*Station)
	}

	IPluginPostListen interface {
		// PostListen it's being called only one time, AFTER the Server is started (if .Listen called)
		// parameter is the station
		PostListen(*Station)
	}

	IPluginPreClose interface {
		// PreClose it's being called only one time, BEFORE the Iris .Close method
		// any plugin cleanup/clear memory happens here
		//
		// The plugin is deactivated after this state
		PreClose(*Station)
	}
)

A small example, imagine that you want to get all routes registered to your server (OR modify them at runtime), with their time registed, methods, (sub)domain and the path, what whould you do on other frameworks when you want something from the framework which it doesn't supports out of the box? and what you can do with Iris:

//file myplugin.go
package main

import (
	"time"

	"github.com/kataras/iris"
)

type RouteInfo struct {
	Method       string
	Domain       string
	Path         string
	TimeRegisted time.Time
}

type myPlugin struct {
	container iris.IPluginContainer
	routes    []RouteInfo
}

func NewMyPlugin() *myPlugin {
	return &myPlugin{routes: make([]RouteInfo, 0)}
}

// All plugins must at least implements these 3 functions

func (i *myPlugin) Activate(container iris.IPluginContainer) error {
	// use the container if you want to register other plugins to the server, yes it's possible a plugin can registers other plugins too.
	// here we set the container in order to use it's printf later at the PostListen.
	i.container = container
	return nil
}

func (i myPlugin) GetName() string {
	return "MyPlugin"
}

func (i myPlugin) GetDescription() string {
	return "My Plugin is just a simple Iris plugin.\n"
}

//
// Implement our plugin, you can view your inject points - listeners on the /kataras/iris/plugin.go too.
//
// Implement the PostHandle, because this is what we need now, we need to add a listener after a route is registed to our server so we do:
func (i *myPlugin) PostHandle(route iris.IRoute) {
	myRouteInfo := &RouteInfo{}
	myRouteInfo.Method = route.GetMethod()
	myRouteInfo.Domain = route.GetDomain()
	myRouteInfo.Path = route.GetPath()

	myRouteInfo.TimeRegisted = time.Now()

	i.routes = append(i.routes, myRouteInfo)
}

// PostListen called after the server is started, here you can do a lot of staff
// you have the right to access the whole iris' Station also, here you can add more routes and do anything you want, for example start a second server too, an admin web interface!
// for example let's print to the server's stdout the routes we collected...
func (i *myPlugin) PostListen(s *iris.Station) {
	i.container.Printf("From MyPlugin: You have registed %d routes ", len(i.routes))
	//do what ever you want, if you have imagination you can do a lot
}

//

Let's register our plugin:


//file main.go
package main

import "github.com/kataras/iris"

func main() {
   iris.Plugin(NewMyPlugin())
   //the plugin is running and caching all these routes
   iris.Get("/", func(c *iris.Context){})
   iris.Post("/login", func(c *iris.Context){})
   iris.Get("/login", func(c *iris.Context){})
   iris.Get("/something", func(c *iris.Context){})

   iris.Listen()
}


Output:

From MyPlugin: You have registed 4 routes

An example of one plugin which is under development is the Iris control, a web interface that gives you control to your server remotely. You can find it's code here

Benchmarks

With Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz 2.50 HGz and 8GB Ram:

Benchmark Wizzard 24 March 2016 - comparing the fasters

See all benchmarks

  1. Total Operations (Executions)
  2. Nanoseconds per operation ns/op
  3. Heap Memory B/op
  4. Allocations per operation allocs/op
Benchmark name Total Operations ns/op B/op allocs/op
BenchmarkAce_GithubAll 10000 121206 13792 167
BenchmarkBear_GithubAll 10000 348919 86448 943
BenchmarkBeego_GithubAll 5000 296816 16608 524
BenchmarkBone_GithubAll 500 2502143 548736 7241
BenchmarkDenco_GithubAll 20000 99705 20224 167
BenchmarkEcho_GithubAll 30000 45469 0 0
BenchmarkGin_GithubAll 50000 39402 0 0
BenchmarkGocraftWeb_GithubAll 5000 446025 131656 1686
BenchmarkGoji_GithubAll 2000 547698 56112 334
BenchmarkGojiv2_GithubAll 2000 763043 118864 3103
BenchmarkGoJsonRest_GithubAll 5000 538030 134371 2737
BenchmarkGoRestful_GithubAll 100 14870850 837832 6913
BenchmarkGorillaMux_GithubAll 200 6690383 144464 1588
BenchmarkHttpRouter_GithubAll 20000 65653 13792 167
BenchmarkHttpTreeMux_GithubAll 10000 215312 65856 671
BenchmarkIris_GithubAll 100000 20731 0 0
BenchmarkKocha_GithubAll 10000 167209 23304 843
BenchmarkLARS_GithubAll 30000 41069 0 0
BenchmarkMacaron_GithubAll 2000 665038 201138 1803
BenchmarkMartini_GithubAll 100 5433644 228213 2483
BenchmarkPat_GithubAll 300 4210240 1499569 27435
BenchmarkPossum_GithubAll 10000 255114 84448 609
BenchmarkR2router_GithubAll 10000 237113 77328 979
BenchmarkRevel_GithubAll 2000 1150565 337424 5512
BenchmarkRivet_GithubAll 20000 96555 16272 167
BenchmarkTango_GithubAll 5000 417423 87075 2267
BenchmarkTigerTonic_GithubAll 2000 994556 233680 5035
BenchmarkTraffic_GithubAll 200 7770444 2659331 21848
BenchmarkVulcan_GithubAll 5000 292216 19894 609

Third Party Middlewares

Note: Some of these, may not be work.

Iris has a middleware system to create it's own middleware and is at a state which tries to find person who are be willing to convert them to Iris middleware or create new. Contact or open an issue if you are interesting.

Middleware Author Description Tested
sessions Ported to Iris Session Management Yes
Graceful Tyler Bunnell Graceful HTTP Shutdown Yes
gzip Iris GZIP response compression Yes
RestGate Prasanga Siripala Secure authentication for REST API endpoints No
secure Cory Jacobsen Middleware that implements a few quick security wins Yes
JWT Middleware Auth0 Middleware checks for a JWT on the Authorization header on incoming requests and decodes it No
binding Matt Holt Data binding from HTTP requests into structs No
i18n Iris Internationalization and Localization Yes
logrus Dan Buch Logrus-based logger No
render Cory Jacobsen Render JSON, XML and HTML templates No
gorelic Jingwen Owen Ou New Relic agent for Go runtime No
pongo2 Iris Middleware for pongo2 templates Yes
oauth2 David Bochenski oAuth2 middleware No
permissions2 Alexander Rødseth Cookies, users and permissions No
onthefly Alexander Rødseth Generate TinySVG, HTML and CSS on the fly No
cors Keuller Magalhaes Cross Origin Resource Sharing (CORS) support Yes
xrequestid Andrea Franz Middleware that assigns a random X-Request-Id header to each request No
VanGoH Taylor Wrobel Configurable AWS-Style HMAC authentication middleware No
stats Florent Messa Store information about your web application (response time, etc.) No

Contributors

Thanks goes to the people who have contributed code to this package, see the GitHub Contributors page.

Community

If you'd like to discuss this package, or ask questions about it, feel free to

Guidelines

  • Never stop writing the docs.
  • Provide full README for examples branch and thirdparty middleware examples.
  • Before any commit run -count 50 -benchtime 30s , if performance stays on top then commit else find other way to do the same thing.
  • Notice the author of any thirdparty package before I try to port into iris myself, maybe they can do it better.
  • Notice author's of middleware, which I'm writing examples for,to take a look, if they don't want to exists in the Iris community, I have to respect them.

Todo

Articles

According to my article ( comparative ultra wide frame Go Http routing performance ) on a variety of relatively Go http routing framework, Iris clear winner, its performance far exceeds other Golang http routing framework.

  • +1 pending article waiting, after writer's holidays

License

This project is licensed under the BSD 3-Clause License. License can be found here.

Documentation

Overview

Copyright (c) 2013, Julien Schmidt Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distributiob.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permissiob.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURindexE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE indexSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos and Go Authors using for the 'log,io,os' packages All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimep.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Copyright (c) 2016, Gerasimos Maropoulos All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  1. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTOR, GERASIMOS MAROPOULOS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Index

Constants

View Source
const (
	// DefaultCharset represents the default charset for content headers
	DefaultCharset = "UTF-8"
	// ContentType represents the header["Content-Type"]
	ContentType = "Content-Type"
	// ContentLength represents the header["Content-Length"]
	ContentLength = "Content-Length"
	// ContentHTML is the  string of text/html response headers
	ContentHTML = "text/html"
	// ContentJSON is the  string of application/json response headers
	ContentJSON = "application/json"
	// ContentJSONP is the  string of application/javascript response headers
	ContentJSONP = "application/javascript"
	// ContentBINARY is the  string of "application/octet-stream response headers
	ContentBINARY = "application/octet-stream"
	// ContentTEXT is the  string of text/plain response headers
	ContentTEXT = "text/plain"
	// ContentXML is the  string of application/xml response headers
	ContentXML = "application/xml"
	// ContentXMLText is the  string of text/xml response headers
	ContentXMLText = "text/xml"
)
View Source
const (
	// ParameterStartByte is very used on the node, it's just contains the byte for the ':' rune/char
	ParameterStartByte = byte(':')
	// SlashByte is just a byte of '/' rune/char
	SlashByte = byte('/')
	// Slash is just a string of "/"
	Slash = "/"
	// MatchEverythingByte is just a byte of '*" rune/char
	MatchEverythingByte = byte('*')
)
View Source
const (
	// DefaultProfilePath is the default path for the web pprof '/debug/pprof'
	DefaultProfilePath = "/debug/pprof"
)
View Source
const (
	// LoggerIrisPrefix is the prefix of the logger '[IRIS] '
	LoggerIrisPrefix = "[IRIS] "
)

Variables

View Source
var Charset = DefaultCharset

Charset is defaulted to UTF-8, you can change it all render methods will have this charset

View Source
var HTTPMethods = struct {
	GET, POST, PUT, DELETE, CONNECT, HEAD, PATCH, OPTIONS, TRACE string
	ALL, ANY                                                     []string //ALL and ANY are exctactly the same I keep both keys, no problem no big array :P
}{"GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", "PATCH", "OPTIONS", "TRACE",
	[]string{"GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", "PATCH", "OPTIONS", "TRACE"},
	[]string{"GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", "PATCH", "OPTIONS", "TRACE"}}

HTTPMethods is just a representation of the available http methods, use to make API. I know they are already exist in the http package, ex: http.MethodConnect, maybe at the future I will remove them from here and keep only the ANY.

View Source
var LoggerOutTerminal = os.Stdout

LoggerOutTerminal os.Stdout , it's the default io.Writer to the Iris' logger

Functions

func Any

func Any(path string, handlersFn ...HandlerFunc)

Any registers a route for ALL of the http methods (Get,Post,Put,Head,Patch,Options,Connect,Delete)

func Close

func Close()

Close is used to close the net.Listener of the standalone http server which has already running via .Listen

func Connect

func Connect(path string, handlersFn ...HandlerFunc)

Connect registers a route for the Connect http method

func CorsMethodMatch

func CorsMethodMatch(m1, reqMethod string) bool

CorsMethodMatch is sets the methodMatch when cors enabled (look OptimusPrime), it's allowing OPTIONS method to all other methods except GET just this

func Delete

func Delete(path string, handlersFn ...HandlerFunc)

Delete registers a route for the Delete http method

func EmitError

func EmitError(statusCode int, ctx *Context)

EmitError emits an error with it's http status code and the iris Context passed to the function

func Get

func Get(path string, handlersFn ...HandlerFunc)

Get registers a route for the Get http method

func GetParamsLen

func GetParamsLen(path string) uint8

GetParamsLen returns the parameters length from a given path

func Handle

func Handle(method string, registedPath string, handlers ...Handler)

Handle registers a route to the server's router

func HandleAnnotated

func HandleAnnotated(irisHandler Handler) error

HandleAnnotated registers a route handler using a Struct implements iris.Handler (as anonymous property) which it's metadata has the form of `method:"path"` and returns the route and an error if any occurs handler is passed by func(urstruct MyStruct) Serve(ctx *Context) {}

func HandleFunc

func HandleFunc(method string, path string, handlersFn ...HandlerFunc)

HandleFunc registers a route with a method, path string, and a handler

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

Head registers a route for the Head http method

func Listen

func Listen(fullHostOrPort ...string) error

Listen starts the standalone http server which listens to the fullHostOrPort parameter which as the form of host:port or just port or empty, the default is 127.0.0.1:8080

func ListenTLS

func ListenTLS(fullAddress string, certFile, keyFile string) error

ListenTLS Starts a httpS/http2 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 fullHostOrPort parameter which as the form of host:port

func MethodMatch

func MethodMatch(m1, m2 string) bool

MethodMatch for normal method match

func OnError

func OnError(statusCode int, handlerFunc HandlerFunc)

OnError registers an error to the http custom errors first parameter is the http status code ( int ) second parameter is the actual handler which called when this status code occured, type of HandlerFunc

func OnNotFound

func OnNotFound(handlerFunc HandlerFunc)

OnNotFound sets the handler for http status 404, default is a response with text: 'Not Found' and status: 404

func OnPanic

func OnPanic(handlerFunc HandlerFunc)

OnPanic sets the handler for http status 500, default is a response with text: The server encountered an unexpected condition which prevented it from fulfilling the request. and status: 500

func OptimusPrime

func OptimusPrime()

OptimusPrime , YOU MUST RUN IT ONLY IF YOU DON'T USE iris.Listen or iris.Serve() method

func Options

func Options(path string, handlersFn ...HandlerFunc)

Options registers a route for the Options http method

func ParseAddr

func ParseAddr(fullHostOrPort []string) string

ParseAddr gets a slice of string and returns the address of which the Iris' server can listen

func Patch

func Patch(path string, handlersFn ...HandlerFunc)

Patch registers a route for the Patch http method

func Plugin

func Plugin(plugin IPlugin) error

Plugin activates the plugins and if succeed then adds it to the activated plugins list

func Post

func Post(path string, handlersFn ...HandlerFunc)

Post registers a route for the Post http method

func Put

func Put(path string, handlersFn ...HandlerFunc)

Put registers a route for the Put http method

func Serve

func Serve() http.Handler

Serve is used instead of the iris.Listen eg http.ListenAndServe(":80",iris.Serve()) if you don't want to use iris.Listen(":80") ( you can't use iris because its package variable it's golang limitation)

func ServeHTTP

func ServeHTTP(res http.ResponseWriter, req *http.Request)

ServeHTTP serves an http request, with this function iris can be used also as a middleware into other already defined http server

func Templates

func Templates(pathGlob string)

Templates sets the templates glob path for the web app

func Trace

func Trace(path string, handlersFn ...HandlerFunc)

Trace registers a route for the Trace http methodd

func URLParam

func URLParam(req *http.Request, key string) string

URLParam returns the get parameter from a request , if any

func URLParams

func URLParams(req *http.Request) url.Values

URLParams the URL.Query() is a complete function which returns the url get parameters from the url query, We don't have to do anything else here.

func Use

func Use(handlers ...Handler)

Use appends a middleware to the route or to the router if it's called from router

func UseFunc

func UseFunc(handlersFn ...HandlerFunc)

UseFunc same as Use but it accepts/receives ...HandlerFunc instead of ...Handler form of acceptable: func(c *iris.Context){//first middleware}, func(c *iris.Context){//second middleware}

func Ws

func Ws(path string, handler Handler)

Ws registers a websocket route

Types

type Branch

type Branch struct {
	BranchCase BranchCase
	// contains filtered or unexported fields
}

Branch is the node of a tree of the routes, in order to learn how this is working, google 'trie' or watch this lecture: https://www.youtube.com/watch?v=uhAUk63tLRM this method is used by the BSD's kernel also

func (*Branch) AddBranch

func (b *Branch) AddBranch(path string, middleware Middleware)

AddBranch adds a branch to the existing branch or to the tree if no branch has the prefix of

func (*Branch) AddNode

func (b *Branch) AddNode(numParams uint8, path string, fullPath string, middleware Middleware)

AddNode adds a branch as children to other Branch

func (*Branch) GetBranch

func (b *Branch) GetBranch(path string, _params PathParameters) (middleware Middleware, params PathParameters, mustRedirect bool)

GetBranch is used by the Router, it finds and returns the correct branch for a path

func (*Branch) GivePrecedenceTo

func (b *Branch) GivePrecedenceTo(index int) int

GivePrecedenceTo just adds the priority of this branch by an index

type BranchCase

type BranchCase uint8

BranchCase is the type which the type of Branch using in order to determinate what type (parameterized, anything, static...) is the perticular node

type Context

type Context struct {
	ResponseWriter IMemoryWriter
	Request        *http.Request
	Params         PathParameters
	// contains filtered or unexported fields
}

Context is resetting every time a request is coming to the server, it holds a pointer to the http.Request, the ResponseWriter the Named Parameters (if any) of the requested path and an underline Renderer.

func (*Context) Clone

func (ctx *Context) Clone() *Context

Clone before we had (c Context) inscope and (c *Context) for outscope like goroutines now we have (c *Context) for both sittuations ,and call .Clone() if we need to pass the context in a gorotoune or to a time func example:

api.Get("/user/:id", func(ctx *iris.Context) {
		c:= ctx.Clone()
		time.AfterFunc(20 * time.Second, func() {
			println(" 20 secs after: from user with id:", c.Param("id"), " context req path:", c.Request.URL.Path)
		})
	})

func (*Context) Close

func (ctx *Context) Close()

Close is used to close the body of the request /TODO: CHECK FOR REQUEST CLOSED IN ORDER TO FIX SOME ERRORS HERE

func (*Context) Data

func (ctx *Context) Data(binaryData []byte)

Data calls the WriteData with the 200 http status ok

func (*Context) Deadline

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

Deadline returns the time when this Context will be canceled, if any.

func (*Context) Do

func (ctx *Context) Do()

Do calls the first handler only, it's like Next with negative pos, used only on Router&MemoryRouter

func (*Context) Done

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

Done returns a channel that is closed when this Context is canceled or times out.

func (*Context) EmitError

func (ctx *Context) EmitError(statusCode int)

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

func (*Context) End

func (ctx *Context) End()

End same as Close, end the response process.

func (*Context) Err

func (ctx *Context) Err() error

Err indicates why this context was canceled, after the Done channel is closed.

func (*Context) Get

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

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

func (*Context) GetCookie

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

GetCookie returns cookie's value by it's name

func (*Context) GetFmt

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

GetFmt returns a value which has this format: func(format string, args ...interface{}) string if doesn't exists returns nil

func (*Context) GetHandlerName

func (ctx *Context) GetHandlerName() string

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

func (*Context) GetInt

func (ctx *Context) GetInt(key string) (value int)

GetInt same as Get but returns the value as int

func (*Context) GetMemoryResponseWriter

func (ctx *Context) GetMemoryResponseWriter() MemoryWriter

GetMemoryResponseWriter returns the MemoryWriter of the Context

func (*Context) GetRequest

func (ctx *Context) GetRequest() *http.Request

GetRequest returns the *http.Request of the Context

func (*Context) GetResponseWriter

func (ctx *Context) GetResponseWriter() IMemoryWriter

GetResponseWriter returns the MemoryWriter of the Context

func (*Context) GetString

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

GetString same as Get but returns the value as string

func (*Context) HTML

func (ctx *Context) HTML(htmlContents string)

HTML calls the WriteHTML with the 200 http status ok

func (*Context) IsStopped

func (ctx *Context) IsStopped() bool

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

func (*Context) JSON

func (ctx *Context) JSON(jsonObjectOrArray interface{}) error

JSON calls the WriteJSON with the 200 http status ok

func (*Context) Next

func (ctx *Context) Next()

Next calls all the next handler from the middleware stack, it used inside a middleware

func (*Context) NotFound

func (ctx *Context) NotFound()

NotFound emits an error 404 to the client, using the custom http errors if no custom errors provided then it sends the default http.NotFound

func (*Context) Panic

func (ctx *Context) Panic()

Panic stops the executions of the context and returns the registed panic handler or if not, the default which is 500 http status to the client

This function is useful when you use the recovery middleware, which is auto-executing the (custom, registed) 500 internal server error.

func (*Context) Param

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

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

func (*Context) ParamInt

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

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

func (*Context) ReadJSON

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

ReadJSON reads JSON from request's body

func (*Context) ReadXML

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

ReadXML reads XML from request's body

func (*Context) Redirect

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

Redirect redirect sends a redirect response the client accepts 2 parameters string and an optional int first parameter is the url to redirect second parameter is the http status should send, default is 302 (Temporary redirect), you can set it to 301 (Permant redirect), if that's nessecery

func (*Context) Redo

func (ctx *Context) Redo(res http.ResponseWriter, req *http.Request)

Redo is used inside the MemoryRouter from a cached Context, do whatever Do does but it sets the newresponsewriter and the request before that

func (*Context) RemoteAddr

func (ctx *Context) RemoteAddr() string

RemoteAddr is like RequestIP but it checks for proxy servers also, tries to get the real client's request IP

func (*Context) Render

func (ctx *Context) Render(pageContext interface{}) error

Render renders the template file html which is already registed to the template cache, with it's pageContext passed to the function

func (*Context) RenderFile

func (ctx *Context) RenderFile(file string, pageContext interface{}) error

RenderFile renders a file by its path and a context passed to the function

func (*Context) RenderJSON

func (ctx *Context) RenderJSON(httpStatus int, jsonStructs ...interface{}) error

RenderJSON renders json objects with indent

func (*Context) RenderXML

func (ctx *Context) RenderXML(httpStatus int, xmlStructs ...interface{}) error

RenderXML writes xml which is converted from struct(s) with a http status which they passed to the function via parameters

func (*Context) RequestIP

func (ctx *Context) RequestIP() string

RequestIP gets just the Remote Address from the client.

func (*Context) Reset

func (ctx *Context) Reset(res http.ResponseWriter, req *http.Request)

Reset resets the Context with a given http.ResponseWriter and *http.request the context is ready-to-use after that, just like a new Context I use it for zero rellocation memory

func (*Context) SendStatus

func (ctx *Context) SendStatus(statusCode int, message string)

SendStatus sends a http status to the client it receives status code (int) and a message (string)

func (*Context) ServeFile

func (ctx *Context) ServeFile(path string)

ServeFile is used to serve a file, via the http.ServeFile

func (*Context) Set

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

Set sets a value to a key in the values map

func (*Context) SetContentType

func (ctx *Context) SetContentType(s []string)

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

func (*Context) SetCookie

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

SetCookie adds a cookie to the request

func (*Context) SetHeader

func (ctx *Context) SetHeader(k string, s []string)

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

func (*Context) SetMemoryResponseWriter

func (ctx *Context) SetMemoryResponseWriter(res MemoryWriter)

SetMemoryResponseWriter sets a particular iris.MemoryWriter to the Context

this can be useful on the middlewares which they have access to change the response object itself (the gzip middleware does it)

func (*Context) SetRequest

func (ctx *Context) SetRequest(req *http.Request)

SetRequest sets a particular *http.Request to the Context

this can be useful on the middlewares which they have access to change the request object itself

func (*Context) SetResponseWriter

func (ctx *Context) SetResponseWriter(res IMemoryWriter)

SetResponseWriter sets the MemoryWriter of the Context

func (*Context) StopExecution

func (ctx *Context) StopExecution()

StopExecution just sets the .pos to 255 in order to not move to the next middlewares(if any)

func (*Context) Text

func (ctx *Context) Text(text string)

Text calls the WriteText with the 200 http status ok

func (*Context) URLParam

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

URLParam returns the get parameter from a request , if any

func (*Context) URLParamInt

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

URLParamInt returns the get parameter int value from a request , if any

func (*Context) Value

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

Value returns the value associated with key or nil if none.

func (*Context) Write

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

Write writes a string via the context's ResponseWriter

func (*Context) WriteData

func (ctx *Context) WriteData(httpStatus int, binaryData []byte)

WriteData writes binary data with a http status

func (*Context) WriteHTML

func (ctx *Context) WriteHTML(httpStatus int, htmlContents string)

WriteHTML writes html string with a http status /TODO or I will think to pass an interface on handlers as second parameter near to the Context, with developer's custom Renderer package .. I will think about it.

func (*Context) WriteJSON

func (ctx *Context) WriteJSON(httpStatus int, jsonObjectOrArray interface{}) error

WriteJSON writes JSON which is encoded from a single json object or array with no Indent

func (*Context) WriteStatus

func (ctx *Context) WriteStatus(statusCode int)

WriteStatus write/or/and/sends to client, to the response writer a given status code

func (*Context) WriteText

func (ctx *Context) WriteText(httpStatus int, text string)

WriteText writes text with a http status

func (*Context) WriteXML

func (ctx *Context) WriteXML(httpStatus int, xmlB []byte) error

WriteXML writes xml which from []byte

func (*Context) XML

func (ctx *Context) XML(xmlBytes []byte) error

XML calls the WriteXML with the 200 http status ok

type ContextCache

type ContextCache struct {
	MaxItems int
	// contains filtered or unexported fields
}

ContextCache creation done with just &ContextCache{}

func NewContextCache

func NewContextCache() *ContextCache

NewContextCache returns the cache for a router, is used on the MemoryRouter

func (*ContextCache) AddItem

func (mc *ContextCache) AddItem(method, url string, ctx *Context)

AddItem adds an item to the bag/cache, is a goroutine.

func (*ContextCache) DoOnTick

func (mc *ContextCache) DoOnTick()

DoOnTick raised every time the ticker ticks, can be called independed, it's just check for items len and resets the cache

func (*ContextCache) GetItem

func (mc *ContextCache) GetItem(method, url string) *Context

GetItem returns an item from the bag/cache, if not exists it returns just nil.

func (*ContextCache) OnTick

func (mc *ContextCache) OnTick()

OnTick is the implementation of the ITick it makes the ContextCache a ticker's listener

func (*ContextCache) SetMaxItems

func (mc *ContextCache) SetMaxItems(_itemslen int)

SetMaxItems receives int and set max cached items to this number

type DownloadManager

type DownloadManager struct {
}

DownloadManager is just a struch which exports the util's downloadZip, directoryExists, unzip methods, used by the plugins via the PluginContainer

func (*DownloadManager) DirectoryExists

func (d *DownloadManager) DirectoryExists(dir string) bool

DirectoryExists returns true if a given local directory exists

func (*DownloadManager) DownloadZip

func (d *DownloadManager) DownloadZip(zipURL string, targetDir string) (string, error)

DownloadZip downlodas a zip to the given local path location

func (*DownloadManager) Install

func (d *DownloadManager) Install(remoteFileZip string, targetDirectory string) (string, error)

Install is just the flow of the: DownloadZip->Unzip->Remove the zip

func (*DownloadManager) Remove

func (d *DownloadManager) Remove(filePath string) error

Remove deletes/removes/rm a file

func (*DownloadManager) Unzip

func (d *DownloadManager) Unzip(archive string, target string) (string, error)

Unzip unzips a zip to the given local path location

type ErrorHandler

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

ErrorHandler is just an object which stores a http status code and a handler

func (ErrorHandler) GetCode

func (e ErrorHandler) GetCode() int

GetCode returns the http status code value

func (ErrorHandler) GetHandler

func (e ErrorHandler) GetHandler() HandlerFunc

GetHandler returns the handler which is type of HandlerFunc

func (*ErrorHandler) SetHandler

func (e *ErrorHandler) SetHandler(h HandlerFunc)

SetHandler sets the handler (type of HandlerFunc) to this particular ErrorHandler

type Garden

type Garden []tree

Garden is the main area which routes are planted/placed

func (Garden) Plant

func (g Garden) Plant(_route IRoute) Garden

Plant plants/adds a route to the garden

type GardenParty

type GardenParty struct {
	MiddlewareSupporter
	// contains filtered or unexported fields
}

GardenParty TODO: inline docs

func (*GardenParty) Any

func (p *GardenParty) Any(path string, handlersFn ...HandlerFunc)

Any registers a route for ALL of the http methods (Get,Post,Put,Head,Patch,Options,Connect,Delete)

func (*GardenParty) Connect

func (p *GardenParty) Connect(path string, handlersFn ...HandlerFunc)

Connect registers a route for the Connect http method

func (*GardenParty) Delete

func (p *GardenParty) Delete(path string, handlersFn ...HandlerFunc)

Delete registers a route for the Delete http method

func (*GardenParty) Get

func (p *GardenParty) Get(path string, handlersFn ...HandlerFunc)

Get registers a route for the Get http method

func (*GardenParty) Handle

func (p *GardenParty) Handle(method string, registedPath string, handlers ...Handler)

Handle registers a route to the server's router

func (*GardenParty) HandleAnnotated

func (p *GardenParty) HandleAnnotated(irisHandler Handler) error

HandleAnnotated registers a route handler using a Struct implements iris.Handler (as anonymous property) which it's metadata has the form of `method:"path"` and returns the route and an error if any occurs handler is passed by func(urstruct MyStruct) Serve(ctx *Context) {}

func (*GardenParty) HandleFunc

func (p *GardenParty) HandleFunc(method string, registedPath string, handlersFn ...HandlerFunc)

HandleFunc registers and returns a route with a method string, path string and a handler registedPath is the relative url path handler is the iris.Handler which you can pass anything you want via iris.ToHandlerFunc(func(res,req){})... or just use func(c *iris.Context)

func (*GardenParty) Head

func (p *GardenParty) Head(path string, handlersFn ...HandlerFunc)

Head registers a route for the Head http method

func (*GardenParty) Options

func (p *GardenParty) Options(path string, handlersFn ...HandlerFunc)

Options registers a route for the Options http method

func (*GardenParty) Party

func (p *GardenParty) Party(path string) IParty

Party is just a group joiner of routes which have the same prefix and share same middleware(s) also. Party can also be named as 'Join' or 'Node' or 'Group' , Party chosen because it has more fun

func (*GardenParty) Patch

func (p *GardenParty) Patch(path string, handlersFn ...HandlerFunc)

Patch registers a route for the Patch http method

func (*GardenParty) Post

func (p *GardenParty) Post(path string, handlersFn ...HandlerFunc)

Post registers a route for the Post http method

func (*GardenParty) Put

func (p *GardenParty) Put(path string, handlersFn ...HandlerFunc)

Put registers a route for the Put http method

func (*GardenParty) Trace

func (p *GardenParty) Trace(path string, handlersFn ...HandlerFunc)

Trace registers a route for the Trace http method

func (*GardenParty) Use

func (p *GardenParty) Use(handlers ...Handler)

Use pass the middleware here it overrides the MiddlewareSupporter's Use only in order to be able to call forceOptimusPrime

func (*GardenParty) Ws

func (p *GardenParty) Ws(path string, handler Handler)

Ws registers a websocket route

type HTTPErrors

type HTTPErrors struct {
	//developer can do Errors.On(500, iris.Handler)
	ErrorHanders []IErrorHandler
}

HTTPErrors is the struct which contains the handlers which will execute if http error occurs One struct per Server instance, the meaning of this is that the developer can change the default error message and replace them with his/her own completely custom handlers

Example of usage: iris.OnError(405, func (ctx *iris.Context){ c.SendStatus(405,"Method not allowed!!!")}) and inside the handler which you have access to the current Context: ctx.EmitError(405) that is the circle, the httpErrors variable stays at the Station(via it's Router), sets from there and emits from a context, but you can also emit directly from iris.Errors().Emit(405,ctx) if that's necessary

func (*HTTPErrors) Emit

func (he *HTTPErrors) Emit(errCode int, ctx *Context)

Emit executes the handler of the given error http status code

func (*HTTPErrors) GetByCode

func (he *HTTPErrors) GetByCode(httpStatus int) IErrorHandler

GetByCode returns the error handler by it's http status code

func (*HTTPErrors) On

func (he *HTTPErrors) On(httpStatus int, handler HandlerFunc)

On Registers a handler for a specific http error status

type Handler

type Handler interface {
	Serve(ctx *Context)
}

Handler the main Iris Handler interface.

func ConvertToHandlers

func ConvertToHandlers(handlersFn []HandlerFunc) []Handler

ConvertToHandlers accepts list of HandlerFunc and returns list of Handler this can be renamed to convertToMiddleware also because it returns a list of []Handler which is what Middleware is

func ToHandler

func ToHandler(handler interface{}) Handler

ToHandler converts http.Handler or func(http.ResponseWriter, *http.Request) to an iris.Handler

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

func ErrorHandlerFunc

func ErrorHandlerFunc(statusCode int, message string) HandlerFunc

ErrorHandlerFunc creates a handler which is responsible to send a particular error to the client

func Static

func Static(SystemPath string, PathToStrip ...string) HandlerFunc

Static is just a function which returns a HandlerFunc with the standar http's fileserver's handler It is not a middleware, it just returns a HandlerFunc to use anywhere we want

func ToHandlerFunc

func ToHandlerFunc(handler interface{}) HandlerFunc

ToHandlerFunc converts http.Handler or func(http.ResponseWriter, *http.Request) to an iris.HandlerFunc func (ctx *Context)

func (HandlerFunc) Serve

func (h HandlerFunc) Serve(ctx *Context)

Serve serves the handler, is like ServeHTTP for Iris

type IBranch

type IBranch interface {
	AddBranch(string, Middleware)
	AddNode(uint8, string, string, Middleware)
	GetBranch(string, PathParameters) (Middleware, PathParameters, bool)
	GivePrecedenceTo(index int) int
}

IBranch is the interface which the type Branch must implement

type IContext

type IContext interface {
	context.Context
	Reset(http.ResponseWriter, *http.Request)
	Do()
	Redo(http.ResponseWriter, *http.Request)
	Next()
	GetResponseWriter() IMemoryWriter
	GetRequest() *http.Request
	GetMemoryResponseWriter() MemoryWriter
	SetMemoryResponseWriter(MemoryWriter)
	Param(key string) string
	ParamInt(key string) (int, error)
	URLParam(key string) string
	URLParamInt(key string) (int, error)
	Get(key string) interface{}
	GetString(key string) (value string)
	GetInt(key string) (value int)
	Set(key string, value interface{})
	Write(format string, a ...interface{})
	ServeFile(path string)
	GetCookie(name string) string
	SetCookie(name string, value string)
	// Errors
	NotFound()
	Panic()
	EmitError(statusCode int)
	StopExecution()
	//
	Redirect(path string, statusHeader ...int) error
	SendStatus(statusCode int, message string)
	RequestIP() string
	Close()
	End()
	IsStopped() bool
	Clone() *Context ///todo IContext again
	RenderFile(file string, pageContext interface{}) error
	Render(pageContext interface{}) error
	//
	// WriteStatus writes http status code to the header
	WriteStatus(statusCode int)
	// SetContentType sets the "Content-Type" header, receives the values
	SetContentType(s []string)
	// SetHeader sets the response headers first parameter is the key, second is the values
	SetHeader(k string, s []string)
	//
	WriteHTML(httpStatus int, htmlContents string)
	HTML(htmlContents string)
	WriteData(httpStatus int, binaryData []byte)
	Data(binaryData []byte)
	WriteText(httpStatus int, text string)
	Text(text string)
	RenderJSON(httpStatus int, jsonStructs ...interface{}) error
	ReadJSON(jsonObject interface{}) error
	WriteJSON(httpStatus int, jsonObjectOrArray interface{}) error
	JSON(jsonObjectOrArray interface{}) error
	WriteXML(httpStatus int, xmlB []byte) error
	XML(xmlB []byte) error
	RenderXML(hhttpStatus int, xmlStructs ...interface{}) error
	ReadXML(xmlObject interface{}) error
	GetHandlerName() string
}

IContext is the domain-driven interface for the iris Context

type IContextCache

type IContextCache interface {
	OnTick()
	AddItem(method, url string, ctx *Context) // This is the faster method, just set&return just a *Context, I tried to return only params and middleware but it's add 10.000 nanoseconds, also +2k bytes of memory . So let's keep it as I did thee first time, I don't know what do do to make it's performance even better... It doesn't go much best, can't use channels because the performance will be get very low, locks are better for this purpose.
	GetItem(method, url string) *Context
	SetMaxItems(maxItems int)
}

IContextCache is the interface of the ContextCache & SyncContextCache

type IDictionary

type IDictionary interface {
	Get(key string) string
	Set(key string, value string)
	String() string
}

IDictionary is the interface which PathParameters using it's just a Get(key), Set(key,value) pair store

type IDownloadManager

type IDownloadManager interface {
	DirectoryExists(dir string) bool
	DownloadZip(zipURL string, targetDir string) (string, error)
	Unzip(archive string, target string) (string, error)
	Remove(filePath string) error
	// install is just the flow of: downloadZip -> unzip -> removeFile(zippedFile)
	// accepts 2 parameters
	//
	// first parameter is the remote url file zip
	// second parameter is the target directory
	// returns a string(installedDirectory) and an error
	//
	// (string) installedDirectory is the directory which the zip file had, this is the real installation path, you don't need to know what it's because these things maybe change to the future let's keep it to return the correct path.
	// the installedDirectory is not empty when the installation is succed, the targetDirectory is not already exists and no error happens
	// the installedDirectory is empty when the installation is already done by previous time or an error happens
	Install(remoteFileZip string, targetDirectory string) (string, error)
}

IDownloadManager is the interface which the DownloadManager should implements

type IErrorHandler

type IErrorHandler interface {
	GetCode() int
	GetHandler() HandlerFunc
	SetHandler(h HandlerFunc)
}

IErrorHandler is the interface which an http error handler should implement

type IHTTPErrors

type IHTTPErrors interface {
	GetByCode(httpStatus int) IErrorHandler
	On(httpStatus int, handler HandlerFunc)
	Emit(errCode int, ctx *Context)
}

IHTTPErrors is the interface which the HTTPErrors using

func Errors

func Errors() IHTTPErrors

Errors returns the object which is resposible for the error(s) handler(s)

type IMemoryRouter

type IMemoryRouter interface {
	IRouter

	ServeWithPath(string, http.ResponseWriter, *http.Request)
	// contains filtered or unexported methods
}

IMemoryRouter is the in-memory cached version of the Router

type IMemoryWriter

type IMemoryWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.CloseNotifier
	Reset(underlineRes http.ResponseWriter)
	WriteString(s string) (int, error)

	Size() int

	Status() int

	//
	IsWritten() bool

	ForceHeader()
}

IMemoryWriter is the interface which the MemoryWriter should implement, implements the http.ResponseWriter

type IMiddlewareSupporter

type IMiddlewareSupporter interface {
	Use(handlers ...Handler)
	UseFunc(handlersFn ...HandlerFunc)
}

IMiddlewareSupporter is an interface which all routers must implement

type IParty

type IParty interface {
	IMiddlewareSupporter
	Handle(method string, registedPath string, handlers ...Handler)
	HandleFunc(method string, registedPath string, handlersFn ...HandlerFunc)
	HandleAnnotated(irisHandler Handler) error
	Get(path string, handlersFn ...HandlerFunc)
	Post(path string, handlersFn ...HandlerFunc)
	Put(path string, handlersFn ...HandlerFunc)
	Delete(path string, handlersFn ...HandlerFunc)
	Connect(path string, handlersFn ...HandlerFunc)
	Head(path string, handlersFn ...HandlerFunc)
	Options(path string, handlersFn ...HandlerFunc)
	Patch(path string, handlersFn ...HandlerFunc)
	Trace(path string, handlersFn ...HandlerFunc)
	Any(path string, handlersFn ...HandlerFunc)
	Ws(path string, handler Handler)
	Party(path string) IParty // Each party can have a party too
	// contains filtered or unexported methods
}

IParty is the interface which implements the whole Party of routes

func NewParty

func NewParty(path string, station *Station, hoster *GardenParty) IParty

NewParty creates and return a new Party, it shouldn't used outside this package but capital because

func Party

func Party(rootPath string) IParty

Party is just a group joiner of routes which have the same prefix and share same middleware(s) also. Party can also be named as 'Join' or 'Node' or 'Group' , Party chosen because it has more fun

type IPlugin

type IPlugin interface {
	// GetName has to returns the name of the plugin, a name is unique
	// name has to be not dependent from other methods of the plugin,
	// because it is being called even before the Activate
	GetName() string
	// GetDescription has to returns the description of what the plugins is used for
	GetDescription() string

	// Activate called BEFORE the plugin being added to the plugins list,
	// if Activate returns none nil error then the plugin is not being added to the list
	// it is being called only one time
	//
	// PluginContainer parameter used to add other plugins if that's necessary by the plugin
	Activate(IPluginContainer) error
}

IPlugin is the interface which all Plugins must implement.

A Plugin can register other plugins also from it's Activate state

type IPluginContainer

type IPluginContainer interface {
	Plugin(plugin IPlugin) error
	RemovePlugin(pluginName string)
	GetByName(pluginName string) IPlugin
	Printf(format string, a ...interface{})
	DoPreHandle(route IRoute)
	DoPostHandle(route IRoute)
	DoPreListen(station *Station)
	DoPostListen(station *Station)
	DoPreClose(station *Station)
	DoPreDownload(pluginTryToDownload IPlugin, downloadURL string)
	GetAll() []IPlugin
	// GetDownloader is the only one module that is used and fire listeners at the same time in this file
	GetDownloader() IDownloadManager
}

IPluginContainer is the interface which the PluginContainer should implements

type IPluginPostHandle

type IPluginPostHandle interface {
	// PostHandle it's being called every time AFTER a Route successfully registed to the Router
	//
	// parameter is the Route
	PostHandle(IRoute)
}

IPluginPostHandle implements the PostHandle(IRoute) method

type IPluginPostListen

type IPluginPostListen interface {
	// PostListen it's being called only one time, AFTER the Server is started (if .Listen called)
	// parameter is the station
	PostListen(*Station)
}

IPluginPostListen implements the PostListen(*Station) method

type IPluginPreClose

type IPluginPreClose interface {
	// PreClose it's being called only one time, BEFORE the Iris .Close method
	// any plugin cleanup/clear memory happens here
	//
	// The plugin is deactivated after this state
	PreClose(*Station)
}

IPluginPreClose implements the PreClose(*Station) method

type IPluginPreDownload

type IPluginPreDownload interface {
	// PreDownload it's being called every time a plugin tries to download something
	//
	// first parameter is the plugin
	// second parameter is the download url
	// must return a boolean, if false then the plugin is not permmited to download this file
	PreDownload(plugin IPlugin, downloadURL string) // bool
}

IPluginPreDownload It's for the future, not being used, I need to create and return an ActivatedPlugin type which will have it's methods, and pass it on .Activate but now we return the whole pluginContainer, which I can't determinate which plugin tries to download something, so we will leave it here for the future.

type IPluginPreHandle

type IPluginPreHandle interface {
	// PreHandle it's being called every time BEFORE a Route is registed to the Router
	//
	//  parameter is the Route
	PreHandle(IRoute)
}

IPluginPreHandle implements the PreHandle(IRoute) method

type IPluginPreListen

type IPluginPreListen interface {
	// PreListen it's being called only one time, BEFORE the Server is started (if .Listen called)
	// is used to do work at the time all other things are ready to go
	//  parameter is the station
	PreListen(*Station)
}

IPluginPreListen implements the PreListen(*Station) method

type IRoute

type IRoute interface {
	GetMethod() string
	GetDomain() string
	GetPath() string
	GetPathPrefix() string
	ProcessPath()
	GetMiddleware() Middleware
	SetMiddleware(m Middleware)
}

IRoute is the interface which the Route should implements it useful to have it as an interface because this interface is passed to the plugins

type IRouter

type IRouter interface {
	IParty

	// Errors
	Errors() IHTTPErrors
	OnError(statusCode int, handlerFunc HandlerFunc)
	// EmitError emits an error with it's http status code and the iris Context passed to the function
	EmitError(statusCode int, ctx *Context)
	// OnNotFound sets the handler for http status 404,
	// default is a response with text: 'Not Found' and status: 404
	OnNotFound(handlerFunc HandlerFunc)
	// OnPanic sets the handler for http status 500,
	// default is a response with text: The server encountered an unexpected condition which prevented it from fulfilling the request. and status: 500
	OnPanic(handlerFunc HandlerFunc)
	//
	ServeHTTP(http.ResponseWriter, *http.Request)
	// contains filtered or unexported methods
}

IRouter is the interface of which any Iris router must implement

type IStation

type IStation interface {
	IRouter
	Serve() http.Handler
	Plugin(IPlugin) error
	GetPluginContainer() IPluginContainer
	GetTemplates() *template.Template
	//yes we need that again if no .Listen called and you use other server, you have to call .Build() before
	OptimusPrime()
	HasOptimized() bool
	GetLogger() *Logger
}

IStation is the interface which the Station should implements

type ITick

type ITick interface {
	OnTick()
}

ITick is the interface which all ticker's listeners must implement

type Logger

type Logger struct {
	*log.Logger
}

Logger is just a log.Logger

func NewLogger

func NewLogger(out io.Writer, prefix string, flag int) *Logger

NewLogger creates a new Logger. The out variable sets the destination to which log data will be written. The prefix appears at the beginning of each generated log line. The flag argument defines the logging properties.

type MemoryRouter

type MemoryRouter struct {
	*Router
	// contains filtered or unexported fields
}

MemoryRouter is the cached version of the Router

func NewMemoryRouter

func NewMemoryRouter(underlineRouter *Router, maxitems int, resetDuration time.Duration) *MemoryRouter

NewMemoryRouter returns a MemoryRouter receives an underline *Router object and int options like MaxItems and ResetDurationTime

func (*MemoryRouter) ServeHTTP

func (r *MemoryRouter) ServeHTTP(res http.ResponseWriter, req *http.Request)

ServeHTTP calls processRequest which finds and serves a route by it's request If no route found, it sends an http status 404 with a custom error middleware, if setted

func (*MemoryRouter) ServeWithPath

func (r *MemoryRouter) ServeWithPath(path string, res http.ResponseWriter, req *http.Request)

ServeWithPath serves a request The only use of this is to no dublicate this particular code inside the other 2 memory routers.

type MemoryRouterDomain

type MemoryRouterDomain struct {
	*MemoryRouter
}

MemoryRouterDomain is the MemoryRouter which is responsible and selected if and only if routes has at least one domain route

func NewMemoryRouterDomain

func NewMemoryRouterDomain(underlineRouter *MemoryRouter) *MemoryRouterDomain

NewMemoryRouterDomain creates a MemoryRouterDomain and returns it

func (*MemoryRouterDomain) ServeHTTP

func (r *MemoryRouterDomain) ServeHTTP(res http.ResponseWriter, req *http.Request)

type MemoryWriter

type MemoryWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

MemoryWriter is used inside Context instead of the http.ResponseWriter, used to have the maximum access and modification via middlewares to the ResponseWriter also offers faster produce of each request's response writer

func (*MemoryWriter) CloseNotify

func (m *MemoryWriter) CloseNotify() <-chan bool

CloseNotify look inside net/http package

func (*MemoryWriter) Flush

func (m *MemoryWriter) Flush()

Flush flushes the contents of the writer

func (*MemoryWriter) ForceHeader

func (m *MemoryWriter) ForceHeader()

ForceHeader forces to write the header and reset's the size of the ResponseWriter

func (*MemoryWriter) Hijack

func (m *MemoryWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack look inside net/http package

func (*MemoryWriter) IsWritten

func (m *MemoryWriter) IsWritten() bool

IsWritten returns true if we already wrote to the MemoryWriter

func (*MemoryWriter) Reset

func (m *MemoryWriter) Reset(underlineRes http.ResponseWriter)

Reset takes an underline http.ResponseWriter and resets the particular MemoryWriter with this underline http.ResponseWriter

func (*MemoryWriter) Size

func (m *MemoryWriter) Size() int

Size returns the size of the writer

func (*MemoryWriter) Status

func (m *MemoryWriter) Status() int

Status returns the http status code

func (*MemoryWriter) Write

func (m *MemoryWriter) Write(data []byte) (int, error)

func (*MemoryWriter) WriteHeader

func (m *MemoryWriter) WriteHeader(statusCode int)

WriteHeader writes an http status code

func (*MemoryWriter) WriteString

func (m *MemoryWriter) WriteString(s string) (size int, err error)

WriteString using io.WriteString to write a string

type Middleware

type Middleware []Handler

Middleware is just a slice of Handler []func(c *Context)

func JoinMiddleware

func JoinMiddleware(middleware1 Middleware, middleware2 Middleware) Middleware

JoinMiddleware uses to create a copy of all middleware and return them in order to use inside the node

type MiddlewareSupporter

type MiddlewareSupporter struct {
	Middleware Middleware
}

MiddlewareSupporter is the struch which make the Imiddlewaresupporter's works, is useful only to no repeat the code of middleware

func (*MiddlewareSupporter) Use

func (m *MiddlewareSupporter) Use(handlers ...Handler)

Use appends handler(s) to the route or to the router if it's called from router

func (*MiddlewareSupporter) UseFunc

func (m *MiddlewareSupporter) UseFunc(handlersFn ...HandlerFunc)

UseFunc is the same as Use but it receives HandlerFunc instead of iris.Handler as parameter(s) form of acceptable: func(c *iris.Context){//first middleware}, func(c *iris.Context){//second middleware}

type PathParameter

type PathParameter struct {
	Key   string
	Value string
}

PathParameter is a struct which contains Key and Value, used for named path parameters

type PathParameters

type PathParameters []PathParameter

PathParameters type for a slice of PathParameter Tt's a slice of PathParameter type, because it's faster than map

func ParseParams

func ParseParams(str string) PathParameters

ParseParams receives a string and returns PathParameters (slice of PathParameter) received string must have this form: key1=value1,key2=value2...

func (PathParameters) Get

func (params PathParameters) Get(key string) string

Get returns a value from a key inside this Parameters If no parameter with this key given then it returns an empty string

func (PathParameters) Set

func (params PathParameters) Set(key string, value string)

Set sets a PathParameter to the PathParameters , it's not used anywhere.

func (PathParameters) String

func (params PathParameters) String() string

String returns a string implementation of all parameters that this PathParameters object keeps hasthe form of key1=value1,key2=value2...

type PluginContainer

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

PluginContainer is the base container of all Iris, registed plugins

func (*PluginContainer) DoPostHandle

func (p *PluginContainer) DoPostHandle(route IRoute)

DoPostHandle raise all plugins which has the DoPostHandle method

func (*PluginContainer) DoPostListen

func (p *PluginContainer) DoPostListen(station *Station)

DoPostListen raise all plugins which has the DoPostListen method

func (*PluginContainer) DoPreClose

func (p *PluginContainer) DoPreClose(station *Station)

DoPreClose raise all plugins which has the DoPreClose method

func (*PluginContainer) DoPreDownload

func (p *PluginContainer) DoPreDownload(pluginTryToDownload IPlugin, downloadURL string)

DoPreDownload raise all plugins which has the DoPreDownload method

func (*PluginContainer) DoPreHandle

func (p *PluginContainer) DoPreHandle(route IRoute)

DoPreHandle raise all plugins which has the PreHandle method

func (*PluginContainer) DoPreListen

func (p *PluginContainer) DoPreListen(station *Station)

DoPreListen raise all plugins which has the DoPreListen method

func (*PluginContainer) GetAll

func (p *PluginContainer) GetAll() []IPlugin

GetAll returns all activated plugins

func (*PluginContainer) GetByName

func (p *PluginContainer) GetByName(pluginName string) IPlugin

GetByName returns a plugin instance by it's name

func (*PluginContainer) GetDownloader

func (p *PluginContainer) GetDownloader() IDownloadManager

GetDownloader returns the download manager

func (*PluginContainer) Plugin

func (p *PluginContainer) Plugin(plugin IPlugin) error

Plugin activates the plugins and if succeed then adds it to the activated plugins list

func (*PluginContainer) Printf

func (p *PluginContainer) Printf(format string, a ...interface{})

Printf sends plain text to any registed logger (future), some plugins maybe want use this method maybe at the future I change it, instead of sync even-driven to async channels...

func (*PluginContainer) RemovePlugin

func (p *PluginContainer) RemovePlugin(pluginName string)

RemovePlugin DOES NOT calls the plugin.PreClose method but it removes it completely from the plugins list

type Route

type Route struct {
	PathPrefix string
	// contains filtered or unexported fields
}

Route contains basic and temporary info about the route, it is nil after iris.Listen called contains all middleware and prepare them for execution Used to create a node at the Router's Build state

func NewRoute

func NewRoute(method string, registedPath string, middleware Middleware) *Route

NewRoute creates, from a path string, and a slice of HandlerFunc

func (Route) GetDomain

func (r Route) GetDomain() string

GetDomain returns the registed domain which this route is ( if none, is "" which is means "localhost"/127.0.0.1)

func (Route) GetMethod

func (r Route) GetMethod() string

GetMethod returns the http method

func (Route) GetMiddleware

func (r Route) GetMiddleware() Middleware

GetMiddleware returns the chain of the []HandlerFunc registed to this Route

func (Route) GetPath

func (r Route) GetPath() string

GetPath returns the full registed path

func (Route) GetPathPrefix

func (r Route) GetPathPrefix() string

GetPathPrefix returns the path prefix, this is the static part before any parameter or *any

func (*Route) ProcessPath

func (r *Route) ProcessPath()

ProcessPath modifies the path in order to set the path prefix of this Route

func (Route) SetMiddleware

func (r Route) SetMiddleware(m Middleware)

SetMiddleware sets the middleware(s)

type Router

type Router struct {
	IParty
	// contains filtered or unexported fields
}

Router is the router , one router per server. Router contains the global middleware, the routes and a Mutex for lock and unlock on route prepare

func NewRouter

func NewRouter(station *Station) *Router

NewRouter creates and returns an empty Router

func (*Router) EmitError

func (r *Router) EmitError(statusCode int, ctx *Context)

EmitError emits an error with it's http status code and the iris Context passed to the function

func (*Router) Errors

func (r *Router) Errors() IHTTPErrors

Errors returns the object which is resposible for the error(s) handler(s)

func (*Router) OnError

func (r *Router) OnError(statusCode int, handlerFunc HandlerFunc)

OnError registers a handler ( type of HandlerFunc) for a specific http error status

func (*Router) OnNotFound

func (r *Router) OnNotFound(handlerFunc HandlerFunc)

OnNotFound sets the handler for http status 404, default is a response with text: 'Not Found' and status: 404

func (*Router) OnPanic

func (r *Router) OnPanic(handlerFunc HandlerFunc)

OnPanic sets the handler for http status 500, default is a response with text: The server encountered an unexpected condition which prevented it from fulfilling the request. and status: 500

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request)

ServeHTTP finds and serves a route by it's request If no route found, it sends an http status 404

type RouterDomain

type RouterDomain struct {
	*Router
}

RouterDomain same as Router but it's override the ServeHTTP and proccessPath.

func NewRouterDomain

func NewRouterDomain(underlineRouter *Router) *RouterDomain

NewRouterDomain creates a RouterDomain from an underline (normal) Router and returns it

func (*RouterDomain) ServeHTTP

func (r *RouterDomain) ServeHTTP(res http.ResponseWriter, req *http.Request)

type RouterType

type RouterType uint8

RouterType is just the type which the Router uses to indentify what type is (Normal,Memory,MemorySync,Domain,DomainMemory )

const (
	// Normal is the Router
	Normal RouterType = iota
	// Memory is the MemoryRouter , used when cache is enabled
	Memory // this is the MemoryRouter
	// MemorySync is the SyncMemoryRouter which is used when cache is enabled and cores > 1
	MemorySync // this is the SyncMemoryRouter
	// Domain is the RouterDomain, used when at least one route has domains
	Domain
	// DomainMemory is the MemoryDomainRouter, used when Domain is used and cache is enabled
	DomainMemory // this is the MemoryDomainRouter
)

type Server

type Server struct {
	IsRunning     bool
	ListeningAddr string
	// IsSecure true if ListenTLS (https/http2)
	IsSecure          bool
	CertFile, KeyFile string
	// contains filtered or unexported fields
}

Server is the container of the tcp listener used to start an http server,

it holds it's router and it's config, also a property named isRunning which can be used to see if the server is already running or not.

Server's New() located at the iris.go file

type Station

type Station struct {
	IRouter
	Server *Server
	// contains filtered or unexported fields
}

Station is the container of all, server, router, cache and the sync.Pool

var (
	DefaultStation *Station
)

iris.go exposes the default global (iris.) public API from the New() default station

func Custom

func Custom(options StationOptions) *Station

Custom is used for iris-experienced developers creates and returns a new iris Station with custom StationOptions

func New

func New() *Station

New creates and returns a new iris Station with recommented options

func (*Station) Close

func (s *Station) Close()

Close is used to close the tcp listener from the server

func (*Station) GetLogger

func (s *Station) GetLogger() *Logger

GetLogger returns ( or creates if not exists already) the logger

func (Station) GetPluginContainer

func (s Station) GetPluginContainer() IPluginContainer

GetPluginContainer returns the pluginContainer

func (Station) GetTemplates

func (s Station) GetTemplates() *template.Template

GetTemplates returns the *template.Template registed to this station, if any

func (*Station) HasOptimized

func (s *Station) HasOptimized() bool

HasOptimized returns if the station has optimized ( OptimusPrime run once)

func (*Station) Listen

func (s *Station) Listen(fullHostOrPort ...string) error

Listen starts the standalone http server which listens to the fullHostOrPort parameter which as the form of host:port or just port

func (*Station) ListenTLS

func (s *Station) ListenTLS(fullAddress string, certFile, keyFile string) error

ListenTLS Starts a httpS/http2 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 fullHostOrPort parameter which as the form of host:port or just port

func (*Station) OptimusPrime

func (s *Station) OptimusPrime()

OptimusPrime make the best last optimizations to make iris the faster framework out there This function is called automatically on .Listen, but if you don't use .Listen or .Serve, then YOU MUST CALL .OptimusPrime before run a server

func (*Station) Plugin

func (s *Station) Plugin(plugin IPlugin) error

Plugin activates the plugins and if succeed then adds it to the activated plugins list

func (*Station) Serve

func (s *Station) Serve() http.Handler

Serve is used instead of the iris.Listen eg http.ListenAndServe(":80",iris.Serve()) if you don't want to use iris.Listen(":80")

func (*Station) Templates

func (s *Station) Templates(pathGlob string)

Templates sets the templates glob path for the web app

type StationOptions

type StationOptions struct {
	// Profile set to true to enable web pprof (debug profiling)
	// Default is false, enabling makes available these 7 routes:
	// /debug/pprof/cmdline
	// /debug/pprof/profile
	// /debug/pprof/symbol
	// /debug/pprof/goroutine
	// /debug/pprof/heap
	// /debug/pprof/threadcreate
	// /debug/pprof/pprof/block
	Profile bool

	// ProfilePath change it if you want other url path than the default
	// Default is /debug/pprof , which means yourhost.com/debug/pprof
	ProfilePath string

	// Cache for Router, change it to false if you don't want to use the cache mechanism that Iris provides for your routes
	Cache bool
	// CacheMaxItems max number of total cached routes, 500 = +~20000 bytes = ~0.019073MB
	// Every time the cache timer reach this number it will reset/clean itself
	// Default is 0
	// If <=0 then cache cleans all of items (bag)
	// Auto cache clean is happening after 5 minutes the last request serve, you can change this number by 'ResetDuration' property
	// Note that MaxItems doesn't means that the items never reach this lengh, only on timer tick this number is checked/consider.
	CacheMaxItems int
	// CacheResetDuration change this time.value to determinate how much duration after last request serving the cache must be reseted/cleaned
	// Default is 5 * time.Minute , Minimum is 30 seconds
	//
	// If CacheMaxItems <= 0 then it clears the whole cache bag at this duration.
	CacheResetDuration time.Duration

	// PathCorrection 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, redirects the client to the correct path /home
	// and VICE - VERSA if /home/ is registed but /home is requested then it redirects to /home/
	//
	// Default is true
	PathCorrection bool
}

StationOptions is the struct which contains all Iris' settings/options

type SyncContextCache

type SyncContextCache struct {
	*ContextCache
	// contains filtered or unexported fields
}

SyncContextCache is the cache version of routine-thread-safe ContextCache

func NewSyncContextCache

func NewSyncContextCache(underlineCache *ContextCache) *SyncContextCache

NewSyncContextCache returns the cache for a router, it's based on the one-thread ContextCache

func (*SyncContextCache) AddItem

func (mc *SyncContextCache) AddItem(method, url string, ctx *Context)

AddItem adds an item to the bag/cache, is a goroutine.

func (*SyncContextCache) GetItem

func (mc *SyncContextCache) GetItem(method, url string) *Context

GetItem returns an item from the bag/cache, if not exists it returns just nil.

func (*SyncContextCache) OnTick

func (mc *SyncContextCache) OnTick()

OnTick is the implementation of the ITick it makes the ContextCache a ticker's listener

type SyncMemoryRouter

type SyncMemoryRouter struct {
	IMemoryRouter
	// contains filtered or unexported fields
}

SyncMemoryRouter is the Router which is routine-thread-safe version of MemoryRouter, used only and only if running cores are > 1

func NewSyncRouter

func NewSyncRouter(underlineRouter IMemoryRouter) *SyncMemoryRouter

NewSyncRouter creates and returns a new SyncRouter object, from an underline IMemoryRouter

func (*SyncMemoryRouter) ServeHTTP

func (r *SyncMemoryRouter) ServeHTTP(res http.ResponseWriter, req *http.Request)

type Ticker

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

Ticker is the timer which is used in cache

func NewTicker

func NewTicker() *Ticker

NewTicker returns a new Ticker

func (*Ticker) OnTick

func (c *Ticker) OnTick(h func())

OnTick add event handlers/ callbacks which are called on each timer's tick

func (*Ticker) Start

func (c *Ticker) Start(duration time.Duration)

Start starts the timer and execute all listener's when tick

func (*Ticker) Stop

func (c *Ticker) Stop()

Stop stops the ticker

Directories

Path Synopsis
middleware
cors
Cors credits goes to @keuller
Cors credits goes to @keuller
plugin
Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455.
Package websocket implements a client and server for the WebSocket protocol as specified in RFC 6455.

Jump to

Keyboard shortcuts

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