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
|
}
|