iris

package module
v0.0.0-...-9648eb0 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2016 License: BSD-3-Clause Imports: 21 Imported by: 0

README

Iris Web Framework

[![Build Status](https://travis-ci.org/kataras/iris.svg)](https://travis-ci.org/kataras/iris) [![Go Report Card](https://goreportcard.com/badge/github.com/kataras/iris)](https://goreportcard.com/report/github.com/kataras/iris) [![GoDoc](https://godoc.org/github.com/kataras/iris?status.svg)](https://godoc.org/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)

Iris is a very minimal but flexible go web framework providing arobust set of features for building shiny web applications.

V0.0.1

This project is under extremely development

Table of Contents

Install

$ go get github.com/kataras/iris
Update

Iris is still in development status, in order to have the latest version update the package every 2-3 days

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

Benchmarks

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

Benchmark Wizzard Iris vs gin vs martini

Principles of iris

  • Easy to use

  • Robust

  • Simplicity Equals Productivity. The best way to make something seem simple is to have it actually be simple. iris's main functionality has clean, classically beautiful APIs

Features

Parameters in your routing pattern: give meaming to your routes, give them a path segment a name and the iris' will provide the dynamic value to you.

Party of routes: Combine routes where have same prefix, provide a middleware to this Party, a Party can have other Party too.

Compatible: At the end the Iris is just a middleware which acts like router and a small simply web framework, this means that you can you use it side-by-side with your favorite big and well-tested web framework. Iris is fully compatible with the net/http package.

Multi server instances: Besides the fact that iris has a default main server. You can declare a new iris using the iris.New() func. example: server1:= iris.New(); server1.Get(....); server1.Listen(":9999")

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")
	//or for https and http2
	//iris.ListenTLS(":8080","localhost.cert","localhost.key")
	//the cert and key must be in the same path of the executable main server file
}

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

API

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

package main

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

func main() {
	iris.Get("/home", iris.ToHandlerFunc(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(res http.ResponseWriter, req *http.Request) {
	//...
}

//iris.Context gives more information and control of the route, named parameters, redirect, error handling and render.
func testPost(c *iris.Context) {
	//...
}

//and so on....

Iris is compatible with net/http package over iris.ToHandlerFunc(...) or iris.ToHandler(...) if you wanna use a whole iris.Handler interface. You can use any method you like but, believe me it's easier to pass just a func(c *Context).

Declaration

Let's make a pause,

  • Q: Why you use iris package declaration? other frameworks needs more lines to start a server
  • 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))
}

Match anything and the Static serve handler

Match everything/anything (symbol *withAKeyLikeParameters)

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

Pure http static file server as handler using iris.Static("./path/to/the/resources/directory/","path_to_strip_or_nothing")

// Will match any request which url's preffix is "/public/"
/* and continues with a file whith it's extension which exists inside the os.Gwd()(dot means working directory)+ /static/resources/
*/
iris.Get("/public/*assets", iris.Static("./static/resources/","/public/"))
//Note: strip of the /public/ is handled  by passing the last argument to "/public/"
//you can pass only the first two arguments for no strip path.

Declaring routes

Iris framework has three (3) different forms of functions in order to declare a route's handler and one(1) annotated struct to declare a complete route.

  1. Typical classic handler function, compatible with net/http and other frameworks using iris.ToHandlerFunc
    • *func(res http.ResponseWriter, req http.Request)
	iris.Get("/user/add", iris.ToHandlerFunc(func(res http.ResponseWriter, req *http.Request)) {

	})
  1. Context parameter in function-declaration
    • *func(c iris.Context)
	iris.Get("/user/:userId", func(c *iris.Context) {

	})
  1. http.Handler again it can be converted by ToHandlerFunc
    • http.Handler
	iris.Get("/about", iris.ToHandlerFunc(http.HandlerFunc(func(res http.Response, req *req.Request)) {

	}))

Note that all .Get,.Post takes a func(c *Context) as parameter, to pass an iris.Handler use the iris.Handle("/path",handler,"GET") 4. 'External' annotated struct which directly implements the Iris Handler interface

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

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

func (u *UserRoute) 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(&UserRoute{})
	//...continue writing your wonderful API

Personally I use the external struct and the *func(c iris.Context) form . At the next chapter you will learn what are the benefits of having the Context as parameter to the handler.

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. 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.
  16. 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).

  17. WriteXML(status int, xmlStructs ...interface{}) & XML(xmlStructs ...interface{}) returns error

    • WriteXML: Writes writes xml which is converted from struct(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.
    • XML: Same as WriteXML but you don't have to pass a status, it's defaulted to http.StatusOK (200).
  18. 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.
  19. 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.
  20. Next()

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

    • SendStatus: writes a http statusCode with a text/plain message

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

Inside the _examples folder you will find practical examples

.

Third Party Middleware

*The iris tries to supports a lot of middleware out there, you can use them by parsing their handlers, for example: *

iris.UseFunc(func(c *iris.Context) {
		//run the middleware here
		c.Next()
	})

Note: Some of these, may not be work, a lot of them are especially for Negroni and nothing more.

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
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
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 Olivier Poitrey Cross Origin Resource Sharing (CORS) support No
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 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

  • Provide a lighter, with less using bytes, to save middleware for a route.
  • Create examples in this repository.
  • Subdomains supports with the same syntax as iris.Get, iris.Post ...
  • Convert useful middlewares out there into Iris middlewares, or contact with their authors to do so.
  • Create an easy websocket api.
  • Create a mechanism that scan for Typescript files, compile them on server startup and serve them.

Licence

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

Documentation

Overview

Copyright (c) 2016, Julien Schmidt & 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 JULIEN SCHMIDT 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 text/xml response headers
	ContentXML = "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('/')
	// 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"
)

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.

Functions

func Close

func Close()

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

func GetParamsLen

func GetParamsLen(path string) uint8

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 Plugin

func Plugin(plugin IPlugin) error

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

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

Types

type Branch

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

func (*Branch) AddBranch

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

func (*Branch) AddNode

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

func (*Branch) GetBranch

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

func (*Branch) GivePrecedenceTo

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

type BranchCase

type BranchCase uint8

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

func (ctx *Context) End()

End same as Close, end the response process.

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

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

GetInt same as Get but returns the value as int

func (*Context) GetRequest

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

func (*Context) GetResponseWriter

func (ctx *Context) GetResponseWriter() IMemoryWriter

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

func (*Context) JSON

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

JSON calls the WriteJSON with the 200 http status ok

func (*Context) New

func (ctx *Context) New()

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 use the default http.NotFound which is already registed nothing special to do here

func (*Context) Panic

func (ctx *Context) Panic()

Panic stops the executions of the context and returns a http status to the client

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

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

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

func (ctx *Context) RequestIP() string

RequestIP gets just the Remote Address from the client.

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

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

SetCookie adds a cookie to the request

func (*Context) SetRequest

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

func (*Context) SetResponseWriter

func (ctx *Context) SetResponseWriter(res IMemoryWriter)

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) 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) 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, xmlStructs ...interface{}) error

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

func (*Context) XML

func (ctx *Context) XML(xmlStructs ...interface{}) error

XML calls the WriteXML with the 200 http status ok

type ErrorHandler

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

ErrorHandlers just an array of struct{ code int, handler http.Handler}

func (ErrorHandler) GetCode

func (e ErrorHandler) GetCode() int

func (ErrorHandler) GetHandler

func (e ErrorHandler) GetHandler() HandlerFunc

func (*ErrorHandler) SetHandler

func (e *ErrorHandler) SetHandler(h HandlerFunc)

type Garden

type Garden []tree // node here is the root node

Garden is the main area which routes are planted/placed

func (Garden) Get

func (g Garden) Get(index int) ITree

func (Garden) GetByMethod

func (g Garden) GetByMethod(method string) IBranch

func (Garden) Len

func (g Garden) Len() int

func (Garden) Plant

func (g Garden) Plant(method string, _route IRoute) IGarden

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

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

func (*HTTPErrors) NotFound

func (he *HTTPErrors) NotFound(ctx *Context)

NotFound emits the registed NotFound (404) custom (or not) handler

func (*HTTPErrors) On

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

On Registers a handler for a specific http error status ( overrides the NotFound and MethodNotAllowed)

func (*HTTPErrors) SetNotFound

func (he *HTTPErrors) SetNotFound(handler HandlerFunc)

SetNotFound this func could named it OnNotFound also, registers a custom StatusNotFound error 404 handler Possible parameter: iris.Handler or iris.HandlerFunc(func(ctx *Context){})

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

ErrorHandler 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
}

type IContext

type IContext interface {
	New()
	Do()
	Redo(req *http.Request, res http.ResponseWriter)
	Next()
	GetResponseWriter() IMemoryWriter
	GetRequest() *http.Request
	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)
	NotFound()
	SendStatus(statusCode int, message string)
	Panic()
	RequestIP() string
	Close()
	End()
	IsStopped() bool
	Clone() *Context ///todo IContext again
	RenderFile(file string, pageContext interface{}) error
	Render(pageContext interface{}) error
	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
	WriteJSON(httpStatus int, jsonObjectOrArray interface{}) error
	JSON(jsonObjectOrArray interface{}) error
	WriteXML(httpStatus int, xmlStructs ...interface{}) error
	XML(xmlStructs ...interface{}) error
}

type IErrorHandler

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

type IGarden

type IGarden interface {
	GetByMethod(method string) IBranch
	Plant(method string, _route IRoute) IGarden
	Get(index int) ITree
	Len() int
}

type IHTTPErrors

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

func DefaultHTTPErrors

func DefaultHTTPErrors() IHTTPErrors

DefaultHTTPErrors creates and returns an instance of HTTPErrors with default handlers

func Errors

func Errors() IHTTPErrors

Errors sets and gets custom error handlers or responses

type IMemoryWriter

type IMemoryWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.CloseNotifier

	Size() int

	Status() int

	//
	IsWritten() bool

	ForceHeader()
}

type IMiddlewareSupporter

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

IMiddlewareSupporter is an interface which all routers must implement

type IParty

type IParty interface {
	IRouterMethods
	IPartyHoster
	IMiddlewareSupporter
	SetParentHosterMiddleware(m Middleware)
}

IParty is the interface which implements the whole Party of routes

func NewParty

func NewParty(rootPath string, underlineMainRouter IRouter) IParty

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 IPartyHoster

type IPartyHoster interface {
	Party(path string) IParty
}

IPartyHoster is the interface which implements the Party func

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

	// PreHandle it's being called every time BEFORE a Route is registed to the Router
	//
	// first parameter is the HTTP method
	// second is the Route
	PreHandle(string, IRoute)
	// PostHandle it's being called every time AFTER a Route successfully registed to the Router
	//
	// first parameter is the HTTP method
	// second is the Route
	PostHandle(string, IRoute)
	// 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
	PreListen(*Station)
	// PostListen it's being called only one time, AFTER the Server is started (if .Listen called)
	// is used to do work when the server is running
	PostListen(*Station, error)

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

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(method string, route IRoute)
	DoPostHandle(method string, route IRoute)
	DoPreListen(station *Station)
	DoPostListen(station *Station, err error)
	DoPreClose(station *Station)
}

type IRoute

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

func Any

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

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

func Connect

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

Connect registers a route for the Connect http method

func Delete

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

Delete registers a route for the Delete http method

func Get

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

Get registers a route for the Get http method

func Handle

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

Handle registers a route to the server's router

func HandleAnnotated

func HandleAnnotated(irisHandler Handler) (IRoute, 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) IRoute

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

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

Head registers a route for the Head http method

func Options

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

Options registers a route for the Options http method

func Patch

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

Patch registers a route for the Patch http method

func Post

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

Post registers a route for the Post http method

func Put

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

Put registers a route for the Put http method

func Trace

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

Trace registers a route for the Trace http methodd

type IRouter

type IRouter interface {
	IMiddlewareSupporter
	IRouterMethods
	IPartyHoster
	HandleAnnotated(Handler) (IRoute, error)
	Handle(string, string, ...Handler) IRoute
	HandleFunc(string, string, ...HandlerFunc) IRoute
	Errors() IHTTPErrors //at the main Router struct this is managed by the MiddlewareSupporter
	// ServeHTTP finds and serves a route by it's request
	// If no route found, it sends an http status 404
	ServeHTTP(http.ResponseWriter, *http.Request)
}

IRouter is the interface of which any Iris router must implement

type IRouterCache

type IRouterCache interface {
	OnTick()
	AddItem(method, url string, ctx *Context)
	GetItem(method, url string) *Context
	SetMaxItems(maxItems int)
}

IRouterCache is the interface which the MemoryRouter implements

type IRouterMethods

type IRouterMethods interface {
	Get(path string, handlersFn ...HandlerFunc) IRoute
	Post(path string, handlersFn ...HandlerFunc) IRoute
	Put(path string, handlersFn ...HandlerFunc) IRoute
	Delete(path string, handlersFn ...HandlerFunc) IRoute
	Connect(path string, handlersFn ...HandlerFunc) IRoute
	Head(path string, handlersFn ...HandlerFunc) IRoute
	Options(path string, handlersFn ...HandlerFunc) IRoute
	Patch(path string, handlersFn ...HandlerFunc) IRoute
	Trace(path string, handlersFn ...HandlerFunc) IRoute
	Any(path string, handlersFn ...HandlerFunc) IRoute
}

IRouterMethods is the interface for method routing

type IStation

type IStation interface {
	IRouter
	Plugin(IPlugin) error
	GetPluginContainer() IPluginContainer
	GetPool() *sync.Pool
	GetTemplates() *template.Template
}

type ITick

type ITick interface {
	OnTick()
}

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

type ITree

type ITree interface {
	GetMethod() string
	GetNode() IBranch
}

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

type MemoryRouterCache

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

MemoryRouterCache creation done with just &MemoryRouterCache{}

func NewMemoryRouterCache

func NewMemoryRouterCache() *MemoryRouterCache

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

func (*MemoryRouterCache) AddItem

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

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

func (*MemoryRouterCache) GetItem

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

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

func (*MemoryRouterCache) OnTick

func (mc *MemoryRouterCache) OnTick()

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

func (*MemoryRouterCache) SetMaxItems

func (mc *MemoryRouterCache) SetMaxItems(_itemslen int)

SetMaxItems receives int and set max cached items to this number

type MemoryWriter

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

func (*MemoryWriter) CloseNotify

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

func (*MemoryWriter) Flush

func (m *MemoryWriter) Flush()

func (*MemoryWriter) ForceHeader

func (m *MemoryWriter) ForceHeader()

func (*MemoryWriter) Hijack

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

func (*MemoryWriter) IsWritten

func (m *MemoryWriter) IsWritten() bool

func (*MemoryWriter) New

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

func (*MemoryWriter) Size

func (m *MemoryWriter) Size() int

func (*MemoryWriter) Status

func (m *MemoryWriter) Status() int

func (*MemoryWriter) Write

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

func (*MemoryWriter) WriteHeader

func (m *MemoryWriter) WriteHeader(statusCode int)

type Middleware

type Middleware []Handler

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

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

func (m MiddlewareSupporter) JoinMiddleware(middleware Middleware) Middleware

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

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(method string, route IRoute)

func (*PluginContainer) DoPostListen

func (p *PluginContainer) DoPostListen(station *Station, err error)

func (*PluginContainer) DoPreClose

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

func (*PluginContainer) DoPreHandle

func (p *PluginContainer) DoPreHandle(method string, route IRoute)

func (*PluginContainer) DoPreListen

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

func (*PluginContainer) GetByName

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

GetByName returns a plugin instance by it's name

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(registedPath string, middleware Middleware) *Route

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

func (Route) GetMiddleware

func (r Route) GetMiddleware() Middleware

func (Route) GetPath

func (r Route) GetPath() string

func (Route) GetPathPrefix

func (r Route) GetPathPrefix() string

func (*Route) ProcessPath

func (r *Route) ProcessPath()

func (Route) SetMiddleware

func (r Route) SetMiddleware(m Middleware)

type Router

type Router struct {
	MiddlewareSupporter
	// 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 IStation) *Router

NewRouter creates and returns an empty Router

func (*Router) Any

func (r *Router) Any(path string, handlersFn ...HandlerFunc) IRoute

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

func (*Router) Connect

func (r *Router) Connect(path string, handlersFn ...HandlerFunc) IRoute

Connect registers a route for the Connect http method

func (*Router) Delete

func (r *Router) Delete(path string, handlersFn ...HandlerFunc) IRoute

Delete registers a route for the Delete http method

func (*Router) Errors

func (r *Router) Errors() IHTTPErrors

Errors get the HTTPErrors from the router

func (*Router) Get

func (r *Router) Get(path string, handlersFn ...HandlerFunc) IRoute

Get registers a route for the Get http method

func (*Router) Handle

func (r *Router) Handle(method string, registedPath string, handlers ...Handler) IRoute

Handle registers a route to the server's router

func (*Router) HandleAnnotated

func (r *Router) HandleAnnotated(irisHandler Handler) (IRoute, 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 (*Router) HandleFunc

func (r *Router) HandleFunc(method string, registedPath string, handlersFn ...HandlerFunc) IRoute

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 (*Router) Head

func (r *Router) Head(path string, handlersFn ...HandlerFunc) IRoute

Head registers a route for the Head http method

func (*Router) Options

func (r *Router) Options(path string, handlersFn ...HandlerFunc) IRoute

Options registers a route for the Options http method

func (*Router) Party

func (r *Router) 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

func (*Router) Patch

func (r *Router) Patch(path string, handlersFn ...HandlerFunc) IRoute

Patch registers a route for the Patch http method

func (*Router) Post

func (r *Router) Post(path string, handlersFn ...HandlerFunc) IRoute

Post registers a route for the Post http method

func (*Router) Put

func (r *Router) Put(path string, handlersFn ...HandlerFunc) IRoute

Put registers a route for the Put http method

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

func (*Router) SetErrors

func (r *Router) SetErrors(httperr IHTTPErrors)

SetErrors sets a HTTPErrors object to the router

func (*Router) Trace

func (r *Router) Trace(path string, handlersFn ...HandlerFunc) IRoute

Trace registers a route for the Trace http method

type Server

type Server struct {
	// 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
	// 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) GetPluginContainer

func (s Station) GetPluginContainer() IPluginContainer

func (Station) GetPool

func (s Station) GetPool() *sync.Pool

func (Station) GetTemplates

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

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

Jump to

Keyboard shortcuts

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