middleware.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package middleware
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "github.com/Unknwon/macaron"
  6. "github.com/macaron-contrib/session"
  7. "github.com/torkelo/grafana-pro/pkg/log"
  8. "github.com/torkelo/grafana-pro/pkg/models"
  9. )
  10. type Context struct {
  11. *macaron.Context
  12. Session session.Store
  13. Account *models.Account
  14. UserAccount *models.Account
  15. IsSigned bool
  16. }
  17. func GetContextHandler() macaron.Handler {
  18. return func(c *macaron.Context, sess session.Store) {
  19. ctx := &Context{
  20. Context: c,
  21. Session: sess,
  22. }
  23. c.Map(ctx)
  24. }
  25. }
  26. // Handle handles and logs error by given status.
  27. func (ctx *Context) Handle(status int, title string, err error) {
  28. if err != nil {
  29. log.Error(4, "%s: %v", title, err)
  30. if macaron.Env != macaron.PROD {
  31. ctx.Data["ErrorMsg"] = err
  32. }
  33. }
  34. switch status {
  35. case 404:
  36. ctx.Data["Title"] = "Page Not Found"
  37. case 500:
  38. ctx.Data["Title"] = "Internal Server Error"
  39. }
  40. ctx.HTML(status, "index")
  41. }
  42. func (ctx *Context) JsonBody(model interface{}) bool {
  43. b, _ := ioutil.ReadAll(ctx.Req.Body)
  44. err := json.Unmarshal(b, &model)
  45. return err == nil
  46. }