base_auth.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "eta/eta_report/models"
  5. "eta/eta_report/services"
  6. "eta/eta_report/utils"
  7. "fmt"
  8. "github.com/beego/beego/v2/server/web"
  9. "net/http"
  10. )
  11. type BaseAuthController struct {
  12. web.Controller
  13. Token string
  14. }
  15. func (this *BaseAuthController) Prepare() {
  16. fmt.Println("enter prepare")
  17. method := this.Ctx.Input.Method()
  18. uri := this.Ctx.Input.URI()
  19. fmt.Println("Url:", uri)
  20. if method != "HEAD" {
  21. if method == "POST" || method == "GET" {
  22. }
  23. } else {
  24. this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
  25. this.StopRun()
  26. return
  27. }
  28. }
  29. func (c *BaseAuthController) ServeJSON(encoding ...bool) {
  30. var (
  31. hasIndent = false
  32. hasEncoding = false
  33. )
  34. if web.BConfig.RunMode == web.PROD {
  35. hasIndent = false
  36. }
  37. if len(encoding) > 0 && encoding[0] == true {
  38. hasEncoding = true
  39. }
  40. if c.Data["json"] == nil {
  41. go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+"异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
  42. return
  43. }
  44. baseRes := c.Data["json"].(*models.BaseResponse)
  45. if baseRes != nil && baseRes.Ret != 200 && baseRes.Ret != 408 && baseRes.IsSendEmail {
  46. body, _ := json.Marshal(baseRes)
  47. go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+" 失败提醒", "URI:"+c.Ctx.Input.URI()+"<br/> ErrMsg:"+baseRes.ErrMsg+";<br/>Msg:"+baseRes.Msg+";<br/> Body:"+string(body), utils.EmailSendToUsers)
  48. }
  49. c.JSON(c.Data["json"], hasIndent, hasEncoding)
  50. }
  51. func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
  52. c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  53. var content []byte
  54. var err error
  55. if hasIndent {
  56. content, err = json.MarshalIndent(data, "", " ")
  57. } else {
  58. content, err = json.Marshal(data)
  59. }
  60. if err != nil {
  61. http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
  62. return err
  63. }
  64. if coding {
  65. content = []byte(utils.StringsToJSON(string(content)))
  66. }
  67. // 数据加密
  68. if services.CheckEncryption() {
  69. content = utils.DesBase64Encrypt(content)
  70. // get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
  71. content = []byte(`"` + string(content) + `"`)
  72. }
  73. return c.Ctx.Output.Body(content)
  74. }