contextx.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package contextx
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "net/http"
  5. "speechAnalysis/pkg/ecode"
  6. "speechAnalysis/pkg/logx"
  7. )
  8. type (
  9. Context struct {
  10. ctx *gin.Context
  11. paramsMap map[string]interface{}
  12. }
  13. Response struct {
  14. Code int `json:"code"`
  15. Data interface{} `json:"data"`
  16. Msg string `json:"msg"`
  17. }
  18. )
  19. func NewContext(ctx *gin.Context, params interface{}) (r *Context, isAllow bool) {
  20. r = &Context{
  21. ctx: ctx,
  22. }
  23. if r.ctx.Request.Method == "OPTIONS" {
  24. r.ctx.String(http.StatusOK, "")
  25. return
  26. }
  27. defer func() {
  28. query := r.ctx.Request.URL.RawQuery
  29. if query != "" {
  30. query = "?" + query
  31. }
  32. urlPath := r.ctx.Request.URL.Path
  33. logx.Infof("%s | %s %s | uid: %s | %+v", ctx.ClientIP(), r.ctx.Request.Method, urlPath+query, r.GetUserId(), params)
  34. }()
  35. // validate params
  36. if params != nil {
  37. if err := r.ctx.ShouldBind(params); err != nil {
  38. r.Fail(ecode.ParamsErr)
  39. return
  40. }
  41. }
  42. isAllow = true
  43. return
  44. }
  45. func (slf *Context) GetRequestPath() (r string) {
  46. r = slf.ctx.Request.URL.Path
  47. return
  48. }
  49. func (slf *Context) GetUserId() (r string) {
  50. v := slf.paramsMap["userId"]
  51. switch v.(type) {
  52. case string:
  53. r = v.(string)
  54. }
  55. return
  56. }
  57. func (slf *Context) Result(code int, data interface{}, msg string) {
  58. slf.ctx.JSON(http.StatusOK, Response{
  59. Code: code,
  60. Data: data,
  61. Msg: msg,
  62. })
  63. }
  64. func (slf *Context) Ok() {
  65. slf.Result(ecode.OK, map[string]interface{}{}, "")
  66. }
  67. func (slf *Context) OkWithDetailed(data interface{}) {
  68. slf.Result(ecode.OK, data, "")
  69. }
  70. func (slf *Context) Fail(errCode int) {
  71. slf.Result(errCode, map[string]interface{}{}, ecode.GetMsg(errCode))
  72. }
  73. func (slf *Context) FailWithDetailed(errCode int, data interface{}) {
  74. slf.Result(errCode, data, ecode.GetMsg(errCode))
  75. }
  76. func (slf *Context) GetCtx() *gin.Context {
  77. return slf.ctx
  78. }
  79. func (slf *Context) SetCtx(c *gin.Context) *Context {
  80. slf.ctx = c
  81. return slf
  82. }