lion

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

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

Go to latest
Published: Nov 1, 2016 License: MIT Imports: 17 Imported by: 0

README

Lion Build Status GoDoc License Go Report Card

Lion is a fast HTTP router for Go with support for middlewares for building modern scalable modular REST APIs.

Lion's Hello World GIF

Lion v2

If you are starting a new project, please consider starting out using the v2 and the new documentation branch. It contains a few breaking changes.

The most important one is that it now uses native http.Handler.

Important

If you are using lion v1, please change your import path to gopkg.in/celrenheit/lion.v1.

You can get lion via:

go get -u gopkg.in/celrenheit/lion.v1

Features

  • Context-Aware: Lion uses the de-facto standard net/Context for storing route params and sharing variables between middlewares and HTTP handlers. It could be integrated in the standard library for Go 1.7 in 2016.
  • Modular: You can define your own modules to easily build a scalable architecture
  • REST friendly: You can define modules to groups http resources together.
  • Host: Match hosts. Each host can get its own content.
  • Zero allocations: Lion generates zero garbage*.

Table of contents

Install/Update

$ go get -u gopkg.in/celrenheit/lion.v1

Hello World

package main

import (
	"fmt"
	"net/http"

	"github.com/celrenheit/lion"
	"golang.org/x/net/context"
)

func Home(c context.Context, w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Home")
}

func Hello(c context.Context, w http.ResponseWriter, r *http.Request) {
	name := lion.Param(c, "name")
	fmt.Fprintf(w, "Hello "+name)
}

func main() {
	l := lion.Classic()
	l.GetFunc("/", Home)
	l.GetFunc("/hello/:name", Hello)
	l.Run()
}

Try it yourself by running the following command from the current directory:

$ go run examples/hello/hello.go

Getting started with modules and resources

We are going to build a sample products listing REST api (without database handling to keep it simple):


func main() {
	l := lion.Classic()
	api := l.Group("/api")
	api.Module(Products{})
	l.Run()
}

// Products module is accessible at url: /api/products
// It handles getting a list of products or creating a new product
type Products struct{}

func (p Products) Base() string {
	return "/products"
}

func (p Products) Get(c context.Context, w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Fetching all products")
}

func (p Products) Post(c context.Context, w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Creating a new product")
}

func (p Products) Routes(r *lion.Router) {
	// Defining a resource for getting, editing and deleting a single product
	r.Resource("/:id", OneProduct{})
}

// OneProduct resource is accessible at url: /api/products/:id
// It handles getting, editing and deleting a single product
type OneProduct struct{}

func (p OneProduct) Get(c context.Context, w http.ResponseWriter, r *http.Request) {
	id := lion.Param(c, "id")
	fmt.Fprintf(w, "Getting product: %s", id)
}

func (p OneProduct) Put(c context.Context, w http.ResponseWriter, r *http.Request) {
	id := lion.Param(c, "id")
	fmt.Fprintf(w, "Updating article: %s", id)
}

func (p OneProduct) Delete(c context.Context, w http.ResponseWriter, r *http.Request) {
	id := lion.Param(c, "id")
	fmt.Fprintf(w, "Deleting article: %s", id)
}

Try it yourself. Run:

$ go run examples/modular-hello/modular-hello.go

Open your web browser to http://localhost:3000/api/products or http://localhost:3000/api/products/123. You should see "Fetching all products" or "Getting product: 123".

Handlers

Handlers should implement the Handler interface:

type Handler interface {
	ServeHTTPC(context.Context, http.ResponseWriter, *http.Request)
}
Using Handlers
l.Get("/get", get)
l.Post("/post", post)
l.Put("/put", put)
l.Delete("/delete", delete)
Using HandlerFuncs

HandlerFuncs shoud have this function signature:

func handlerFunc(c context.Context, w http.ResponseWriter, r *http.Request)  {
  fmt.Fprintf(w, "Hi!")
}

l.GetFunc("/get", handlerFunc)
l.PostFunc("/post", handlerFunc)
l.PutFunc("/put", handlerFunc)
l.DeleteFunc("/delete", handlerFunc)
Using native http.Handler
type nativehandler struct {}

func (_ nativehandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

}

l.GetH("/somepath", nativehandler{})
l.PostH("/somepath", nativehandler{})
l.PutH("/somepath", nativehandler{})
l.DeleteH("/somepath", nativehandler{})
Using native http.Handler with lion.Wrap()

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


func main() {
	l := lion.New()
	l.Get("/somepath", lion.Wrap(nativehandler{}))
}
Using native http.Handler with lion.WrapFunc()
func getHandlerFunc(w http.ResponseWriter, r *http.Request) {

}

func main() {
	l := lion.New()
	l.Get("/somepath", lion.WrapFunc(getHandlerFunc))
}

Middlewares

Middlewares should implement the Middleware interface:

type Middleware interface {
	ServeNext(Handler) Handler
}

The ServeNext function accepts a Handler and returns a Handler.

You can also use MiddlewareFuncs. For example:

func middlewareFunc(next Handler) Handler  {
	return next
}
Using Named Middlewares

Named middlewares are designed to be able to reuse a previously defined middleware. For example, if you have a EnsureAuthenticated middleware that check whether a user is logged in. You can define it once and reuse later in your application.

l := lion.New()
l.Define("EnsureAuthenticated", NewEnsureAuthenticatedMiddleware())

To reuse it later in your application, you can use the UseNamed method. If it cannot find the named middleware if the current Router instance it will try to find it in the parent router. If a named middleware is not found it will panic.

api := l.Group("/api")
api.UseNamed("EnsureAuthenticated")
Using Negroni Middlewares

You can use Negroni middlewares you can find a list of third party middlewares here

l := lion.New()
l.UseNegroni(negroni.NewRecovery())
l.Run()

Matching Hosts

You can match a specific or multiple hosts. You can use patterns in the same way they are currently used for routes with only some edge cases. The main difference is that you will have to use the '$' character instead of ':' to define a parameter.

admin.example.com will match admin.example.com $username.blog.com will match messi.blog.com will not match my.awesome.blog.com *.example.com will match my.admin.example.com

l := New()

// Group by /api basepath
api := l.Group("/api")

// Specific to v1
v1 := api.Subrouter().
	Host("v1.example.org")

v1.Get("/", v1Handler)

// Specific to v2
v2 := api.Subrouter().
	Host("v2.example.org")

v2.Get("/", v2Handler)
l.Run()

Resources

You can define a resource to represent a REST, CRUD api resource. You define global middlewares using Uses() method. For defining custom middlewares for each http method, you have to create a function which name is composed of the http method suffixed by "Middlewares". For example, if you want to define middlewares for the Get method you will have to create a method called: GetMiddlewares().

A resource is defined by the following methods. Everything is optional:


// Global middlewares for the resource (Optional)
Uses() Middlewares

// Middlewares for the http methods (Optional)
GetMiddlewares() Middlewares
PostMiddlewares() Middlewares
PutMiddlewares() Middlewares
DeleteMiddlewares() Middlewares


// HandlerFuncs for each HTTP Methods (Optional)
Get(c context.Context, w http.ResponseWriter, r *http.Request)
Post(c context.Context, w http.ResponseWriter, r *http.Request)
Put(c context.Context, w http.ResponseWriter, r *http.Request)
Delete(c context.Context, w http.ResponseWriter, r *http.Request)

Example:

package main

type todolist struct{}

func (t todolist) Uses() lion.Middlewares {
	return lion.Middlewares{lion.NewLogger()}
}

func (t todolist) Get(c context.Context, w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "getting todos")
}

func main() {
	l := lion.New()
	l.Resource("/todos", todolist{})
	l.Run()
}

## Modules

Modules are a way to modularize an api which can then define submodules, subresources and custom routes. A module is defined by the following methods:

// Required: Base url pattern of the module
Base() string

// Routes accepts a Router instance. This method is used to define the routes of this module.
// Each routes defined are relative to the Base() url pattern
Routes(*Router)

// Optional: Requires named middlewares. Refer to Named Middlewares section
Requires() []string
package main

type api struct{}

// Required: Base url
func (t api) Base() string { return "/api" }

// Required: Here you can declare sub-resources, submodules and custom routes.
func (t api) Routes(r *lion.Router) {
	r.Module(v1{})
	r.Get("/custom", t.CustomRoute)
}

// Optional: Attach Get method to this Module.
// ====> A Module is also a Resource.
func (t api) Get(c context.Context, w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "This also a resource accessible at http://localhost:3000/api")
}

// Optional: Defining custom routes
func (t api) CustomRoute(c context.Context, w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "This a custom route for this module http://localhost:3000/api/")
}

func main() {
	l := lion.New()
	// Registering the module
	l.Module(api{})
	l.Run()
}

Examples

Using GET, POST, PUT, DELETE http methods
l := lion.Classic()

// Using Handlers
l.Get("/get", get)
l.Post("/post", post)
l.Put("/put", put)
l.Delete("/delete", delete)

// Using functions
l.GetFunc("/get", getFunc)
l.PostFunc("/post", postFunc)
l.PutFunc("/put", putFunc)
l.DeleteFunc("/delete", deleteFunc)

l.Run()
Using middlewares
func main() {
	l := lion.Classic()

	// Using middleware
	l.Use(lion.NewLogger())

	// Using middleware functions
	l.UseFunc(someMiddlewareFunc)

	l.GetFunc("/hello/:name", Hello)

	l.Run()
}
Group routes by a base path
l := lion.Classic()
api := l.Group("/api")

v1 := l.Group("/v1")
v1.GetFunc("/somepath", gettingFromV1)

v2 := l.Group("/v2")
v2.GetFunc("/somepath", gettingFromV2)

l.Run()
Mounting a router into a base path
l := lion.Classic()

sub := lion.New()
sub.GetFunc("/somepath", getting)


l.Mount("/api", sub)
Default middlewares

lion.Classic() creates a router with default middlewares (Recovery, RealIP, Logger, Static). If you wish to create a blank router without any middlewares you can use lion.New().

func main()  {
	// This a no middlewares registered
	l := lion.New()
	l.Use(lion.NewLogger())

	l.GetFunc("/hello/:name", Hello)

	l.Run()
}

Custom Middlewares

Custom middlewares should implement the Middleware interface:

type Middleware interface {
	ServeNext(Handler) Handler
}

You can also make MiddlewareFuncs to use using .UseFunc() method. It has to accept a Handler and return a Handler:

func(next Handler) Handler
Custom Logger example
type logger struct{}

func (*logger) ServeNext(next lion.Handler) lion.Handler {
	return lion.HandlerFunc(func(c context.Context, w http.ResponseWriter, r *http.Request) {
		start := time.Now()

		next.ServeHTTPC(c, w, r)

		fmt.Printf("Served %s in %s\n", r.URL.Path, time.Since(start))
	})
}

Then in the main function you can use the middleware using:

l := lion.New()

l.Use(&logger{})
l.GetFunc("/hello/:name", Hello)
l.Run()

Benchmarks

Without path cleaning

BenchmarkLion_Param       	10000000	       164 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_Param5      	 5000000	       372 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_Param20     	 1000000	      1080 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_ParamWrite  	10000000	       180 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GithubStatic	10000000	       160 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GithubParam 	 5000000	       359 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GithubAll   	   30000	     62888 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GPlusStatic 	20000000	       104 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GPlusParam  	10000000	       182 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GPlus2Params	 5000000	       286 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GPlusAll    	  500000	      3227 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_ParseStatic 	10000000	       123 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_ParseParam  	10000000	       145 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_Parse2Params	10000000	       212 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_ParseAll    	  300000	      5242 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_StaticAll   	   50000	     37998 ns/op	       0 B/op	       0 allocs/op

With path cleaning

BenchmarkLion_Param       	10000000	       227 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_Param5      	 3000000	       427 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_Param20     	 1000000	      1321 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_ParamWrite  	 5000000	       256 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GithubStatic	10000000	       214 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GithubParam 	 3000000	       445 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GithubAll   	   20000	     88664 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GPlusStatic 	10000000	       122 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GPlusParam  	 5000000	       381 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GPlus2Params	 5000000	       409 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_GPlusAll    	  500000	      3952 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_ParseStatic 	10000000	       146 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_ParseParam  	10000000	       187 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_Parse2Params	 5000000	       314 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_ParseAll    	  200000	      7857 ns/op	       0 B/op	       0 allocs/op
BenchmarkLion_StaticAll   	   30000	     56170 ns/op	      96 B/op	       8 allocs/op

A more in depth benchmark with a comparison with other frameworks is coming soon.

License

https://github.com/celrenheit/lion/blob/master/LICENSE

Todo

  • Support for Go 1.7 context
  • Host matching
  • Automatic OPTIONS handler
  • Modules
    • JWT Auth module
  • Better static file handling
  • More documentation

Credits

Documentation

Overview

Package lion is a fast HTTP router for building modern scalable modular REST APIs in Go.

Install and update:

go get -u github.com/celrenheit/lion

Getting started:

Start by importing "github.com/celrenheit/lion" into your project. Then you need to create a new instance of the router using lion.New() for a blank router or lion.Classic() for a router with default middlewares included.

Here is a simple hello world example:

package main

import (
	"fmt"
	"net/http"

	"github.com/celrenheit/lion"
	"golang.org/x/net/context"
)

func Home(c context.Context, w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Home")
}

func Hello(c context.Context, w http.ResponseWriter, r *http.Request) {
	name := lion.Param(c, "name")
	fmt.Fprintf(w, "Hello "+name)
}

func main() {
	l := lion.Classic()
	l.GetFunc("/", Home)
	l.GetFunc("/hello/:name", Hello)
	l.Run()
}

You can open your web browser to http://localhost:3000/hello/world and you should see "Hello world". If it finds a PORT environnement variable it will use that. Otherwise, it will use run the server at localhost:3000. If you wish to provide a specific port you can run it using: l.Run(":8080")

Index

Constants

View Source
const (
	GET     = "GET"
	HEAD    = "HEAD"
	POST    = "POST"
	PUT     = "PUT"
	DELETE  = "DELETE"
	TRACE   = "TRACE"
	OPTIONS = "OPTIONS"
	CONNECT = "CONNECT"
	PATCH   = "PATCH"
)

HTTP methods constants

Variables

This section is empty.

Functions

func Param

func Param(c context.Context, key string) string

Param returns the value of a url param base on the passed context

func UnWrap

func UnWrap(h Handler) http.Handler

UnWrap converts a Handler to an http.Handler

Types

type ConnectResource

type ConnectResource interface {
	Connect(c context.Context, w http.ResponseWriter, r *http.Request)
}

ConnectResource is an interface for defining a HandlerFunc used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type ConnectResourceMiddlewares

type ConnectResourceMiddlewares interface {
	ConnectMiddlewares() Middlewares
}

ConnectResourceMiddlewares is an interface for defining middlewares used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type Context

type Context struct {
	context.Context
	// contains filtered or unexported fields
}

Context implements golang.org/x/net/context.Context and stores values of url parameters

func C

func C(c context.Context) *Context

C returns a Context based on a context.Context passed. If it does not convert to Context, it creates a new one with the context passed as argument.

func NewContext

func NewContext() *Context

NewContext creates a new context instance

func NewContextWithParent

func NewContextWithParent(c context.Context) *Context

NewContextWithParent creates a new context with a parent context specified

func (*Context) AddParam

func (p *Context) AddParam(key, val string)

func (*Context) Param

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

Param returns the value of a param. If it does not exist it returns an empty string

func (*Context) ParamOk

func (p *Context) ParamOk(key string) (string, bool)

ParamOk returns the value of a param and a boolean that indicates if the param exists.

func (*Context) Remove

func (p *Context) Remove(key string)

func (*Context) Reset

func (p *Context) Reset()

func (*Context) Value

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

Value returns the value for the passed key. If it is not found in the url params it returns parent's context Value

type DeleteResource

type DeleteResource interface {
	Delete(c context.Context, w http.ResponseWriter, r *http.Request)
}

DeleteResource is an interface for defining a HandlerFunc used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type DeleteResourceMiddlewares

type DeleteResourceMiddlewares interface {
	DeleteMiddlewares() Middlewares
}

DeleteResourceMiddlewares is an interface for defining middlewares used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type GetResource

type GetResource interface {
	Get(c context.Context, w http.ResponseWriter, r *http.Request)
}

GetResource is an interface for defining a HandlerFunc used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type GetResourceMiddlewares

type GetResourceMiddlewares interface {
	GetMiddlewares() Middlewares
}

GetResourceMiddlewares is an interface for defining middlewares used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type Handler

type Handler interface {
	ServeHTTPC(context.Context, http.ResponseWriter, *http.Request)
}

Handler responds to an HTTP request

func Wrap

func Wrap(h http.Handler) Handler

Wrap converts an http.Handler to returns a Handler

func WrapFunc

func WrapFunc(fn http.HandlerFunc) Handler

WrapFunc converts an http.HandlerFunc to return a Handler

type HandlerFunc

type HandlerFunc func(context.Context, http.ResponseWriter, *http.Request)

HandlerFunc is a wrapper for a function to implement the Handler interface

func (HandlerFunc) ServeHTTP

func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP makes HandlerFunc implement net/http.Handler interface

func (HandlerFunc) ServeHTTPC

func (h HandlerFunc) ServeHTTPC(c context.Context, w http.ResponseWriter, r *http.Request)

ServeHTTPC makes HandlerFunc implement Handler interface

type HeadResource

type HeadResource interface {
	Head(c context.Context, w http.ResponseWriter, r *http.Request)
}

HeadResource is an interface for defining a HandlerFunc used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type HeadResourceMiddlewares

type HeadResourceMiddlewares interface {
	HeadMiddlewares() Middlewares
}

HeadResourceMiddlewares is an interface for defining middlewares used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type Logger

type Logger struct {
	*log.Logger
}

Logger is a middlewares that logs incoming http requests

func NewLogger

func NewLogger() *Logger

NewLogger creates a new Logger

func (*Logger) ServeNext

func (l *Logger) ServeNext(next Handler) Handler

ServeNext implements the Middleware interface for Logger. It wraps the corresponding http.ResponseWriter and saves statistics about the status code returned, the number of bytes written and the time that requests took.

type M

type M map[string]string

M is an alias for map[string]string.

type Middleware

type Middleware interface {
	ServeNext(Handler) Handler
}

Middleware interface that takes as input a Handler and returns a Handler

func MaxAge

func MaxAge(dur time.Duration) Middleware

MaxAge is a middleware that defines the max duration headers

func MaxAgeWithFilter

func MaxAgeWithFilter(dur time.Duration, filter func(c context.Context, w http.ResponseWriter, r *http.Request) bool) Middleware

MaxAgeWithFilter is a middleware that defines the max duration headers with a filter function. If the filter returns true then the headers will be set. Otherwise, if it returns false the headers will not be set.

func NoCache

func NoCache() Middleware

NoCache middleware sets headers to disable browser caching. Inspired by https://github.com/mytrile/nocache

func RealIP

func RealIP() Middleware

RealIP is a middleware that sets a http.Request's RemoteAddr to the results of parsing either the X-Forwarded-For header or the X-Real-IP header (in that order).

This middleware should be inserted fairly early in the middleware stack to ensure that subsequent layers (e.g., request loggers) which examine the RemoteAddr will see the intended value.

You should only use this middleware if you can trust the headers passed to you (in particular, the two headers this middleware uses), for example because you have placed a reverse proxy like HAProxy or nginx in front of Goji. If your reverse proxies are configured to pass along arbitrary header values from the client, or if you use this middleware without a reverse proxy, malicious clients will be able to make you very sad (or, depending on how you're using RemoteAddr, vulnerable to an attack of some sort). Taken from https://github.com/zenazn/goji/blob/master/web/middleware/realip.go

type MiddlewareFunc

type MiddlewareFunc func(Handler) Handler

MiddlewareFunc wraps a function that takes as input a Handler and returns a Handler. So that it implements the Middlewares interface

func (MiddlewareFunc) ServeNext

func (m MiddlewareFunc) ServeNext(next Handler) Handler

ServeNext makes MiddlewareFunc implement Middleware

type Middlewares

type Middlewares []Middleware

Middlewares is an array of Middleware

func (Middlewares) BuildHandler

func (middlewares Middlewares) BuildHandler(handler Handler) Handler

BuildHandler builds a chain of middlewares from a passed Handler and returns a Handler

type Module

type Module interface {
	Resource
	Base() string
	Routes(*Router)
}

Module represent an independent router entity. It should be used to group routes and subroutes together.

type ModuleRequirements

type ModuleRequirements interface {
	Requires() []string
}

ModuleRequirements specify that the module requires specific named middlewares.

type OptionsResource

type OptionsResource interface {
	Options(c context.Context, w http.ResponseWriter, r *http.Request)
}

OptionsResource is an interface for defining a HandlerFunc used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type OptionsResourceMiddlewares

type OptionsResourceMiddlewares interface {
	OptionsMiddlewares() Middlewares
}

OptionsResourceMiddlewares is an interface for defining middlewares used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type PatchResource

type PatchResource interface {
	Patch(c context.Context, w http.ResponseWriter, r *http.Request)
}

PatchResource is an interface for defining a HandlerFunc used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type PatchResourceMiddlewares

type PatchResourceMiddlewares interface {
	PatchMiddlewares() Middlewares
}

PatchResourceMiddlewares is an interface for defining middlewares used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type PostResource

type PostResource interface {
	Post(c context.Context, w http.ResponseWriter, r *http.Request)
}

PostResource is an interface for defining a HandlerFunc used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type PostResourceMiddlewares

type PostResourceMiddlewares interface {
	PostMiddlewares() Middlewares
}

PostResourceMiddlewares is an interface for defining middlewares used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type PutResource

type PutResource interface {
	Put(c context.Context, w http.ResponseWriter, r *http.Request)
}

PutResource is an interface for defining a HandlerFunc used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type PutResourceMiddlewares

type PutResourceMiddlewares interface {
	PutMiddlewares() Middlewares
}

PutResourceMiddlewares is an interface for defining middlewares used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type Recovery

type Recovery struct {
	Logger     *log.Logger
	PrintStack bool
	StackAll   bool
	StackSize  int
}

Recovery is a middleware that recovers from panics Taken from https://github.com/codegangsta/negroni/blob/master/recovery.go

func NewRecovery

func NewRecovery() *Recovery

NewRecovery creates a new Recovery instance

func (*Recovery) ServeNext

func (rec *Recovery) ServeNext(next Handler) Handler

ServeNext is the method responsible for recovering from a panic

type RegisterMatcher

type RegisterMatcher interface {
	Register(method, pattern string, handler Handler)
	Match(*Context, *http.Request) (*Context, Handler)
}

RegisterMatcher registers and matches routes to Handlers

type Resource

type Resource interface{}

Resource defines the minimum required methods

type ResourceUses

type ResourceUses interface {
	Uses() Middlewares
}

ResourceUses is an interface with the Uses() method which can be used to define global middlewares for the resource. DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	http.Hijacker
	Status() int
	BytesWritten() int
	Tee(io.Writer)
	Unwrap() http.ResponseWriter
}

ResponseWriter is the proxy responseWriter

func WrapResponseWriter

func WrapResponseWriter(w http.ResponseWriter) ResponseWriter

WrapResponseWriter wraps an http.ResponseWriter and returns a ResponseWriter

type Router

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

Router is the main component of Lion. It is responsible for registering handlers and middlewares

func Classic

func Classic() *Router

Classic creates a new router instance with default middlewares: Recovery, RealIP, Logger and Static. The static middleware instance is initiated with a directory named "public" located relatively to the current working directory.

func New

func New(mws ...Middleware) *Router

New creates a new router instance

func (*Router) Any

func (r *Router) Any(pattern string, handler Handler)

Any registers the provided Handler for all of the allowed http methods: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH

func (*Router) AnyFunc

func (r *Router) AnyFunc(pattern string, handler HandlerFunc)

AnyFunc registers the provided HandlerFunc for all of the allowed http methods: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH

func (*Router) Connect

func (r *Router) Connect(pattern string, handler Handler)

Connect registers an http CONNECT method receiver with the provided Handler

func (*Router) ConnectFunc

func (r *Router) ConnectFunc(pattern string, fn HandlerFunc)

ConnectFunc wraps a HandlerFunc as a Handler and registers it to the router

func (*Router) ConnectH

func (r *Router) ConnectH(pattern string, handler http.Handler)

ConnectH wraps a http.Handler

func (*Router) Define

func (r *Router) Define(name string, mws ...Middleware)

Define registers some middleware using a name for reuse later using UseNamed method.

func (*Router) DefineFunc

func (r *Router) DefineFunc(name string, mws ...MiddlewareFunc)

DefineFunc is a convenience wrapper for Define() to use MiddlewareFunc instead of a Middleware instance

func (*Router) Delete

func (r *Router) Delete(pattern string, handler Handler)

Delete registers an http DELETE method receiver with the provided Handler

func (*Router) DeleteFunc

func (r *Router) DeleteFunc(pattern string, fn HandlerFunc)

DeleteFunc wraps a HandlerFunc as a Handler and registers it to the router

func (*Router) DeleteH

func (r *Router) DeleteH(pattern string, handler http.Handler)

DeleteH wraps a http.Handler

func (*Router) Get

func (r *Router) Get(pattern string, handler Handler)

Get registers an http GET method receiver with the provided Handler

func (*Router) GetFunc

func (r *Router) GetFunc(pattern string, fn HandlerFunc)

GetFunc wraps a HandlerFunc as a Handler and registers it to the router

func (*Router) GetH

func (r *Router) GetH(pattern string, handler http.Handler)

GetH wraps a http.Handler

func (*Router) Group

func (r *Router) Group(pattern string, mws ...Middleware) *Router

Group creates a subrouter with parent pattern provided.

func (*Router) Handle

func (r *Router) Handle(method, pattern string, handler Handler)

Handle is the underling method responsible for registering a handler for a specific method and pattern.

func (*Router) HandleFunc

func (r *Router) HandleFunc(method, pattern string, fn HandlerFunc)

HandleFunc wraps a HandlerFunc and pass it to Handle method

func (*Router) Head

func (r *Router) Head(pattern string, handler Handler)

Head registers an http HEAD method receiver with the provided Handler

func (*Router) HeadFunc

func (r *Router) HeadFunc(pattern string, fn HandlerFunc)

HeadFunc wraps a HandlerFunc as a Handler and registers it to the router

func (*Router) HeadH

func (r *Router) HeadH(pattern string, handler http.Handler)

HeadH wraps a http.Handler

func (*Router) Host

func (r *Router) Host(hostpattern string) *Router

Host sets the host for the current router instances. You can use patterns in the same way they are currently used for routes but in reverse order (params on the left)

NOTE: You have to use the '$' character instead of ':' for matching host parameters.

The following patterns works:

admin.example.com			will match			admin.example.com
$username.blog.com			will match			messi.blog.com
					will not match			my.awesome.blog.com
*.example.com				will match			my.admin.example.com

The following patterns are not allowed:

mail.*
*

func (*Router) Module

func (r *Router) Module(modules ...Module)

Module register modules for the current router instance.

func (*Router) Mount

func (r *Router) Mount(pattern string, router *Router, mws ...Middleware)

Mount mounts a subrouter at the provided pattern

func (*Router) NotFoundHandler

func (r *Router) NotFoundHandler(handler Handler)

NotFoundHandler gives the ability to use a specific 404 NOT FOUND handler

func (*Router) Options

func (r *Router) Options(pattern string, handler Handler)

Options registers an http OPTIONS method receiver with the provided Handler

func (*Router) OptionsFunc

func (r *Router) OptionsFunc(pattern string, fn HandlerFunc)

OptionsFunc wraps a HandlerFunc as a Handler and registers it to the router

func (*Router) OptionsH

func (r *Router) OptionsH(pattern string, handler http.Handler)

OptionsH wraps a http.Handler

func (*Router) Patch

func (r *Router) Patch(pattern string, handler Handler)

Patch registers an http PATCH method receiver with the provided Handler

func (*Router) PatchFunc

func (r *Router) PatchFunc(pattern string, fn HandlerFunc)

PatchFunc wraps a HandlerFunc as a Handler and registers it to the router

func (*Router) PatchH

func (r *Router) PatchH(pattern string, handler http.Handler)

PatchH wraps a http.Handler

func (*Router) Post

func (r *Router) Post(pattern string, handler Handler)

Post registers an http POST method receiver with the provided Handler

func (*Router) PostFunc

func (r *Router) PostFunc(pattern string, fn HandlerFunc)

PostFunc wraps a HandlerFunc as a Handler and registers it to the router

func (*Router) PostH

func (r *Router) PostH(pattern string, handler http.Handler)

PostH wraps a http.Handler

func (*Router) Put

func (r *Router) Put(pattern string, handler Handler)

Put registers an http PUT method receiver with the provided Handler

func (*Router) PutFunc

func (r *Router) PutFunc(pattern string, fn HandlerFunc)

PutFunc wraps a HandlerFunc as a Handler and registers it to the router

func (*Router) PutH

func (r *Router) PutH(pattern string, handler http.Handler)

PutH wraps a http.Handler

func (*Router) Resource

func (r *Router) Resource(pattern string, resource Resource)

Resource registers a Resource with the corresponding pattern

func (*Router) Run

func (r *Router) Run(addr ...string)

Run calls http.ListenAndServe for the current router. If no addresses are specified as arguments, it will use the PORT environnement variable if it is defined. Otherwise, it will listen on port 3000 of the localmachine

r := New()
r.Run() // will call
r.Run(":8080")

func (*Router) RunTLS

func (r *Router) RunTLS(addr, certFile, keyFile string)

RunTLS calls http.ListenAndServeTLS for the current router

r := New()
r.RunTLS(":3443", "cert.pem", "key.pem")

func (*Router) ServeFile

func (r *Router) ServeFile(base, path string)

ServeFile serve a specific file located at the passed path

l := New()
l.ServeFile("/robots.txt", "path/to/robots.txt")

func (*Router) ServeFiles

func (r *Router) ServeFiles(base string, root http.FileSystem)

ServeFiles serves files located in root http.FileSystem

This can be used as shown below:

r := New()
r.ServeFiles("/static", http.Dir("static")) // This will serve files in the directory static with /static prefix

func (*Router) ServeHTTP

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

ServeHTTP calls ServeHTTPC with a context.Background()

func (*Router) ServeHTTPC

func (r *Router) ServeHTTPC(c context.Context, w http.ResponseWriter, req *http.Request)

ServeHTTPC finds the handler associated with the request's path. If it is not found it calls the NotFound handler

func (*Router) Subrouter

func (r *Router) Subrouter(mws ...Middleware) *Router

Subrouter creates a new router based on the parent router.

A subrouter has the same pattern and host as the parent router. It has it's own middlewares.

func (*Router) Trace

func (r *Router) Trace(pattern string, handler Handler)

Trace registers an http TRACE method receiver with the provided Handler

func (*Router) TraceFunc

func (r *Router) TraceFunc(pattern string, fn HandlerFunc)

TraceFunc wraps a HandlerFunc as a Handler and registers it to the router

func (*Router) TraceH

func (r *Router) TraceH(pattern string, handler http.Handler)

TraceH wraps a http.Handler

func (*Router) Use

func (r *Router) Use(middlewares ...Middleware)

Use registers middlewares to be used

func (*Router) UseFunc

func (r *Router) UseFunc(middlewareFuncs ...MiddlewareFunc)

UseFunc wraps a MiddlewareFunc as a Middleware and registers it middlewares to be used

func (*Router) UseHandler

func (r *Router) UseHandler(handler Handler)

UseHandler gives the ability to add and serve a Handler and serve the next handler

func (*Router) UseHandlerFunc

func (r *Router) UseHandlerFunc(fn HandlerFunc)

UseHandlerFunc is a convenience wrapper for UseHandler

func (*Router) UseNamed

func (r *Router) UseNamed(name string)

UseNamed adds a middleware already defined using Define method. If it cannot find it in the current router, it will look for it in the parent router.

func (*Router) UseNegroni

func (r *Router) UseNegroni(n negroniHandler)

UseNegroni gives the ability to use Negroni.Handler middlewares as lion.Middlewares

func (*Router) UseNegroniFunc

func (r *Router) UseNegroniFunc(n func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc))

UseNegroniFunc is a convenience wrapper for UseNegroni to Negroni.HandlerFunc

type Static

type Static struct {
	// Dir is the directory to serve static files from
	Dir http.FileSystem
	// Prefix is the optional prefix used to serve the static directory content
	Prefix string
	// IndexFile defines which file to serve as index if it exists.
	IndexFile string
}

Static is a middleware handler that serves static files in the given directory/filesystem. Taken from https://github.com/codegangsta/negroni/blob/master/static.go

func NewStatic

func NewStatic(directory http.FileSystem) *Static

NewStatic returns a new instance of Static

func (*Static) ServeNext

func (s *Static) ServeNext(next Handler) Handler

ServeNext tries to find a file in the directory

type TraceResource

type TraceResource interface {
	Trace(c context.Context, w http.ResponseWriter, r *http.Request)
}

TraceResource is an interface for defining a HandlerFunc used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

type TraceResourceMiddlewares

type TraceResourceMiddlewares interface {
	TraceMiddlewares() Middlewares
}

TraceResourceMiddlewares is an interface for defining middlewares used in Resource method DEPRECATED: These methods will be removed in v2. This should not cause problems since they are already publicly exposed for documentation purpose only.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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