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