github.com/ashleymcnamara/buffalo@v0.8.0/handler.go (about) 1 package buffalo 2 3 import ( 4 "net/http" 5 6 "github.com/gorilla/mux" 7 "github.com/pkg/errors" 8 ) 9 10 // Handler is the basis for all of Buffalo. A Handler 11 // will be given a Context interface that represents the 12 // give request/response. It is the responsibility of the 13 // Handler to handle the request/response correctly. This 14 // could mean rendering a template, JSON, etc... or it could 15 // mean returning an error. 16 /* 17 func (c Context) error { 18 return c.Render(200, render.String("Hello World!")) 19 } 20 21 func (c Context) error { 22 return c.Redirect(301, "http://github.com/gobuffalo/buffalo") 23 } 24 25 func (c Context) error { 26 return c.Error(422, errors.New("oops!!")) 27 } 28 */ 29 type Handler func(Context) error 30 31 func (a *App) newContext(info RouteInfo, res http.ResponseWriter, req *http.Request) Context { 32 ws := res.(*buffaloResponse) 33 params := req.URL.Query() 34 vars := mux.Vars(req) 35 for k, v := range vars { 36 params.Set(k, v) 37 } 38 39 session := a.getSession(req, ws) 40 41 return &DefaultContext{ 42 Context: req.Context(), 43 response: ws, 44 request: req, 45 params: params, 46 logger: a.Logger, 47 session: session, 48 flash: newFlash(session), 49 data: map[string]interface{}{ 50 "env": a.Env, 51 "routes": a.Routes(), 52 "current_route": info, 53 "current_path": req.URL.Path, 54 }, 55 } 56 } 57 58 func (a *App) handlerToHandler(info RouteInfo, h Handler) http.Handler { 59 hf := func(res http.ResponseWriter, req *http.Request) { 60 c := a.newContext(info, res, req) 61 62 defer c.Flash().persist(c.Session()) 63 64 err := a.Middleware.handler(h)(c) 65 66 if err != nil { 67 status := 500 68 // unpack root cause and check for HTTPError 69 cause := errors.Cause(err) 70 httpError, ok := cause.(HTTPError) 71 if ok { 72 status = httpError.Status 73 } 74 eh := a.ErrorHandlers.Get(status) 75 err = eh(status, err, c) 76 if err != nil { 77 // things have really hit the fan if we're here!! 78 a.Logger.Error(err) 79 c.Response().WriteHeader(500) 80 c.Response().Write([]byte(err.Error())) 81 } 82 // err := c.Error(500, err) 83 // a.Logger.Error(err) 84 } 85 } 86 return http.HandlerFunc(hf) 87 }