lion
v0.0.0-20191115102631-69ee5db2c99e
Documentation
pkg.go.dev ↗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")
Constants
GET (9 declarations)
const ( GET = "GET" HEAD = "HEAD" POST = "POST" PUT = "PUT" DELETE = "DELETE" TRACE = "TRACE" OPTIONS = "OPTIONS" CONNECT = "CONNECT" PATCH = "PATCH" )
HTTP methods constants
Variables
ErrInvalidRedirectStatusCode
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
Param
func Param(req *http.Request, key string) string
Param returns the value of a url param base on the passed context
Types
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.
C
func C(req *http.Request) 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.
HTTPError
type HTTPError interface {
error
Status() int
}
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
ErrorBadRequest (6 declarations)
var (
// ErrorBadRequest returns a BadRequest response with the corresponding body
ErrorBadRequest HTTPError = httpError{http.StatusBadRequest}
// ErrorUnauthorized returns a Unauthorized response with the corresponding body
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}
)
Middleware
type Middleware interface {
ServeNext(http.Handler) http.Handler
}
Middleware interface that takes as input a Handler and returns a Handler
MiddlewareFunc
type MiddlewareFunc func(http.Handler) http.Handler
MiddlewareFunc wraps a function that takes as input a Handler and returns a Handler. So that it implements the Middlewares interface
MiddlewareFunc.ServeNext
func (m MiddlewareFunc) ServeNext(next http.Handler) http.Handler
ServeNext makes MiddlewareFunc implement Middleware
Middlewares
type Middlewares []Middleware
Middlewares is an array of Middleware
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
Middlewares.ServeNext
func (middlewares Middlewares) ServeNext(next http.Handler) http.Handler
ServeNext allows Middlewares to implement the Middleware interface. This is useful to allow Grouping middlewares together and being able to use them as a single Middleware.
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.
Resource
type Resource interface{}
Resource defines the minimum required methods
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.
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"
Router
type Router struct {
// contains filtered or unexported fields
}
Router is the main component of Lion. It is responsible for registering handlers and middlewares
New
func New(mws ...Middleware) *Router
New creates a new router instance
Router.ANY
func (r *Router) ANY(pattern string, handler func(Context)) Route
ANY registers the provided contextual Handler for all of the allowed http methods: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH
Router.Any
func (r *Router) Any(pattern string, handler http.Handler) Route
Any registers the provided Handler for all of the allowed http methods: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH
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
Router.CONNECT
func (r *Router) CONNECT(pattern string, handler func(Context)) Route
CONNECT registers an http CONNECT method receiver with the provided contextual Handler
Router.Configure
func (r *Router) Configure(opts ...RouterOption)
Configure allows you to customize a Router using RouterOption
Router.Connect
func (r *Router) Connect(pattern string, handler http.Handler) Route
Connect registers an http CONNECT method receiver with the provided Handler
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
Router.DELETE
func (r *Router) DELETE(pattern string, handler func(Context)) Route
DELETE registers an http DELETE method receiver with the provided contextual Handler
Router.Define
func (r *Router) Define(name string, mws ...Middleware)
Define registers some middleware using a name for reuse later using UseNamed method.
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
Router.Delete
func (r *Router) Delete(pattern string, handler http.Handler) Route
Delete registers an http DELETE method receiver with the provided Handler
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
Router.GET
func (r *Router) GET(pattern string, handler func(Context)) Route
GET registers an http GET method receiver with the provided contextual Handler
Router.Get
func (r *Router) Get(pattern string, handler http.Handler) Route
Get registers an http GET method receiver with the provided Handler
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
Router.Group
func (r *Router) Group(pattern string, mws ...Middleware) *Router
Group creates a subrouter with parent pattern provided.
Router.HEAD
func (r *Router) HEAD(pattern string, handler func(Context)) Route
HEAD registers an http HEAD method receiver with the provided contextual Handler
Router.Handle
func (r *Router) Handle(method, pattern string, handler http.Handler) Route
Handle is the underling method responsible for registering a handler for a specific method and pattern.
Router.HandleFunc
func (r *Router) HandleFunc(method, pattern string, fn http.HandlerFunc) Route
HandleFunc wraps a HandlerFunc and pass it to Handle method
Router.Head
func (r *Router) Head(pattern string, handler http.Handler) Route
Head registers an http HEAD method receiver with the provided Handler
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
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.* *
Router.Module
func (r *Router) Module(modules ...Module)
Module register modules for the current router instance.
Router.Mount
func (r *Router) Mount(pattern string, sub *Router, mws ...Middleware)
Mount mounts a subrouter at the provided pattern
Router.OPTIONS
func (r *Router) OPTIONS(pattern string, handler func(Context)) Route
OPTIONS registers an http OPTIONS method receiver with the provided contextual Handler
Router.Options
func (r *Router) Options(pattern string, handler http.Handler) Route
Options registers an http OPTIONS method receiver with the provided Handler
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
Router.PATCH
func (r *Router) PATCH(pattern string, handler func(Context)) Route
PATCH registers an http PATCH method receiver with the provided contextual Handler
Router.POST
func (r *Router) POST(pattern string, handler func(Context)) Route
POST registers an http POST method receiver with the provided contextual Handler
Router.PUT
func (r *Router) PUT(pattern string, handler func(Context)) Route
PUT registers an http PUT method receiver with the provided contextual Handler
Router.Patch
func (r *Router) Patch(pattern string, handler http.Handler) Route
Patch registers an http PATCH method receiver with the provided Handler
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
Router.Post
func (r *Router) Post(pattern string, handler http.Handler) Route
Post registers an http POST method receiver with the provided Handler
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
Router.Put
func (r *Router) Put(pattern string, handler http.Handler) Route
Put registers an http PUT method receiver with the provided Handler
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
Router.Resource
func (r *Router) Resource(pattern string, resource Resource)
Resource registers a Resource with the corresponding pattern
Router.Route
func (r *Router) Route(name string) 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.
Router.Routes
func (r *Router) Routes() Routes
Routes returns the Routes associated with the current Router instance.
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")
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")
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")
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
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
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.
Router.TRACE
func (r *Router) TRACE(pattern string, handler func(Context)) Route
TRACE registers an http TRACE method receiver with the provided contextual Handler
Router.Trace
func (r *Router) Trace(pattern string, handler http.Handler) Route
Trace registers an http TRACE method receiver with the provided Handler
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
Router.USE
func (r *Router) USE(middlewares ...func(func(Context)) func(Context))
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.
Router.Use
func (r *Router) Use(middlewares ...Middleware)
Use registers middlewares to be used
Router.UseFunc
func (r *Router) UseFunc(middlewareFuncs ...MiddlewareFunc)
UseFunc wraps a MiddlewareFunc as a Middleware and registers it middlewares to be used
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.
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.
RouterOption
type RouterOption func(*Router)
RouterOption configure a Router
WithLogger
func WithLogger(logger *log.Logger) RouterOption
WithLogger allows to customize the underlying logger
WithNotFoundHandler
func WithNotFoundHandler(h http.Handler) RouterOption
WithNotFoundHandler override the default not found handler
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
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
Routes.ByName
func (rs Routes) ByName(name string) Route
ByName returns the route corresponding to the name given. It returns nil otherwise.
Routes.ByPattern
func (rs Routes) ByPattern(pattern string) Route
ByPattern returns the route corresponding to the pattern given. It returns nil otherwise.
Routes.String
func (rs Routes) String() string
String returns a string representation of a list of routes.