| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package contextx
- import (
- "github.com/gin-gonic/gin"
- "net/http"
- "speechAnalysis/pkg/ecode"
- "speechAnalysis/pkg/logx"
- )
- 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
- }
|