base_controller.go 6.6 KB

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