iris

package module
v3.0.0-beta+incompatible Latest Latest
Warning

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

Go to latest
Published: May 30, 2016 License: Apache-2.0 Imports: 35 Imported by: 0

README

Iris Logo

Travis Widget Release Widget Report Widget License Widget Gitter Widget Documentation Widget

Benchmark Wizzard Processing Time Horizontal Graph

$ cat main.go
package main

import  "github.com/kataras/iris"

func main() {
	iris.Get("/hi_json", func(c *iris.Context) {
		c.JSON(200, iris.Map{
			"Name": "Iris",
			"Age":  2,
		})
	})
	iris.Listen(":8080")
}

Learn about configuration and render.

Installation

The only requirement is Go 1.6

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

If you are connected to the Internet through China click here

Features

  • Focus on high performance
  • Robust routing & subdomains
  • View system supporting 5+ template engines
  • Highly scalable Websocket API with custom events
  • Sessions support with GC, memory & redis providers
  • Middlewares & Plugins were never be easier
  • Full REST API
  • Custom HTTP Errors
  • Typescript compiler + Browser editor
  • Content negotiation & streaming
  • Transport Layer Security

Docs & Community

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

  • Post an issue or idea here
  • Chat with us

Open debates

TIP Be sure to read the history for Migrating from 2.x to 3.x.

Philosophy

The Iris philosophy is to provide robust tooling for HTTP, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs.

Iris does not force you to use any specific ORM or template engine. With support for the most used template engines, you can quickly craft the perfect application.

Benchmarks

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

Benchmark Wizzard Processing Time Horizontal Graph

Please click here to view all detailed benchmarks.

Testing

Iris suggests you to use this new suite to test your API. Httpexpect supports fasthttp & Iris after recommandation. Its author is very active so I believe its a promising library. You can view examples here and here.

Versioning

Current: v3.0.0-beta

Iris is an active project

Read more about Semantic Versioning 2.0.0

Todo

for the next release 'v3'

  • Create server & client side (js) library for .on('event', func action(...)) / .emit('event')... (like socket.io but supports only websocket).
  • Find and provide support for the most stable template engine and be able to change it via the configuration, keep html/templates support.
  • Extend, test and publish to the public the Iris' cmd.

If you're willing to donate click here

People

The author of Iris is @kataras

License

This project is licensed under the Apache License 2.0.

License can be found here.

Documentation

Overview

Package iris v3.0.0-beta

Note: When 'Station', we mean the Iris type.

Index

Constants

View Source
const (
	// DefaultUserAgent default to 'iris' but it is not used anywhere yet
	DefaultUserAgent = "iris"
	// 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"
	// ContentBINARY is the string of application/octet-stream response headers
	ContentBINARY = "application/octet-stream"

	// LastModified "Last-Modified"
	LastModified = "Last-Modified"
	// IfModifiedSince "If-Modified-Since"
	IfModifiedSince = "If-Modified-Since"
	// ContentDisposition "Content-Disposition"
	ContentDisposition = "Content-Disposition"

	// TimeFormat default time format for any kind of datetime parsing
	TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
)
View Source
const (
	StatusContinue           = 100
	StatusSwitchingProtocols = 101

	StatusOK                   = 200
	StatusCreated              = 201
	StatusAccepted             = 202
	StatusNonAuthoritativeInfo = 203
	StatusNoContent            = 204
	StatusResetContent         = 205
	StatusPartialContent       = 206

	StatusMultipleChoices   = 300
	StatusMovedPermanently  = 301
	StatusFound             = 302
	StatusSeeOther          = 303
	StatusNotModified       = 304
	StatusUseProxy          = 305
	StatusTemporaryRedirect = 307

	StatusBadRequest                   = 400
	StatusUnauthorized                 = 401
	StatusPaymentRequired              = 402
	StatusForbidden                    = 403
	StatusNotFound                     = 404
	StatusMethodNotAllowed             = 405
	StatusNotAcceptable                = 406
	StatusProxyAuthRequired            = 407
	StatusRequestTimeout               = 408
	StatusConflict                     = 409
	StatusGone                         = 410
	StatusLengthRequired               = 411
	StatusPreconditionFailed           = 412
	StatusRequestEntityTooLarge        = 413
	StatusRequestURITooLong            = 414
	StatusUnsupportedMediaType         = 415
	StatusRequestedRangeNotSatisfiable = 416
	StatusExpectationFailed            = 417
	StatusTeapot                       = 418
	StatusPreconditionRequired         = 428
	StatusTooManyRequests              = 429
	StatusRequestHeaderFieldsTooLarge  = 431
	StatusUnavailableForLegalReasons   = 451

	StatusInternalServerError           = 500
	StatusNotImplemented                = 501
	StatusBadGateway                    = 502
	StatusServiceUnavailable            = 503
	StatusGatewayTimeout                = 504
	StatusHTTPVersionNotSupported       = 505
	StatusNetworkAuthenticationRequired = 511
)

taken from net/http

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('*')

	// MethodGet "GET"
	MethodGet = "GET"
	// MethodPost "POST"
	MethodPost = "POST"
	// MethodPut "PUT"
	MethodPut = "PUT"
	// MethodDelete "DELETE"
	MethodDelete = "DELETE"
	// MethodConnect "CONNECT"
	MethodConnect = "CONNECT"
	// MethodHead "HEAD"
	MethodHead = "HEAD"
	// MethodPatch "PATCH"
	MethodPatch = "PATCH"
	// MethodOptions "OPTIONS"
	MethodOptions = "OPTIONS"
	// MethodTrace "TRACE"
	MethodTrace = "TRACE"
)
View Source
const (
	Version = "v3.0.0-beta"
)

Variables

View Source
var (

	// ErrHandler returns na error with message: 'Passed argument is not func(*Context) neither an object which implements the iris.Handler with Serve(ctx *Context)
	// It seems to be a  +type Points to: +pointer.'
	ErrHandler = errors.New("Passed argument is not func(*Context) neither an object which implements the iris.Handler with Serve(ctx *Context)\n It seems to be a  %T Points to: %v.")
	// ErrHandleAnnotated returns an error with message: 'HandleAnnotated parse: +specific error(s)'
	ErrHandleAnnotated           = errors.New("HandleAnnotated parse: %s")
	ErrControllerContextNotFound = errors.New("Context *iris.Context could not be found, the Controller won't be registed.")
	ErrDirectoryFileNotFound     = errors.New("Directory or file %s couldn't found. Trace: %s")

	// ErrPluginAlreadyExists returns an error with message: 'Cannot activate the same plugin again, plugin '+plugin name[+plugin description]' is already exists'
	ErrPluginAlreadyExists = errors.New("Cannot use the same plugin again, '%s[%s]' is already exists")
	// ErrPluginActivate returns an error with message: 'While trying to activate plugin '+plugin name'. Trace: +specific error'
	ErrPluginActivate = errors.New("While trying to activate plugin '%s'. Trace: %s")
	// ErrPluginRemoveNoPlugins returns an error with message: 'No plugins are registed yet, you cannot remove a plugin from an empty list!'
	ErrPluginRemoveNoPlugins = errors.New("No plugins are registed yet, you cannot remove a plugin from an empty list!")
	// ErrPluginRemoveEmptyName returns an error with message: 'Plugin with an empty name cannot be removed'
	ErrPluginRemoveEmptyName = errors.New("Plugin with an empty name cannot be removed")
	// ErrPluginRemoveNotFound returns an error with message: 'Cannot remove a plugin which doesn't exists'
	ErrPluginRemoveNotFound = errors.New("Cannot remove a plugin which doesn't exists")

	// ErrServeContent returns an error with message: 'While trying to serve content to the client. Trace +specific error'
	ErrServeContent = errors.New("While trying to serve content to the client. Trace %s")

	// ErrTemplateExecute returns an error with message:'Unable to execute a template. Trace: +specific error'
	ErrTemplateExecute = errors.New("Unable to execute a template. Trace: %s")

	// ErrFlashNotFound returns an error with message: 'Unable to get flash message. Trace: Cookie does not exists'
	ErrFlashNotFound = errors.New("Unable to get flash message. Trace: Cookie does not exists")
	// ErrSessionNil returns an error with message: 'Unable to set session, Config().Session.Provider is nil, please refer to the docs!'
	ErrSessionNil = errors.New("Unable to set session, Config().Session.Provider is nil, please refer to the docs!")
)
View Source
var (
	HTMLEngine     = config.HTMLEngine
	PongoEngine    = config.PongoEngine
	MarkdownEngine = config.MarkdownEngine
	JadeEngine     = config.JadeEngine
	AmberEngine    = config.AmberEngine

	DefaultEngine = config.DefaultEngine
	NoEngine      = config.NoEngine

	NoLayout = config.NoLayout
)
View Source
var (

	// MethodConnectBytes []byte("CONNECT")
	MethodConnectBytes = []byte(MethodConnect)
	// AllMethods "GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", "PATCH", "OPTIONS", "TRACE"
	AllMethods = [...]string{"GET", "POST", "PUT", "DELETE", "CONNECT", "HEAD", "PATCH", "OPTIONS", "TRACE"}
)

Functions

func API

func API(registedPath string, controller HandlerAPI, middlewares ...HandlerFunc) error

API converts & registers a custom struct to the router receives three parameters first is the request path (string) second is the custom struct (interface{}) which can be anything that has a *iris.Context as field third are the common middlewares, is optional parameter

Recommend to use when you retrieve data from an external database, and the router-performance is not the (only) thing which slows the server's overall performance.

This is a slow method, if you care about router-performance use the Handle/HandleFunc/Get/Post/Put/Delete/Trace/Options... instead

Usage: All the below methods are optional except the *iris.Context field, example with /users :

package main

import (

"github.com/kataras/iris"

)

type UserAPI struct {
	*iris.Context
}

// GET /users

func (u UserAPI) Get() {
	u.Write("Get from /users")
	// u.JSON(iris.StatusOK,myDb.AllUsers())
}

// GET /:param1 which its value passed to the id argument func (u UserAPI) GetBy(id string) { // id equals to u.Param("param1")

u.Write("Get from /users/%s", id)
// u.JSON(iris.StatusOK, myDb.GetUserById(id))

}

// PUT /users

func (u UserAPI) Put() {
	name := u.FormValue("name")
	// myDb.InsertUser(...)
	println(string(name))
	println("Put from /users")
}

// POST /users/:param1

func (u UserAPI) PostBy(id string) {
	name := u.FormValue("name") // you can still use the whole Context's features!
	// myDb.UpdateUser(...)
	println(string(name))
	println("Post from /users/" + id)
}

// DELETE /users/:param1

func (u UserAPI) DeleteBy(id string) {
	// myDb.DeleteUser(id)
	println("Delete from /" + id)
}
func main() {
	iris.API("/users", UserAPI{})
	iris.Listen(":80")
}

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 Config

func Config() *config.Iris

Config returns the configs

func Connect

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

Connect registers a route for the Connect http method

func Delete

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

Delete registers a route for the Delete http method

func EmitError

func EmitError(httpStatus int, ctx *Context)

EmitError executes the handler of the given error http status code

func Favicon

func Favicon(favPath string, requestPath ...string) error

Favicon serves static favicon accepts 2 parameters, second is optionally favPath (string), declare the system directory path of the __.ico requestPath (string), it's the route's path, by default this is the "/favicon.ico" because some browsers tries to get this by default first, you can declare your own path if you have more than one favicon (desktop, mobile and so on)

this func will add a route for you which will static serve the /yuorpath/yourfile.ico to the /yourfile.ico (nothing special that you can't handle by yourself) Note that you have to call it on every favicon you have to serve automatically (dekstop, mobile and so on)

returns an error if something goes bad

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 if empty method is passed then registers handler(s) for all methods, same as .Any

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) {}

HandleAnnotated will be deprecated until the final v3 !

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(addr string)

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

It panics on error if you need a func to return an error use the ListenWithErr ex: iris.Listen(":8080")

func ListenTLS

func ListenTLS(addr string, certFile, keyFile string)

ListenTLS Starts a https server with certificates, if you use this method the requests of the form of 'http://' will fail only https:// connections are allowed which listens to the addr parameter which as the form of host:port or just port

It panics on error if you need a func to return an error use the ListenTLSWithErr ex: iris.ListenTLS(":8080","yourfile.cert","yourfile.key")

func ListenTLSWithErr

func ListenTLSWithErr(addr string, certFile, keyFile string) error

ListenTLSWithErr Starts a https server with certificates, if you use this method the requests of the form of 'http://' will fail only https:// connections are allowed which listens to the addr parameter which as the form of host:port or just port

It returns an error you are responsible how to handle this if you need a func to panic on error use the ListenTLS ex: log.Fatal(iris.ListenTLSWithErr(":8080","yourfile.cert","yourfile.key"))

func ListenWithErr

func ListenWithErr(addr string) error

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

It returns an error you are responsible how to handle this if you need a func to panic on error use the Listen ex: log.Fatal(iris.ListenWithErr(":8080"))

func Logger

func Logger() *logger.Logger

Logger returns the logger

func OnError

func OnError(httpStatus int, handler HandlerFunc)

OnError Registers a handler for a specific http error status

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 Options

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

Options registers a route for the Options http method

func Patch

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

Patch registers a route for the Patch http method

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 Rest

func Rest() *rest.Render

Rest returns the rest render

func RouteConflicts

func RouteConflicts(r *Route, with string) bool

RouteConflicts checks for route's middleware conflicts

func Server

func Server() *server.Server

Server returns the server

func Static

func Static(reqPath string, systemPath string, stripSlashes int)

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

func StaticContent

func StaticContent(reqPath string, contentType string, content []byte)

StaticContent serves bytes, memory cached, on the reqPath

func StaticFS

func StaticFS(reqPath string, systemPath string, stripSlashes int)

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

func StaticServe

func StaticServe(systemPath string, requestPath ...string)

StaticServe serves a directory as web resource it's the simpliest form of the Static* functions Almost same usage as StaticWeb accepts only one required parameter which is the systemPath ( the same path will be used to register the GET&HEAD routes) if second parameter is empty, otherwise the requestPath is the second parameter it uses gzip compression (compression on each request, no file cache)

func StaticWeb

func StaticWeb(reqPath string, systemPath string, stripSlashes int)

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

func StatusText

func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

func Templates

func Templates() *template.Template

Templates returns the template render

func Trace

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

Trace registers a route for the Trace http methodd

func URLEncode

func URLEncode(path string) string
Credits to Manish Singh @kryptodev for URLEncode

URLEncode returns the path encoded as url useful when you want to pass something to a database and be valid to retrieve it via context.Param use it only for special cases, when the default behavior doesn't suits you.

http://www.blooberry.com/indexdot/html/topics/urlencoding.htm

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 Websocket

func Websocket() websocket.Server

Websocket returns the websocket server

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 {
	*fasthttp.RequestCtx
	Params PathParameters
	// contains filtered or unexported fields
}

Context is resetting every time a request is coming to the server it is not good practice to use this object in goroutines, for these cases use the .Clone()

func (*Context) Clone

func (ctx *Context) Clone() context.IContext

Clone use that method if you want to use the context inside a goroutine

func (*Context) Data

func (ctx *Context) Data(status int, v []byte) error

Data writes out the raw bytes as binary data.

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) Err

func (ctx *Context) Err() error

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

func (*Context) ExecuteTemplate

func (ctx *Context) ExecuteTemplate(tmpl *template.Template, pageContext interface{}) error

ExecuteTemplate executes a simple html template, you can use that if you already have the cached templates the recommended way to render is to use iris.Templates("./templates/path/*.html") and ctx.RenderFile("filename.html",struct{}) accepts 2 parameters the first parameter is the template (*template.Template) the second parameter is the page context (interfac{}) returns an error if any errors occurs while executing this template

func (*Context) Get

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

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

func (*Context) GetCookie

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

GetCookie returns cookie's value by it's name returns empty string if nothing was found

func (*Context) GetFlash

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

GetFlash get a flash message by it's key after this action the messages is removed returns string, if the cookie doesn't exists the string is empty

func (*Context) GetFlashBytes

func (ctx *Context) GetFlashBytes(key string) (value []byte, err error)

GetFlashBytes get a flash message by it's key after this action the messages is removed returns []byte along with an error if the cookie doesn't exists or decode fails

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) int

GetInt same as Get but returns the value as int if nothing founds returns -1

func (*Context) GetRequestCtx

func (ctx *Context) GetRequestCtx() *fasthttp.RequestCtx

GetRequestCtx returns the current fasthttp context

func (*Context) GetString

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

GetString same as Get but returns the value as string if nothing founds returns empty string ""

func (*Context) HTML

func (ctx *Context) HTML(status int, name string, binding interface{}, layout ...string) error

HTML builds up the response from the specified template and bindings. Note: parameter layout has meaning only when using the iris.HTMLTemplate

func (*Context) HostString

func (ctx *Context) HostString() string

HostString returns the Host of the request( the url as string )

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(status int, v interface{}) error

JSON marshals the given interface object and writes the JSON response.

func (*Context) JSONP

func (ctx *Context) JSONP(status int, callback string, v interface{}) error

JSONP marshals the given interface object and writes the JSON response.

func (*Context) Markdown

func (ctx *Context) Markdown(status int, markdown string)

Markdown parses and renders to the client a particular (dynamic) markdown string accepts two parameters first is the http status code second is the markdown string

func (*Context) MarkdownString

func (ctx *Context) MarkdownString(markdown string) string

MarkdownString parses the (dynamic) markdown string and returns the converted html string

func (*Context) MethodString

func (ctx *Context) MethodString() string

MethodString returns the HTTP Method

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) PathString

func (ctx *Context) PathString() string

PathString returns the full path as string

func (*Context) PostFormValue

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

PostFormValue returns a single value from post request's data

func (*Context) ReadForm

func (ctx *Context) ReadForm(formObject interface{}) error

ReadForm binds the formObject with the form data it supports any kind of struct

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)

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) 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) RemoveCookie

func (ctx *Context) RemoveCookie(name string)

RemoveCookie deletes a cookie by it's name/key

func (*Context) Render

func (ctx *Context) Render(name string, binding interface{}, layout ...string) error

Render same as .HTML but with status to iris.StatusOK (200)

func (*Context) RenderString

func (ctx *Context) RenderString(name string, binding interface{}, layout ...string) (result string, err error)

Render accepts a template filename, its context data and returns the result of the parsed template (string)

func (*Context) RequestHeader

func (ctx *Context) RequestHeader(k string) string

RequestHeader returns the request header's value accepts one parameter, the key of the header (string) returns string

func (*Context) RequestIP

func (ctx *Context) RequestIP() string

RequestIP gets just the Remote Address from the client.

func (*Context) Reset

func (ctx *Context) Reset(reqCtx *fasthttp.RequestCtx)

Reset resets the Context with a given domain.Response and domain.Request the context is ready-to-use after that, just like a new Context I use it for zero rellocation memory

func (*Context) SendFile

func (ctx *Context) SendFile(filename string, destinationName string) error

SendFile sends file for force-download to the client

You can define your own "Content-Type" header also, after this function call for example: ctx.Response.Header.Set("Content-Type","thecontent/type")

func (*Context) ServeContent

func (ctx *Context) ServeContent(content io.ReadSeeker, filename string, modtime time.Time, gzipCompression bool) (err error)

ServeContent serves content, headers are autoset receives three parameters, it's low-level function, instead you can use .ServeFile(string)

You can define your own "Content-Type" header also, after this function call

func (*Context) ServeFile

func (ctx *Context) ServeFile(filename string, gzipCompression bool) error

ServeFile serves a view file, to send a file ( zip for example) to the client you should use the SendFile(serverfilename,clientfilename) receives two parameters filename/path (string) gzipCompression (bool)

You can define your own "Content-Type" header also, after this function call

func (*Context) Session

func (ctx *Context) Session() store.IStore

Sessionreturns the current session store, returns nil if provider is ""

func (*Context) SessionDestroy

func (ctx *Context) SessionDestroy()

SessionDestroy destroys the whole session, calls the provider's destory and remove the cookie

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(cookie *fasthttp.Cookie)

SetCookie adds a cookie

func (*Context) SetCookieKV

func (ctx *Context) SetCookieKV(key, value string)

SetCookieKV adds a cookie, receives just a key(string) and a value(string)

func (*Context) SetFlash

func (ctx *Context) SetFlash(key string, value string)

SetFlash sets a flash message, accepts 2 parameters the key(string) and the value(string)

func (*Context) SetFlashBytes

func (ctx *Context) SetFlashBytes(key string, value []byte)

SetFlashBytes sets a flash message, accepts 2 parameters the key(string) and the value([]byte)

func (*Context) SetHeader

func (ctx *Context) SetHeader(k string, v string)

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

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) Stream

func (ctx *Context) Stream(cb func(writer *bufio.Writer))

Stream same as StreamWriter

func (*Context) StreamReader

func (ctx *Context) StreamReader(bodyStream io.Reader, bodySize int)

StreamReader sets response body stream and, optionally body size.

If bodySize is >= 0, then the bodyStream must provide exactly bodySize bytes before returning io.EOF.

If bodySize < 0, then bodyStream is read until io.EOF.

bodyStream.Close() is called after finishing reading all body data if it implements io.Closer.

See also StreamReader.

func (*Context) StreamWriter

func (ctx *Context) StreamWriter(cb func(writer *bufio.Writer))

StreamWriter registers the given stream writer for populating response body.

This function may be used in the following cases:

  • if response body is too big (more than 10MB).
  • if response body is streamed from slow external sources.
  • if response body must be streamed to the client in chunks. (aka `http server push`).

func (*Context) Text

func (ctx *Context) Text(status int, v string) error

Text writes out a string as plain text.

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) URLParams

func (ctx *Context) URLParams() map[string]string

URLParams returns a map of a list of each url(query) parameter

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) WriteHTML

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

WriteHTML writes html string with a http status

func (*Context) XML

func (ctx *Context) XML(status int, v interface{}) error

XML marshals the given interface object and writes the XML response.

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 Garden

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

Garden is the main area which routes are planted/placed

func (*Garden) Plant

func (g *Garden) Plant(station *Iris, _route IRoute)

Plant plants/adds a route to the garden

type GardenParty

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

GardenParty is the struct which makes all the job for registering routes and middlewares

func (*GardenParty) API

func (p *GardenParty) API(path string, controller HandlerAPI, middlewares ...HandlerFunc) error

API converts & registers a custom struct to the router receives two parameters first is the request path (string) second is the custom struct (interface{}) which can be anything that has a *iris.Context as field. third are the common middlewares, is optional parameter

Recommend to use when you retrieve data from an external database, and the router-performance is not the (only) thing which slows the server's overall performance.

This is a slow method, if you care about router-performance use the Handle/HandleFunc/Get/Post/Put/Delete/Trace/Options... instead

Usage: All the below methods are optional except the *iris.Context field, example with /users :

package main

import (

"github.com/kataras/iris"

)

type UserAPI struct {
	*iris.Context
}

// GET /users

func (u UserAPI) Get() {
	u.Write("Get from /users")
	// u.JSON(iris.StatusOK,myDb.AllUsers())
}

// GET /:param1 which its value passed to the id argument func (u UserAPI) GetBy(id string) { // id equals to u.Param("param1")

u.Write("Get from /users/%s", id)
// u.JSON(iris.StatusOK, myDb.GetUserById(id))

}

// PUT /users

func (u UserAPI) Put() {
	name := u.FormValue("name")
	// myDb.InsertUser(...)
	println(string(name))
	println("Put from /users")
}

// POST /users/:param1

func (u UserAPI) PostBy(id string) {
	name := u.FormValue("name") // you can still use the whole Context's features!
	// myDb.UpdateUser(...)
	println(string(name))
	println("Post from /users/" + id)
}

// DELETE /users/:param1

func (u UserAPI) DeleteBy(id string) {
	// myDb.DeleteUser(id)
	println("Delete from /" + id)
}
func main() {
	iris.API("/users", UserAPI{})
	iris.Listen(":80")
}

func (*GardenParty) Any

func (p *GardenParty) Any(registedPath 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) Favicon

func (p *GardenParty) Favicon(favPath string, requestPath ...string) error

Favicon serves static favicon accepts 2 parameters, second is optionally favPath (string), declare the system directory path of the __.ico requestPath (string), it's the route's path, by default this is the "/favicon.ico" because some browsers tries to get this by default first, you can declare your own path if you have more than one favicon (desktop, mobile and so on)

this func will add a route for you which will static serve the /yuorpath/yourfile.ico to the /yourfile.ico (nothing special that you can't handle by yourself) Note that you have to call it on every favicon you have to serve automatically (dekstop, mobile and so on)

returns an error if something goes bad

func (*GardenParty) Get

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

Get registers a route for the Get http method

func (*GardenParty) H_

func (p *GardenParty) H_(method string, registedPath string, fn func(context.IContext))

H_ is used to convert a context.IContext handler func to iris.HandlerFunc, is used only inside iris internal package to avoid import cycles

func (*GardenParty) Handle

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

Handle registers a route to the server's router if empty method is passed then registers handler(s) for all methods, same as .Any

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) IsRoot

func (p *GardenParty) IsRoot() bool

IsRoot returns true if this is the root party ("/")

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, handlersFn ...HandlerFunc) 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) Static

func (p *GardenParty) Static(relative string, systemPath string, stripSlashes int)

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

func (*GardenParty) StaticContent

func (p *GardenParty) StaticContent(reqPath string, contentType string, content []byte)

StaticContent serves bytes, memory cached, on the reqPath

func (*GardenParty) StaticFS

func (p *GardenParty) StaticFS(reqPath string, systemPath string, stripSlashes int)

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

func (*GardenParty) StaticHandlerFunc

func (p *GardenParty) StaticHandlerFunc(systemPath string, stripSlashes int, compress bool, generateIndexPages bool, indexNames []string) HandlerFunc

StaticHandlerFunc returns a HandlerFunc to serve static system directory Accepts 5 parameters

first is the systemPath (string) Path to the root directory to serve files from.

second is the stripSlashes (int) level * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: ""

third is the compress (bool) Transparently compresses responses if set to true.

The server tries minimizing CPU usage by caching compressed files. It adds fasthttp.FSCompressedFileSuffix suffix to the original file name and tries saving the resulting compressed file under the new file name. So it is advisable to give the server write access to Root and to all inner folders in order to minimze CPU usage when serving compressed responses.

fourth is the generateIndexPages (bool) Index pages for directories without files matching IndexNames are automatically generated if set.

Directory index generation may be quite slow for directories with many files (more than 1K), so it is discouraged enabling index pages' generation for such directories.

fifth is the indexNames ([]string) List of index file names to try opening during directory access.

For example:

  • index.html
  • index.htm
  • my-super-index.xml

func (*GardenParty) StaticServe

func (p *GardenParty) StaticServe(systemPath string, requestPath ...string)

StaticServe serves a directory as web resource it's the simpliest form of the Static* functions Almost same usage as StaticWeb accepts only one required parameter which is the systemPath ( the same path will be used to register the GET&HEAD routes) if second parameter is empty, otherwise the requestPath is the second parameter it uses gzip compression (compression on each request, no file cache)

func (*GardenParty) StaticWeb

func (p *GardenParty) StaticWeb(reqPath string, systemPath string, stripSlashes int)

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 registers a Handler middleware

func (*GardenParty) UseFunc

func (p *GardenParty) UseFunc(handlersFn ...HandlerFunc)

UseFunc registers a HandlerFunc middleware

type HTTPErrorContainer

type HTTPErrorContainer struct {
	// Errors contains all the httperrorhandlers
	Errors []*HTTPErrorHandler
}

HTTPErrorContainer 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)

func (*HTTPErrorContainer) EmitError

func (he *HTTPErrorContainer) EmitError(errCode int, ctx *Context)

EmitError executes the handler of the given error http status code

func (*HTTPErrorContainer) GetByCode

func (he *HTTPErrorContainer) GetByCode(httpStatus int) *HTTPErrorHandler

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

func (*HTTPErrorContainer) OnError

func (he *HTTPErrorContainer) OnError(httpStatus int, handler HandlerFunc)

OnError Registers a handler for a specific http error status

func (*HTTPErrorContainer) OnNotFound

func (he *HTTPErrorContainer) OnNotFound(handlerFunc HandlerFunc)

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

func (*HTTPErrorContainer) OnPanic

func (he *HTTPErrorContainer) 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

type HTTPErrorHandler

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

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

func (*HTTPErrorHandler) GetCode

func (e *HTTPErrorHandler) GetCode() int

GetCode returns the http status code value

func (*HTTPErrorHandler) GetHandler

func (e *HTTPErrorHandler) GetHandler() HandlerFunc

GetHandler returns the handler which is type of HandlerFunc

func (*HTTPErrorHandler) SetHandler

func (e *HTTPErrorHandler) SetHandler(h HandlerFunc)

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

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 an http.Handler or http.HandlerFunc to an iris.Handler

func ToHandlerFastHTTP

func ToHandlerFastHTTP(h fasthttp.RequestHandler) Handler

ToHandlerFastHTTP converts an fasthttp.RequestHandler to an iris.Handler

type HandlerAPI

type HandlerAPI interface {
}

HandlerAPI allow the use of a custom struct as API handler(s) for a particular request path It's just an interface {}, we keep it here to make things more readable.

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 HTTPErrorHandlerFunc

func HTTPErrorHandlerFunc(statusCode int, message string) HandlerFunc

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

func StaticHandlerFunc

func StaticHandlerFunc(systemPath string, stripSlashes int, compress bool, generateIndexPages bool, indexNames []string) HandlerFunc

StaticHandlerFunc returns a HandlerFunc to serve static system directory Accepts 5 parameters

first is the systemPath (string) Path to the root directory to serve files from.

second is the stripSlashes (int) level * stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar" * stripSlashes = 1, original path: "/foo/bar", result: "/bar" * stripSlashes = 2, original path: "/foo/bar", result: ""

third is the compress (bool) Transparently compresses responses if set to true.

The server tries minimizing CPU usage by caching compressed files. It adds FSCompressedFileSuffix suffix to the original file name and tries saving the resulting compressed file under the new file name. So it is advisable to give the server write access to Root and to all inner folders in order to minimze CPU usage when serving compressed responses.

fourth is the generateIndexPages (bool) Index pages for directories without files matching IndexNames are automatically generated if set.

Directory index generation may be quite slow for directories with many files (more than 1K), so it is discouraged enabling index pages' generation for such directories.

fifth is the indexNames ([]string) List of index file names to try opening during directory access.

For example:

  • index.html
  • index.htm
  • my-super-index.xml

func ToHandlerFunc

func ToHandlerFunc(handler interface{}) HandlerFunc

ToHandlerFunc converts an http.Handler or http.HandlerFunc to an iris.HandlerFunc

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 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 IMiddlewareSupporter

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

IMiddlewareSupporter is an interface which all routers must implement

type IParty

type IParty interface {
	Handle(string, string, ...Handler)
	HandleFunc(string, string, ...HandlerFunc)
	HandleAnnotated(Handler) error
	API(path string, controller HandlerAPI, middlewares ...HandlerFunc) error
	Get(string, ...HandlerFunc)
	Post(string, ...HandlerFunc)
	Put(string, ...HandlerFunc)
	Delete(string, ...HandlerFunc)
	Connect(string, ...HandlerFunc)
	Head(string, ...HandlerFunc)
	Options(string, ...HandlerFunc)
	Patch(string, ...HandlerFunc)
	Trace(string, ...HandlerFunc)
	Any(string, ...HandlerFunc)
	Use(...Handler)
	UseFunc(...HandlerFunc)
	StaticHandlerFunc(systemPath string, stripSlashes int, compress bool, generateIndexPages bool, indexNames []string) HandlerFunc
	Static(string, string, int)
	StaticFS(string, string, int)
	StaticWeb(relative string, systemPath string, stripSlashes int)
	StaticServe(systemPath string, requestPath ...string)
	Party(string, ...HandlerFunc) IParty // Each party can have a party too
	IsRoot() bool
}

IParty is the interface which implements the whole Party of routes

func Party

func Party(path string, handlersFn ...HandlerFunc) 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 {
}

IPlugin just an empty base for plugins A Plugin can be added with: .Add(PreHandleFunc(func(IRoute))) and so on... or .Add(myPlugin{}) which myPlugin is a struct with any of the methods below or .PreHandle(PreHandleFunc), .PostHandle(func(IRoute)) and so on...

type IPluginActivate

type IPluginActivate interface {
	// 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
}

IPluginActivate implements the Activate(IPluginContainer) error method

type IPluginContainer

type IPluginContainer interface {
	Add(plugin IPlugin) error
	Remove(pluginName string) error
	GetName(plugin IPlugin) string
	GetDescription(plugin IPlugin) string
	GetByName(pluginName string) IPlugin
	Printf(format string, a ...interface{})
	DoPreHandle(route IRoute)
	DoPostHandle(route IRoute)
	DoPreListen(station *Iris)
	DoPostListen(station *Iris)
	DoPreClose(station *Iris)
	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 IPluginGetDescription

type IPluginGetDescription interface {
	// GetDescription has to returns the description of what the plugins is used for
	GetDescription() string
}

IPluginGetDescription implements the GetDescription() string method

type IPluginGetName

type IPluginGetName 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
}

IPluginGetName implements the GetName() string method

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(*Iris)
}

IPluginPostListen implements the PostListen(*Iris) 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(*Iris)
}

IPluginPreClose implements the PreClose(*Iris) 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(*Iris)
}

IPluginPreListen implements the PreListen(*Iris) method

type IRoute

type IRoute interface {
	GetMethod() string
	GetDomain() string
	GetPath() string
	GetMiddleware() Middleware
	HasCors() bool
}

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 Iris

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

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

var DefaultIris *Iris = New()

DefaultIris in order to use iris.Get(...,...) we need a default Iris on the package level

func New

func New(cfg ...config.Iris) *Iris

New creates and returns a new iris station.

Receives an optional config.Iris as parameter If empty then config.Default() is used instead

func (*Iris) Close

func (s *Iris) Close()

Close terminates the server and panic if error occurs

func (*Iris) CloseWithErr

func (s *Iris) CloseWithErr() error

CloseWithErr is used to close the tcp listener from the server, returns an error

func (*Iris) Config

func (s *Iris) Config() *config.Iris

Config returns the configs

func (*Iris) Listen

func (s *Iris) Listen(addr string)

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

It panics on error if you need a func to return an error use the ListenWithErr ex: iris.Listen(":8080")

func (*Iris) ListenTLS

func (s *Iris) ListenTLS(addr string, certFile, keyFile string)

ListenTLS Starts a https server with certificates, if you use this method the requests of the form of 'http://' will fail only https:// connections are allowed which listens to the addr parameter which as the form of host:port or just port

It panics on error if you need a func to return an error use the ListenTLSWithErr ex: iris.ListenTLS(":8080","yourfile.cert","yourfile.key")

func (*Iris) ListenTLSWithErr

func (s *Iris) ListenTLSWithErr(addr string, certFile, keyFile string) error

ListenTLSWithErr Starts a https server with certificates, if you use this method the requests of the form of 'http://' will fail only https:// connections are allowed which listens to the addr parameter which as the form of host:port or just port

It returns an error you are responsible how to handle this if you need a func to panic on error use the ListenTLS ex: log.Fatal(iris.ListenTLSWithErr(":8080","yourfile.cert","yourfile.key"))

func (*Iris) ListenWithErr

func (s *Iris) ListenWithErr(addr string) error

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

It returns an error you are responsible how to handle this if you need a func to panic on error use the Listen ex: log.Fatal(iris.ListenWithErr(":8080"))

func (*Iris) Logger

func (s *Iris) Logger() *logger.Logger

Logger returns the logger

func (*Iris) Plugins

func (s *Iris) Plugins() *PluginContainer

Plugins returns the plugin container

func (*Iris) PostListen

func (s *Iris) PostListen()

PostListen sets the rest render, template engine, sessions and notice the plugins capital because we need it sometimes, for example inside the graceful it's a non-blocking func

func (*Iris) PreListen

func (s *Iris) PreListen(opt config.Server) *server.Server

PreListen call router's optimize, sets the server's handler and notice the plugins capital because we need it sometimes, for example inside the graceful receives the config.Server returns the station's Server (*server.Server) it's a non-blocking func

func (*Iris) Rest

func (s *Iris) Rest() *rest.Render

Render returns the rest render

func (*Iris) Server

func (s *Iris) Server() *server.Server

Server returns the server

func (*Iris) Templates

func (s *Iris) Templates() *template.Template

Templates returns the template render

func (*Iris) Websocket

func (s *Iris) Websocket() websocket.Server

Websocket returns the websocket server

type Map

type Map map[string]interface{}

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 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) 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 Plugins

func Plugins() *PluginContainer

Plugins returns the plugin container

func (*PluginContainer) Add

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

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

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 *Iris)

DoPostListen raise all plugins which has the DoPostListen method

func (*PluginContainer) DoPreClose

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

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 *Iris)

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) GetDescription

func (p *PluginContainer) GetDescription(plugin IPlugin) string

GetDescription returns the name of a plugin, if no GetDescription() implemented it returns an empty string ""

func (*PluginContainer) GetDownloader

func (p *PluginContainer) GetDownloader() IDownloadManager

GetDownloader returns the download manager

func (*PluginContainer) GetName

func (p *PluginContainer) GetName(plugin IPlugin) string

GetName returns the name of a plugin, if no GetName() implemented it returns an empty string ""

func (*PluginContainer) PostHandle

func (p *PluginContainer) PostHandle(fn PostHandleFunc)

PostHandle adds a PostHandle plugin-function to the plugin flow container

func (*PluginContainer) PostListen

func (p *PluginContainer) PostListen(fn PostListenFunc)

PostListen adds a PostListen plugin-function to the plugin flow container

func (*PluginContainer) PreClose

func (p *PluginContainer) PreClose(fn PreCloseFunc)

PreClose adds a PreClose plugin-function to the plugin flow container

func (*PluginContainer) PreDownload

func (p *PluginContainer) PreDownload(fn PreDownloadFunc)

PreDownload adds a PreDownload plugin-function to the plugin flow container

func (*PluginContainer) PreHandle

func (p *PluginContainer) PreHandle(fn PreHandleFunc)

PreHandle adds a PreHandle plugin-function to the plugin flow container

func (*PluginContainer) PreListen

func (p *PluginContainer) PreListen(fn PreListenFunc)

PreListen adds a PreListen plugin-function to the plugin flow container

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) Remove

func (p *PluginContainer) Remove(pluginName string) error

Remove removes a plugin by it's name, if pluginName is empty "" or no plugin found with this name, then nothing is removed and a specific error is returned. This doesn't calls the PreClose method

type PostHandleFunc

type PostHandleFunc func(IRoute)

func (PostHandleFunc) PostHandle

func (fn PostHandleFunc) PostHandle(route IRoute)

type PostListenFunc

type PostListenFunc func(*Iris)

func (PostListenFunc) PostListen

func (fn PostListenFunc) PostListen(station *Iris)

type PreCloseFunc

type PreCloseFunc func(*Iris)

func (PreCloseFunc) PreClose

func (fn PreCloseFunc) PreClose(station *Iris)

type PreDownloadFunc

type PreDownloadFunc func(IPlugin, string)

func (PreDownloadFunc) PreDownload

func (fn PreDownloadFunc) PreDownload(pl IPlugin, downloadURL string)

type PreHandleFunc

type PreHandleFunc func(IRoute)

func (PreHandleFunc) PreHandle

func (fn PreHandleFunc) PreHandle(route IRoute)

type PreListenFunc

type PreListenFunc func(*Iris)

func (PreListenFunc) PreListen

func (fn PreListenFunc) PreListen(station *Iris)

type Route

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

Route contains basic and temporary info about the route in order to be stored to the tree It's struct because we pass it ( as IRoute) to the plugins

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) HasCors

func (r *Route) HasCors() bool

HasCors check if middleware passsed to a route has cors

Directories

Path Synopsis
File bindings/form.go source code from https://github.com/monoculum/formame.
File bindings/form.go source code from https://github.com/monoculum/formame.
Package config defines the default settings and semantic variables
Package config defines the default settings and semantic variables
middleware
plugin
render
store
Package store the package is in diffent folder to reduce the import cycles from the ./context/context.go *
Package store the package is in diffent folder to reduce the import cycles from the ./context/context.go *
Package tests empty Why empty? The only reason I don't make unit tests is because I think the whole story here is wrong.
Package tests empty Why empty? The only reason I don't make unit tests is because I think the whole story here is wrong.

Jump to

Keyboard shortcuts

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