base_common.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "eta_gn/eta_report/models"
  5. "eta_gn/eta_report/services"
  6. "eta_gn/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. if services.CheckEncryption() {
  66. content = utils.DesBase64Encrypt(content, utils.DesKey)
  67. content = []byte(`"` + string(content) + `"`)
  68. }
  69. return c.Ctx.Output.Body(content)
  70. }
  71. func (c *BaseCommonController) logUri(content []byte, requestBody, ip string) {
  72. utils.ApiLog.Info("uri:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), requestBody, content, ip)
  73. return
  74. }