base_controller.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. // 设置Cookie为HTTPOnly
  157. b.Ctx.SetCookie("", "", -1, "/", "", false, true, "")
  158. var content []byte
  159. var err error
  160. if hasIndent {
  161. content, err = json.MarshalIndent(data, "", " ")
  162. } else {
  163. content, err = json.Marshal(data)
  164. }
  165. ip := b.Ctx.Input.IP()
  166. requestBody, err := url.QueryUnescape(string(b.Ctx.Input.RequestBody))
  167. if err != nil {
  168. logger.Info("apiRequest:[err:%s]", err.Error())
  169. }
  170. b.logUri(content, requestBody, ip)
  171. if htConfig.NeedEncode() {
  172. content = auth.DesBase64Encrypt(content, htConfig.GetDesCode())
  173. content = []byte(`"` + string(content) + `"`)
  174. }
  175. if coding {
  176. content = []byte(stringUtils.StringsToJSON(string(content)))
  177. }
  178. return b.Ctx.Output.Body(content)
  179. }
  180. func (b *BaseController) logUri(respContent []byte, requestBody, ip string) {
  181. authorization := ""
  182. method := b.Ctx.Input.Method()
  183. uri := b.Ctx.Input.URI()
  184. if method != "HEAD" {
  185. if method == "POST" || method == "GET" {
  186. authorization = b.Ctx.Input.Header("authorization")
  187. if authorization == "" {
  188. authorization = b.Ctx.Input.Header("Authorization")
  189. }
  190. if authorization == "" {
  191. newAuthorization := b.GetString("authorization")
  192. if newAuthorization != `` {
  193. authorization = "authorization=" + newAuthorization
  194. } else {
  195. newAuthorization = b.GetString("Authorization")
  196. authorization = "authorization=" + newAuthorization
  197. }
  198. } else {
  199. if strings.Contains(authorization, ";") {
  200. authorization = strings.Replace(authorization, ";", "$", 1)
  201. }
  202. }
  203. if authorization == "" {
  204. strArr := strings.Split(uri, "?")
  205. for k, v := range strArr {
  206. fmt.Println(k, v)
  207. }
  208. if len(strArr) > 1 {
  209. authorization = strArr[1]
  210. authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
  211. fmt.Println(authorization)
  212. }
  213. }
  214. }
  215. }
  216. logger.Info("apiRequest:[uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s]", b.Ctx.Input.URI(), authorization, requestBody, respContent, ip)
  217. return
  218. }