base_common.go 1.9 KB

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