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" "context" ) func Home(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Home") } func Hello(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
- Variables
- func Param(req *http.Request, key string) string
- type Context
- type HTTPError
- type Middleware
- type MiddlewareFunc
- type Middlewares
- type Module
- type Resource
- type Route
- type RoutePathBuilder
- type Router
- func (r *Router) ANY(pattern string, handler func(Context)) Route
- func (r *Router) Any(pattern string, handler http.Handler) Route
- func (r *Router) AnyFunc(pattern string, handler http.HandlerFunc) Route
- func (r *Router) CONNECT(pattern string, handler func(Context)) Route
- func (r *Router) Configure(opts ...RouterOption)
- func (r *Router) Connect(pattern string, handler http.Handler) Route
- func (r *Router) ConnectFunc(pattern string, fn http.HandlerFunc) Route
- func (r *Router) DELETE(pattern string, handler func(Context)) Route
- func (r *Router) Define(name string, mws ...Middleware)
- func (r *Router) DefineFunc(name string, mws ...MiddlewareFunc)
- func (r *Router) Delete(pattern string, handler http.Handler) Route
- func (r *Router) DeleteFunc(pattern string, fn http.HandlerFunc) Route
- func (r *Router) GET(pattern string, handler func(Context)) Route
- func (r *Router) Get(pattern string, handler http.Handler) Route
- func (r *Router) GetFunc(pattern string, fn http.HandlerFunc) Route
- func (r *Router) Group(pattern string, mws ...Middleware) *Router
- func (r *Router) HEAD(pattern string, handler func(Context)) Route
- func (r *Router) Handle(method, pattern string, handler http.Handler) Route
- func (r *Router) HandleFunc(method, pattern string, fn http.HandlerFunc) Route
- func (r *Router) Head(pattern string, handler http.Handler) Route
- func (r *Router) HeadFunc(pattern string, fn http.HandlerFunc) Route
- func (r *Router) Host(hostpattern string) *Router
- func (r *Router) Module(modules ...Module)
- func (r *Router) Mount(pattern string, sub *Router, mws ...Middleware)
- func (r *Router) OPTIONS(pattern string, handler func(Context)) Route
- func (r *Router) Options(pattern string, handler http.Handler) Route
- func (r *Router) OptionsFunc(pattern string, fn http.HandlerFunc) Route
- func (r *Router) PATCH(pattern string, handler func(Context)) Route
- func (r *Router) POST(pattern string, handler func(Context)) Route
- func (r *Router) PUT(pattern string, handler func(Context)) Route
- func (r *Router) Patch(pattern string, handler http.Handler) Route
- func (r *Router) PatchFunc(pattern string, fn http.HandlerFunc) Route
- func (r *Router) Post(pattern string, handler http.Handler) Route
- func (r *Router) PostFunc(pattern string, fn http.HandlerFunc) Route
- func (r *Router) Put(pattern string, handler http.Handler) Route
- func (r *Router) PutFunc(pattern string, fn http.HandlerFunc) Route
- func (r *Router) Resource(pattern string, resource Resource)
- func (r *Router) Route(name string) Route
- func (r *Router) Routes() Routes
- func (r *Router) Run(addr ...string)
- func (r *Router) RunTLS(addr, certFile, keyFile string)
- func (r *Router) ServeFile(base, path string)
- func (r *Router) ServeFiles(base string, root http.FileSystem)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) Subrouter(mws ...Middleware) *Router
- func (r *Router) TRACE(pattern string, handler func(Context)) Route
- func (r *Router) Trace(pattern string, handler http.Handler) Route
- func (r *Router) TraceFunc(pattern string, fn http.HandlerFunc) Route
- func (r *Router) USE(middlewares ...func(func(Context)) func(Context))
- func (r *Router) Use(middlewares ...Middleware)
- func (r *Router) UseFunc(middlewareFuncs ...MiddlewareFunc)
- func (r *Router) UseNamed(name string)
- func (r *Router) UseNext(funcs ...func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc))
- type RouterOption
- type Routes
Constants ¶
const ( GET = "GET" HEAD = "HEAD" POST = "POST" PUT = "PUT" DELETE = "DELETE" TRACE = "TRACE" OPTIONS = "OPTIONS" CONNECT = "CONNECT" PATCH = "PATCH" )
HTTP methods constants
Variables ¶
var ( // ErrInvalidRedirectStatusCode is used to notify when an invalid redirect status code is used on Context.Redirect() ErrInvalidRedirectStatusCode = errors.New("Invalid redirect status code") )
Functions ¶
Types ¶
type Context ¶
type Context interface { context.Context http.ResponseWriter Param(key string) string ParamOk(key string) (string, bool) Clone() Context Request() *http.Request // Request Cookie(name string) (*http.Cookie, error) Query(name string) string GetHeader(key string) string // Response WithStatus(code int) Context WithHeader(key, value string) Context WithCookie(cookie *http.Cookie) Context // Rendering JSON(data interface{}) error XML(data interface{}) error String(format string, a ...interface{}) error Error(err error) error File(path string) error Attachment(path, filename string) error Redirect(urlStr string) error }
Context is used to store url params and is a convinient utility to read informations from the current *http.Request and render to the current http.ResponseWriter. It implements the http.ResponseWriter interface.
type HTTPError ¶
HTTPError allows to write an error to http.ResponseWriter. You can use it with Context. Like in the following example:
func(c lion.Context) { c.Error(lion.ErrorUnauthorized) }
This will return a response with status code 401 and a body of "Unauthorized". Check below for the available http error
var ( // ErrorBadRequest returns a BadRequest response with the corresponding body ErrorBadRequest HTTPError = httpError{http.StatusBadRequest} ErrorUnauthorized HTTPError = httpError{http.StatusUnauthorized} // ErrorForbidden returns a Forbidden response with the corresponding body ErrorForbidden HTTPError = httpError{http.StatusForbidden} // ErrorNotFound returns a NotFound response with the corresponding body ErrorNotFound HTTPError = httpError{http.StatusNotFound} // ErrorMethodNotAllowed returns a MethodNotAllowed response with the corresponding body ErrorMethodNotAllowed HTTPError = httpError{http.StatusMethodNotAllowed} // ErrorInternalServer returns a InternalServerError response with the corresponding body ErrorInternalServer HTTPError = httpError{http.StatusInternalServerError} )
type Middleware ¶
Middleware interface that takes as input a Handler and returns a Handler
type MiddlewareFunc ¶
MiddlewareFunc wraps a function that takes as input a Handler and returns a Handler. So that it implements the Middlewares interface
type Middlewares ¶
type Middlewares []Middleware
Middlewares is an array of Middleware
func (Middlewares) BuildHandler ¶
func (middlewares Middlewares) BuildHandler(handler http.Handler) http.Handler
BuildHandler builds a chain of middlewares from a passed Handler and returns a Handler
type Module ¶
Module represent an independent router entity. It should be used to group routes and subroutes together.
type Route ¶
type Route interface { // WithName allows to specify a name for the current route WithName(name string) Route // Methods returns the http methods set for the current route Methods() (methods []string) // Host returns the host set Host() string // Name returns the name set for the current route Name() string // Pattern returns the underlying pattern for the route Pattern() string // Handler return the according http.Handler for the method specified // The returned handler is already built using the middlewares in *Router Handler(method string) http.Handler // Path returns a path with the provided params. // If any of the params is missing this function will return an error. Path(params map[string]string) (string, error) // Build allows you to build params by params. // For example: route.Build().WithParam("id", "123").WithParam("post_id", "456") Build() RoutePathBuilder // Convenient alias for Build().WithParam() // Calling this method will create a new RoutePathBuilder WithParam(key, value string) RoutePathBuilder }
Route defines a single route registered in your Router. A Route corresponds to the pattern and host given. It contains the handlers for each HTTP methods.
type RoutePathBuilder ¶
type RoutePathBuilder interface { WithParam(key, value string) RoutePathBuilder Path() (string, error) }
RoutePathBuilder is a convenient utility to build path given each url parameters. Here is a simple example usage.
router := New() route := router.Get("/posts/:user", postsHandler) path := route.Build().WithParam("user", "123") // path should be equal to "/posts/123"
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 (*Router) ANY ¶
ANY registers the provided contextual Handler for all of the allowed http methods: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH
func (*Router) Any ¶
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 http.HandlerFunc) Route
AnyFunc registers the provided HandlerFunc for all of the allowed http methods: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH
func (*Router) CONNECT ¶
CONNECT registers an http CONNECT method receiver with the provided contextual Handler
func (*Router) Configure ¶
func (r *Router) Configure(opts ...RouterOption)
Configure allows you to customize a Router using RouterOption
func (*Router) Connect ¶
Connect registers an http CONNECT method receiver with the provided Handler
func (*Router) ConnectFunc ¶
func (r *Router) ConnectFunc(pattern string, fn http.HandlerFunc) Route
ConnectFunc wraps a HandlerFunc as a Handler and registers it to the router
func (*Router) DELETE ¶
DELETE registers an http DELETE method receiver with the provided contextual 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) DeleteFunc ¶
func (r *Router) DeleteFunc(pattern string, fn http.HandlerFunc) Route
DeleteFunc wraps a HandlerFunc as a Handler and registers it to the router
func (*Router) GetFunc ¶
func (r *Router) GetFunc(pattern string, fn http.HandlerFunc) Route
GetFunc wraps a HandlerFunc as a Handler and registers it to the router
func (*Router) Group ¶
func (r *Router) Group(pattern string, mws ...Middleware) *Router
Group creates a subrouter with parent pattern provided.
func (*Router) HEAD ¶
HEAD registers an http HEAD method receiver with the provided contextual Handler
func (*Router) Handle ¶
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 http.HandlerFunc) Route
HandleFunc wraps a HandlerFunc and pass it to Handle method
func (*Router) HeadFunc ¶
func (r *Router) HeadFunc(pattern string, fn http.HandlerFunc) Route
HeadFunc wraps a HandlerFunc as a Handler and registers it to the router
func (*Router) Host ¶
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) Mount ¶
func (r *Router) Mount(pattern string, sub *Router, mws ...Middleware)
Mount mounts a subrouter at the provided pattern
func (*Router) OPTIONS ¶
OPTIONS registers an http OPTIONS method receiver with the provided contextual Handler
func (*Router) Options ¶
Options registers an http OPTIONS method receiver with the provided Handler
func (*Router) OptionsFunc ¶
func (r *Router) OptionsFunc(pattern string, fn http.HandlerFunc) Route
OptionsFunc wraps a HandlerFunc as a Handler and registers it to the router
func (*Router) PATCH ¶
PATCH registers an http PATCH method receiver with the provided contextual Handler
func (*Router) POST ¶
POST registers an http POST method receiver with the provided contextual Handler
func (*Router) PatchFunc ¶
func (r *Router) PatchFunc(pattern string, fn http.HandlerFunc) Route
PatchFunc wraps a HandlerFunc as a Handler and registers it to the router
func (*Router) PostFunc ¶
func (r *Router) PostFunc(pattern string, fn http.HandlerFunc) Route
PostFunc wraps a HandlerFunc as a Handler and registers it to the router
func (*Router) PutFunc ¶
func (r *Router) PutFunc(pattern string, fn http.HandlerFunc) Route
PutFunc wraps a HandlerFunc as a Handler and registers it to the router
func (*Router) Route ¶
Route get the Route associated with the name specified. Each Route corresponds to a pattern and a host registered.
GET host1.org/users POST host1.org/users
share the same Route. If you want to get the http.Handler for a specific HTTP method, please refer to Route.Handler(method) method.
func (*Router) Run ¶
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 ¶
RunTLS calls http.ListenAndServeTLS for the current router
r := New() r.RunTLS(":3443", "cert.pem", "key.pem")
func (*Router) ServeFile ¶
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 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 ¶
TRACE registers an http TRACE method receiver with the provided contextual Handler
func (*Router) TraceFunc ¶
func (r *Router) TraceFunc(pattern string, fn http.HandlerFunc) Route
TraceFunc wraps a HandlerFunc as a Handler and registers it to the router
func (*Router) USE ¶
USE allows you to use contextual middlewares. Example:
router.USE(func (next func(Context)) func(Context) { return func(c Context) { if c.GetHeader("Authorization") == "" { c.Error(lion.ErrorUnauthorized) return } next(c) } })
This will return an HTTP 401 Unauthorized response if the "Authorization" header is set. Otherwise, it will continue to next middleware.
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) UseNamed ¶
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) UseNext ¶
func (r *Router) UseNext(funcs ...func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc))
UseNext allows to use middlewares with the following form: func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) Previously named: UseNegroniFunc. This can be useful if you want to use negroni style middleware or a middleware already built by the community.
type RouterOption ¶
type RouterOption func(*Router)
RouterOption configure a Router
func WithLogger ¶
func WithLogger(logger *log.Logger) RouterOption
WithLogger allows to customize the underlying logger
func WithNotFoundHandler ¶
func WithNotFoundHandler(h http.Handler) RouterOption
WithNotFoundHandler override the default not found handler
func WithServer ¶
func WithServer(server *http.Server) RouterOption
WithServer allows to customize the underlying http.Server Note: when using Run() the handler and the address will change
type Routes ¶
type Routes []Route
Routes is an slice of Route. Check Routes.ByName or Routes.ByPattern to find out if it is useful to you
func (Routes) ByName ¶
ByName returns the route corresponding to the name given. It returns nil otherwise.