middleware.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package middleware
  2. import (
  3. "encoding/json"
  4. "strconv"
  5. "strings"
  6. "github.com/Unknwon/macaron"
  7. "github.com/macaron-contrib/session"
  8. "github.com/torkelo/grafana-pro/pkg/log"
  9. "github.com/torkelo/grafana-pro/pkg/models"
  10. "github.com/torkelo/grafana-pro/pkg/setting"
  11. )
  12. type Context struct {
  13. *macaron.Context
  14. Session session.Store
  15. Account *models.Account
  16. UserAccount *models.Account
  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) IsApiRequest() bool {
  52. return strings.HasPrefix(ctx.Req.URL.Path, "/api")
  53. }
  54. func (ctx *Context) JsonApiErr(status int, message string, err error) {
  55. resp := make(map[string]interface{})
  56. if err != nil {
  57. log.Error(4, "%s: %v", message, err)
  58. if setting.Env != setting.PROD {
  59. resp["error"] = err.Error()
  60. }
  61. }
  62. switch status {
  63. case 404:
  64. resp["message"] = "Not Found"
  65. case 500:
  66. resp["message"] = "Internal Server Error"
  67. }
  68. if message != "" {
  69. resp["message"] = message
  70. }
  71. ctx.JSON(status, resp)
  72. }
  73. func (ctx *Context) JsonBody(model interface{}) bool {
  74. b, _ := ctx.Req.Body().Bytes()
  75. err := json.Unmarshal(b, &model)
  76. return err == nil
  77. }