base_common.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "eta/eta_report/models"
  5. "eta/eta_report/services"
  6. "eta/eta_report/utils"
  7. "github.com/beego/beego/v2/server/web"
  8. "net/http"
  9. )
  10. type BaseCommonController struct {
  11. web.Controller
  12. Token string
  13. }
  14. func (this *BaseCommonController) Prepare() {
  15. }
  16. func (c *BaseCommonController) ServeJSON(encoding ...bool) {
  17. var (
  18. hasIndent = false
  19. hasEncoding = false
  20. )
  21. if web.BConfig.RunMode == web.PROD {
  22. hasIndent = false
  23. }
  24. if len(encoding) > 0 && encoding[0] == true {
  25. hasEncoding = true
  26. }
  27. if c.Data["json"] == nil {
  28. go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+"异常提醒", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
  29. return
  30. }
  31. baseRes := c.Data["json"].(*models.BaseResponse)
  32. if baseRes != nil && !baseRes.Success && baseRes.IsSendEmail {
  33. go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+" 失败提醒", "URI:"+c.Ctx.Input.URI()+" ErrMsg:"+baseRes.ErrMsg+";Msg"+baseRes.Msg, utils.EmailSendToUsers)
  34. }
  35. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  36. }
  37. func (c *BaseCommonController) JSON(data interface{}, hasIndent bool, coding bool) error {
  38. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  39. var content []byte
  40. var err error
  41. if hasIndent {
  42. content, err = json.MarshalIndent(data, "", " ")
  43. } else {
  44. content, err = json.Marshal(data)
  45. }
  46. if err != nil {
  47. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  48. return err
  49. }
  50. if coding {
  51. content = []byte(utils.StringsToJSON(string(content)))
  52. }
  53. // 数据加密
  54. if services.CheckEncryption() {
  55. content = utils.DesBase64Encrypt(content)
  56. // get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
  57. content = []byte(`"` + string(content) + `"`)
  58. }
  59. return c.Ctx.Output.Body(content)
  60. }