middleware.go 1.6 KB

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