middleware.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 (c *Context) GetAccountId() int {
  18. return c.Account.Id
  19. }
  20. func GetContextHandler() macaron.Handler {
  21. return func(c *macaron.Context, sess session.Store) {
  22. ctx := &Context{
  23. Context: c,
  24. Session: sess,
  25. }
  26. c.Map(ctx)
  27. }
  28. }
  29. // Handle handles and logs error by given status.
  30. func (ctx *Context) Handle(status int, title string, err error) {
  31. if err != nil {
  32. log.Error(4, "%s: %v", title, err)
  33. if macaron.Env != macaron.PROD {
  34. ctx.Data["ErrorMsg"] = err
  35. }
  36. }
  37. switch status {
  38. case 404:
  39. ctx.Data["Title"] = "Page Not Found"
  40. case 500:
  41. ctx.Data["Title"] = "Internal Server Error"
  42. }
  43. ctx.HTML(status, "index")
  44. }
  45. func (ctx *Context) ApiError(status int, message string, err error) {
  46. resp := make(map[string]interface{})
  47. if err != nil {
  48. log.Error(4, "%s: %v", message, err)
  49. if macaron.Env != macaron.PROD {
  50. resp["error"] = err
  51. }
  52. }
  53. switch status {
  54. case 404:
  55. resp["message"] = "Not Found"
  56. case 500:
  57. resp["message"] = "Internal Server Error"
  58. }
  59. if message != "" {
  60. resp["message"] = message
  61. }
  62. ctx.HTML(status, "index")
  63. }
  64. func (ctx *Context) JsonBody(model interface{}) bool {
  65. b, _ := ioutil.ReadAll(ctx.Req.Body)
  66. err := json.Unmarshal(b, &model)
  67. return err == nil
  68. }