middleware.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package middleware
  2. import (
  3. "encoding/json"
  4. "strconv"
  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. "github.com/torkelo/grafana-pro/pkg/setting"
  10. )
  11. type Context struct {
  12. *macaron.Context
  13. Session session.Store
  14. Account *models.Account
  15. UserAccount *models.Account
  16. }
  17. func (c *Context) GetAccountId() int64 {
  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, strconv.Itoa(status))
  44. }
  45. func (ctx *Context) JsonOK(message string) {
  46. resp := make(map[string]interface{})
  47. resp["message"] = message
  48. ctx.JSON(200, resp)
  49. }
  50. func (ctx *Context) JsonApiErr(status int, message string, err error) {
  51. resp := make(map[string]interface{})
  52. if err != nil {
  53. log.Error(4, "%s: %v", message, err)
  54. if setting.Env != setting.PROD {
  55. resp["error"] = err.Error()
  56. }
  57. }
  58. switch status {
  59. case 404:
  60. resp["message"] = "Not Found"
  61. case 500:
  62. resp["message"] = "Internal Server Error"
  63. }
  64. if message != "" {
  65. resp["message"] = message
  66. }
  67. ctx.JSON(status, resp)
  68. }
  69. func (ctx *Context) JsonBody(model interface{}) bool {
  70. b, _ := ctx.Req.Body().Bytes()
  71. err := json.Unmarshal(b, &model)
  72. return err == nil
  73. }