base_common.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "eta/eta_mini_api/models"
  5. "eta/eta_mini_api/services"
  6. "eta/eta_mini_api/utils"
  7. "net/http"
  8. "net/url"
  9. "github.com/beego/beego/v2/server/web"
  10. )
  11. type BaseCommonController struct {
  12. web.Controller
  13. }
  14. func (c *BaseCommonController) Prepare() {
  15. var requestBody string
  16. method := c.Ctx.Input.Method()
  17. if method == "GET" {
  18. requestBody = c.Ctx.Request.RequestURI
  19. } else {
  20. requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  21. }
  22. ip := c.Ctx.Input.IP()
  23. utils.ApiLog.Info("uri:%s, requestBody:%s, ip:%s", c.Ctx.Input.URI(), requestBody, ip)
  24. }
  25. func (c *BaseCommonController) ServeJSON(encoding ...bool) {
  26. var (
  27. hasIndent = false
  28. hasEncoding = false
  29. )
  30. if web.BConfig.RunMode == web.PROD {
  31. hasIndent = false
  32. }
  33. if len(encoding) > 0 && encoding[0] == true {
  34. hasEncoding = true
  35. }
  36. if c.Data["json"] == nil {
  37. utils.ApiLog.Notice(utils.APPNAME+" "+utils.RunMode+"异常提醒", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值")
  38. return
  39. }
  40. baseRes := c.Data["json"].(*models.BaseResponse)
  41. if baseRes != nil && !baseRes.Success {
  42. utils.ApiLog.Notice("接口:" + "URI:" + c.Ctx.Input.URI() + ";ErrMsg:" + baseRes.ErrMsg + ";Msg" + baseRes.Msg)
  43. }
  44. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  45. }
  46. func (c *BaseCommonController) JSON(data interface{}, hasIndent bool, coding bool) error {
  47. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  48. var content []byte
  49. var err error
  50. if hasIndent {
  51. content, err = json.MarshalIndent(data, "", " ")
  52. } else {
  53. content, err = json.Marshal(data)
  54. }
  55. if err != nil {
  56. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  57. return err
  58. }
  59. ip := c.Ctx.Input.IP()
  60. requestBody, _ := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  61. utils.ApiLog.Info("请求地址:", c.Ctx.Input.URI(), "Authorization:", c.Ctx.Input.Header("Authorization"), "RequestBody:", requestBody, "ResponseBody", string(content), "IP:", 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. }