package controllers import ( "bytes" "cron_admin/app/constants/errorcode" "cron_admin/app/utils" "cron_admin/config" "encoding/base64" "encoding/json" "errors" "github.com/go-playground/locales/zh" ut "github.com/go-playground/universal-translator" "github.com/qit-team/snow-core/log/logger" "gopkg.in/go-playground/validator.v9" zh_translations "gopkg.in/go-playground/validator.v9/translations/zh" "io/ioutil" "net/http" "github.com/gin-gonic/gin" ) func EncriptJson(h gin.H) string { var data, err = json.Marshal(h) if err != nil { utils.Log(nil, "encriptJso", err) } rs, err := utils.Des3Encrypt(data, config.GetConf().AppKey) res := base64.StdEncoding.EncodeToString(rs) return res } func Error404(c *gin.Context) { HandRes(c, nil, errorcode.NotFound) } func Error500(c *gin.Context) { HandRes(c, nil, errorcode.SystemError) } /** * 将请求的body转换为request数据结构 * @param c * @param request 传入request数据结构的指针 如 new(TestRequest) */ func GenRequest(c *gin.Context, request interface{}) (msgs []string, err error) { if c.Request.Method == "GET" || c.Request.Method == "DELETE" { err = c.ShouldBindQuery(request) } else { err = c.ShouldBindJSON(request) } if err == nil { validate := validator.New() zh_ch := zh.New() uni := ut.New(zh_ch) trans, _ := uni.GetTranslator("zh") //验证器注册翻译器 zh_translations.RegisterDefaultTranslations(validate, trans) errValidate := validate.Struct(request) if errValidate != nil { for _, v := range errValidate.(validator.ValidationErrors) { msgs = append(msgs, v.Translate(trans)) } err = errorcode.ParamError return } } return } // 重复读取body func ReadBody(c *gin.Context) (body []byte, err error) { body, err = ioutil.ReadAll(c.Request.Body) if err != nil { return } c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body)) return } func GetRequest(c *gin.Context) interface{} { request, _ := c.Get("request") return request } func HandRes(c *gin.Context, data interface{}, err error) { var bizErr *errorcode.BusinessErr if err == nil { bizErr = errorcode.Success } else { if errors.Is(err, &errorcode.BusinessErr{}) { errors.As(err, &bizErr) } else { utils.Log(c, "系统错误", err.Error()) logger.GetLogger().Error() bizErr = errorcode.SystemError } } if data == nil { data = gin.H{} } jsonData := gin.H{ "code": bizErr.Code(), "message": bizErr.Error(), "data": data, } if config.GetConf().Env == "production" { c.String(http.StatusOK, EncriptJson(jsonData)) } else { c.JSON(http.StatusOK, jsonData) } c.Abort() } func GetPlayerId(c *gin.Context) string { playerId, _ := c.Get("playerId") if playerId == nil { return "" } return playerId.(string) }