base_controller.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_mini_ht_api/common/component/config"
  6. logger "eta/eta_mini_ht_api/common/component/log"
  7. "eta/eta_mini_ht_api/common/contants"
  8. "eta/eta_mini_ht_api/common/exception"
  9. "eta/eta_mini_ht_api/common/http"
  10. "eta/eta_mini_ht_api/common/utils/auth"
  11. stringUtils "eta/eta_mini_ht_api/common/utils/string"
  12. "fmt"
  13. "github.com/beego/beego/v2/server/web"
  14. "net/url"
  15. "strings"
  16. )
  17. var (
  18. htConfig = config.GetConfig(contants.HT).(*config.HTBizConfig)
  19. )
  20. type WrapData struct {
  21. Msg string
  22. Data interface{}
  23. }
  24. type BaseResponse struct {
  25. Ret int `description:"返回状态码"`
  26. Msg string
  27. ErrMsg string
  28. ErrCode int
  29. Data interface{} `json:"data,omitempty"`
  30. Success bool `description:"true 执行成功,false 执行失败"`
  31. }
  32. type BaseController struct {
  33. web.Controller
  34. }
  35. func (b *BaseController) FailResponse(errInfo error, msg string) {
  36. var retData BaseResponse
  37. var etaError *exception.EtaError
  38. if !errors.As(errInfo, &etaError) {
  39. etaError = exception.New(exception.UnknownError)
  40. }
  41. retData = BaseResponse{
  42. Ret: 200,
  43. Msg: msg,
  44. ErrMsg: etaError.ErrorMsg,
  45. ErrCode: etaError.ErrorCode,
  46. Data: nil}
  47. b.Data["json"] = retData
  48. b.ServeJSON()
  49. }
  50. // JsonResult /*
  51. func (b *BaseController) JsonResult(status int, errCode int, errMsg string, msg string, success bool, data interface{}) {
  52. retData := BaseResponse{
  53. Ret: status,
  54. Msg: msg,
  55. ErrMsg: errMsg,
  56. ErrCode: errCode,
  57. Data: data,
  58. Success: success}
  59. b.Ctx.Output.SetStatus(status)
  60. //content, err := json.Marshal(retData)
  61. //if err != nil {
  62. // logger.Error("加密失败")
  63. //} else {
  64. // if htConfig.NeedEncode() {
  65. // content = auth.DesBase64Encrypt(content, htConfig.GetDesCode())
  66. // }
  67. //}
  68. //fmt.Printf("%s", content)
  69. //b.Data["json"] = content
  70. b.Data["json"] = retData
  71. b.ServeJSON()
  72. }
  73. func (b *BaseController) GetPostParams(data interface{}) {
  74. err := json.Unmarshal(b.Ctx.Input.RequestBody, data)
  75. if err != nil {
  76. logger.Error("解析请求参数失败:%v", err)
  77. data = nil
  78. }
  79. }
  80. // Wrap ControllerWrap 是一个用于封装控制器方法的函数
  81. func Wrap(a *BaseController, fn func() (*WrapData, error)) {
  82. result, err := fn()
  83. if err != nil {
  84. logger.Error("%v", err)
  85. a.FailResponse(err, result.Msg)
  86. return
  87. }
  88. a.JsonResult(http.GetHttpStatusByAlias("ok"), http.ErrOK, "", result.Msg, http.Success, result.Data)
  89. }
  90. func (b *BaseController) InitWrapData(msg string) *WrapData {
  91. return &WrapData{Msg: msg}
  92. }
  93. func (b *BaseController) SuccessResult(msg string, data interface{}, wrapData *WrapData) {
  94. wrapData.Msg = msg
  95. wrapData.Data = data
  96. }
  97. func (b *BaseController) FailedResult(msg string, wrapData *WrapData) {
  98. wrapData.Msg = msg
  99. }
  100. func (b *BaseController) Prepare() {
  101. var requestBody string
  102. uri := b.Ctx.Input.URI()
  103. method := b.Ctx.Input.Method()
  104. if method == "GET" {
  105. requestBody = b.Ctx.Request.RequestURI
  106. } else {
  107. requestBody, _ = url.QueryUnescape(string(b.Ctx.Input.RequestBody))
  108. }
  109. ip := b.Ctx.Input.IP()
  110. b.Ctx.Input.URL()
  111. logger.Info("apiRequest:[uri:%s, requestBody:%s, ip:%s]", uri, requestBody, ip)
  112. }
  113. func (b *BaseController) Finish() {
  114. runMode := web.BConfig.RunMode
  115. if b.Data["json"] == nil {
  116. logger.Warn("apiRequest:[异常提醒:%v 接口:URI:%v;无返回值]", runMode, b.Ctx.Input.URI())
  117. return
  118. }
  119. baseRes := b.Data["json"].(BaseResponse)
  120. content, err := json.Marshal(baseRes)
  121. if err != nil {
  122. logger.Error("apiRequest:[应答json格式化失败:%s]", err)
  123. }
  124. if !baseRes.Success {
  125. logger.Info("apiRequest:[异常提醒:%v接口:URI:%v;ErrMsg:&v;Msg:%v]", b.Ctx.Input.URI(), baseRes.ErrMsg, baseRes.Msg)
  126. } else {
  127. if baseRes.Data == nil {
  128. logger.Warn("apiRequest:[异常提醒:%v 接口:URI:%v;无返回值]", runMode, b.Ctx.Input.URI())
  129. return
  130. } else {
  131. logger.Info("apiRequest:[uri:%s, resData:%s, ip:%s]", b.Ctx.Input.URI(), content)
  132. }
  133. }
  134. }
  135. type RequestInfo struct {
  136. Uri string `json:"uri"`
  137. IpAddress string `json:"ip_address"`
  138. Method string `json:"method"`
  139. Params string `json:"params"`
  140. }
  141. func (b *BaseController) ServeJSON(encoding ...bool) {
  142. var (
  143. hasIndent = false
  144. hasEncoding = false
  145. )
  146. if web.BConfig.RunMode == web.PROD {
  147. hasIndent = false
  148. }
  149. if len(encoding) > 0 && encoding[0] == true {
  150. hasEncoding = true
  151. }
  152. b.JSON(b.Data["json"], hasIndent, hasEncoding)
  153. }
  154. func (b *BaseController) JSON(data interface{}, hasIndent bool, coding bool) error {
  155. b.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
  156. //desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
  157. //c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
  158. // 设置Cookie为HTTPOnly
  159. b.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
  160. var content []byte
  161. var err error
  162. if hasIndent {
  163. content, err = json.MarshalIndent(data, "", " ")
  164. } else {
  165. content, err = json.Marshal(data)
  166. }
  167. ip := b.Ctx.Input.IP()
  168. requestBody, err := url.QueryUnescape(string(b.Ctx.Input.RequestBody))
  169. if err != nil {
  170. logger.Info("apiRequest:[err:%s]", err.Error())
  171. }
  172. b.logUri(content, requestBody, ip)
  173. if htConfig.NeedEncode() {
  174. content = auth.DesBase64Encrypt(content, htConfig.GetDesCode())
  175. content = []byte(`"` + string(content) + `"`)
  176. }
  177. if coding {
  178. content = []byte(stringUtils.StringsToJSON(string(content)))
  179. }
  180. return b.Ctx.Output.Body(content)
  181. }
  182. func (b *BaseController) logUri(respContent []byte, requestBody, ip string) {
  183. authorization := ""
  184. method := b.Ctx.Input.Method()
  185. uri := b.Ctx.Input.URI()
  186. if method != "HEAD" {
  187. if method == "POST" || method == "GET" {
  188. authorization = b.Ctx.Input.Header("authorization")
  189. if authorization == "" {
  190. authorization = b.Ctx.Input.Header("Authorization")
  191. }
  192. if authorization == "" {
  193. newAuthorization := b.GetString("authorization")
  194. if newAuthorization != `` {
  195. authorization = "authorization=" + newAuthorization
  196. } else {
  197. newAuthorization = b.GetString("Authorization")
  198. authorization = "authorization=" + newAuthorization
  199. }
  200. } else {
  201. if strings.Contains(authorization, ";") {
  202. authorization = strings.Replace(authorization, ";", "$", 1)
  203. }
  204. }
  205. if authorization == "" {
  206. strArr := strings.Split(uri, "?")
  207. for k, v := range strArr {
  208. fmt.Println(k, v)
  209. }
  210. if len(strArr) > 1 {
  211. authorization = strArr[1]
  212. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  213. fmt.Println(authorization)
  214. }
  215. }
  216. }
  217. }
  218. logger.Info("apiRequest:[uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s]", b.Ctx.Input.URI(), authorization, requestBody, respContent, ip)
  219. return
  220. }