package zhios_tool_e import ( "code.fnuoos.com/go_rely_warehouse/zyos_go_tools.git/utils" "code.fnuoos.com/go_rely_warehouse/zyos_go_tools.git/utils/logx" "encoding/json" "net/http" "github.com/gin-gonic/gin" ) // GetMsg get error information based on Code // 因为这里code是自己控制的, 因此没考虑报错信息 func GetMsg(code int) (int, string) { if msg, ok := MsgFlags[code]; ok { return code / 1000, msg } if http.StatusText(code) == "" { code = 200 } return code, MsgFlags[ERR_BAD_REQUEST] } // 成功输出, fields 是额外字段, 与code, msg同级 func OutSuc(c *gin.Context, data interface{}, fields map[string]interface{}) { res := gin.H{ "code": 1, "msg": "ok", "data": data, } if fields != nil { for k, v := range fields { res[k] = v } } jsonData, _ := json.Marshal(res) strs := string(jsonData) if c.GetString("translate_open") != "" { strs = utils.ReadReverse(c, string(jsonData), "") } if utils.GetApiVersion(c) > 0 { //加了签名校验只返回加密的字符串 strs = utils.ResultAes(c, []byte(strs)) } c.Writer.WriteString(strs) } func OutSucPure(c *gin.Context, data interface{}, fields map[string]interface{}) { res := gin.H{ "code": 1, "msg": "ok", "data": data, } if fields != nil { for k, v := range fields { res[k] = v } } jsonData, _ := json.Marshal(res) strs := string(jsonData) if c.GetString("translate_open") != "" { strs = utils.ReadReverse(c, string(jsonData), "") } if utils.GetApiVersion(c) > 0 { //加了签名校验只返回加密的字符串 strs = utils.ResultAes(c, []byte(strs)) } c.Writer.WriteString(strs) } // 错误输出 func OutErr(c *gin.Context, code int, err ...interface{}) { statusCode, msg := GetMsg(code) if len(err) > 0 && err[0] != nil { e := err[0] switch v := e.(type) { case E: statusCode = v.Code / 1000 msg = v.Error() logx.Error(v.msg + ": " + v.st) // 记录堆栈信息 case error: logx.Error(v) break case string: msg = v case int: if _, ok := MsgFlags[v]; ok { msg = MsgFlags[v] } } } if c.GetString("translate_open") != "" { msg = utils.ReadReverse(c, msg, "") } if utils.GetApiVersion(c) > 0 { //加了签名校验只返回加密的字符串 jsonData, _ := json.Marshal(gin.H{ "code": code, "msg": msg, "data": []struct{}{}, }) str := utils.ResultAes(c, jsonData) if code > 100000 { code = int(utils.FloatFormat(float64(code/1000), 0)) } c.Status(500) c.Writer.WriteString(str) } else { c.AbortWithStatusJSON(statusCode, gin.H{ "code": code, "msg": msg, "data": []struct{}{}, }) } } // 重定向 func OutRedirect(c *gin.Context, code int, loc string) { if code < 301 || code > 308 { code = 303 } c.Redirect(code, loc) c.Abort() }