97 lines
2.3 KiB
Go
97 lines
2.3 KiB
Go
package web
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"gitlab.quimbo.fr/odwrtw/canape-sql/auth"
|
|
|
|
"github.com/Sirupsen/logrus"
|
|
"github.com/codegangsta/negroni"
|
|
"github.com/gorilla/mux"
|
|
"github.com/jmoiron/sqlx"
|
|
"github.com/unrolled/render"
|
|
)
|
|
|
|
type Mode string
|
|
|
|
const (
|
|
ProductionMode Mode = "production"
|
|
DeveloppementMode = "developpement"
|
|
TestMode = "test"
|
|
)
|
|
|
|
// Env describes an environement object passed to all handlers
|
|
type Env struct {
|
|
Database *sqlx.DB
|
|
Log *logrus.Entry
|
|
Router *mux.Router
|
|
Render *render.Render
|
|
Auth *auth.Authorizer
|
|
Mode Mode
|
|
}
|
|
|
|
// NewEnv returns a new *Env
|
|
func NewEnv(db *sqlx.DB, auth *auth.Authorizer, log *logrus.Entry, templatesDir string) *Env {
|
|
return &Env{
|
|
Database: db,
|
|
Log: log,
|
|
Router: mux.NewRouter(),
|
|
Render: render.New(render.Options{
|
|
Directory: templatesDir,
|
|
Layout: "layout",
|
|
Funcs: tmplFuncs,
|
|
DisableHTTPErrorRendering: true,
|
|
RequirePartials: true,
|
|
}),
|
|
Auth: auth,
|
|
Mode: ProductionMode,
|
|
}
|
|
}
|
|
|
|
// GetURL returns URL string from URL name and params
|
|
// Usefull for redirection and templates
|
|
func (e *Env) GetURL(name string, pairs ...string) (string, error) {
|
|
route := e.Router.Get(name)
|
|
if route == nil {
|
|
return "", fmt.Errorf("No route find for the given name: %s", name)
|
|
}
|
|
URL, err := route.URL(pairs...)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return URL.String(), nil
|
|
}
|
|
|
|
type HandlerFunc func(e *Env, w http.ResponseWriter, r *http.Request) error
|
|
|
|
func (e *Env) Handle(name, route string, H HandlerFunc) {
|
|
e.Router.Handle(route, Handler{e, H})
|
|
}
|
|
|
|
func (e *Env) HandleRole(name, route string, H HandlerFunc, role string) {
|
|
e.Router.Handle(route, negroni.New(
|
|
auth.NewMiddlewareRole(e.Auth, role),
|
|
negroni.Wrap(Handler{e, H}),
|
|
))
|
|
}
|
|
|
|
// The Handler struct that takes a configured Env and a function matching our
|
|
// handler signature
|
|
type Handler struct {
|
|
*Env
|
|
H func(e *Env, w http.ResponseWriter, r *http.Request) error
|
|
}
|
|
|
|
// ServeHTTP allows our Handler type to satisfy http.Handler.
|
|
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
err := h.H(h.Env, w, r)
|
|
if err != nil {
|
|
// Any error types we don't specifically look out for default
|
|
// to serving a HTTP 500
|
|
h.Env.Log.Errorf(err.Error())
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError),
|
|
http.StatusInternalServerError)
|
|
}
|
|
}
|