base_common.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. "net/url"
  10. )
  11. type BaseCommonController struct {
  12. web.Controller
  13. Token string
  14. }
  15. func (this *BaseCommonController) Prepare() {
  16. }
  17. func (c *BaseCommonController) ServeJSON(encoding ...bool) {
  18. var (
  19. hasIndent = false
  20. hasEncoding = false
  21. )
  22. if web.BConfig.RunMode == web.PROD {
  23. hasIndent = false
  24. }
  25. if len(encoding) > 0 && encoding[0] == true {
  26. hasEncoding = true
  27. }
  28. if c.Data["json"] == nil {
  29. go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+"异常提醒", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
  30. return
  31. }
  32. baseRes := c.Data["json"].(*models.BaseResponse)
  33. if baseRes != nil && !baseRes.Success && baseRes.IsSendEmail {
  34. go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+" 失败提醒", "URI:"+c.Ctx.Input.URI()+" ErrMsg:"+baseRes.ErrMsg+";Msg"+baseRes.Msg, utils.EmailSendToUsers)
  35. }
  36. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  37. }
  38. func (c *BaseCommonController) JSON(data interface{}, hasIndent bool, coding bool) error {
  39. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  40. desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  41. c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  42. var content []byte
  43. var err error
  44. if hasIndent {
  45. content, err = json.MarshalIndent(data, "", " ")
  46. } else {
  47. content, err = json.Marshal(data)
  48. }
  49. if err != nil {
  50. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  51. return err
  52. }
  53. ip := c.Ctx.Input.IP()
  54. requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  55. if err != nil {
  56. requestBody = string(c.Ctx.Input.RequestBody)
  57. }
  58. if requestBody == "" {
  59. requestBody = c.Ctx.Input.URI()
  60. }
  61. c.logUri(content, requestBody, ip)
  62. if coding {
  63. content = []byte(utils.StringsToJSON(string(content)))
  64. }
  65. // 数据加密
  66. if services.CheckEncryption() {
  67. content = utils.DesBase64Encrypt(content, utils.DesKey)
  68. // get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
  69. content = []byte(`"` + string(content) + `"`)
  70. }
  71. return c.Ctx.Output.Body(content)
  72. }
  73. func (c *BaseCommonController) logUri(content []byte, requestBody, ip string) {
  74. utils.ApiLog.Info("uri:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), requestBody, content, ip)
  75. return
  76. }