middleware.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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) JsonOK(message string) {
  47. resp := make(map[string]interface{})
  48. resp["message"] = message
  49. ctx.JSON(200, resp)
  50. }
  51. func (ctx *Context) JsonApiErr(status int, message string, err error) {
  52. resp := make(map[string]interface{})
  53. if err != nil {
  54. log.Error(4, "%s: %v", message, err)
  55. if setting.Env != setting.PROD {
  56. resp["error"] = err.Error()
  57. }
  58. }
  59. switch status {
  60. case 404:
  61. resp["message"] = "Not Found"
  62. case 500:
  63. resp["message"] = "Internal Server Error"
  64. }
  65. if message != "" {
  66. resp["message"] = message
  67. }
  68. ctx.JSON(status, resp)
  69. }
  70. func (ctx *Context) JsonBody(model interface{}) bool {
  71. b, _ := ctx.Req.Body().Bytes()
  72. err := json.Unmarshal(b, &model)
  73. return err == nil
  74. }