package web import ( "fmt" "net/http" "gitlab.quimbo.fr/odwrtw/canape-sql/auth" "github.com/Sirupsen/logrus" "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 } // Handler create a new handler func (e *Env) Handler(H func(e *Env, w http.ResponseWriter, r *http.Request) error) Handler { return 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) } } // InternalError create a internal error func InternalError(err error) error { return nil }