base_common.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/beego/beego/v2/server/web"
  6. "hongze/hongze_public_api/services/alarm_msg"
  7. "hongze/hongze_public_api/utils"
  8. "net/http"
  9. "net/url"
  10. )
  11. type BaseCommonController struct {
  12. web.Controller
  13. }
  14. func (this *BaseCommonController) Prepare() {
  15. var requestBody string
  16. method := this.Ctx.Input.Method()
  17. if method == "GET" {
  18. requestBody = this.Ctx.Request.RequestURI
  19. } else {
  20. requestBody, _ = url.QueryUnescape(string(this.Ctx.Input.RequestBody))
  21. }
  22. ip := this.Ctx.Input.IP()
  23. apiLog.Println("请求地址:", this.Ctx.Input.URI(), "RequestBody:", requestBody, "IP:", 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. msg := "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值"
  38. go alarm_msg.SendAlarmMsg(msg, 3)
  39. return
  40. }
  41. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  42. }
  43. func (c *BaseCommonController) JSON(data interface{}, hasIndent bool, coding bool) error {
  44. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  45. var content []byte
  46. var err error
  47. if hasIndent {
  48. content, err = json.MarshalIndent(data, "", " ")
  49. } else {
  50. content, err = json.Marshal(data)
  51. }
  52. if err != nil {
  53. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  54. return err
  55. }
  56. ip := c.Ctx.Input.IP()
  57. params := c.Ctx.Input.Params()
  58. fmt.Println("params")
  59. fmt.Println(params)
  60. requestBody, _ := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
  61. apiLog.Println("请求地址:", 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. return c.Ctx.Output.Body(content)
  66. }