浏览代码

增加错误码组件

Simon Zhou 5 年之前
父节点
当前提交
d16bf47b6f
共有 4 个文件被更改,包括 72 次插入7 次删除
  1. 14 0
      ex/code.go
  2. 22 0
      ex/msg.go
  3. 29 0
      models/response.go
  4. 7 7
      token/token.go

+ 14 - 0
ex/code.go

@@ -0,0 +1,14 @@
+package ex
+
+const (
+	SUCCESS        = 200
+	ERROR          = 500
+	INVALID_PARAMS = 400
+
+	ERROR_AUTH_CHECK_TOKEN_MISSING = 20001
+	ERROR_AUTH_CHECK_TOKEN_FAIL    = 20002
+
+	ERROR_UPLOAD_SAVE_IMAGE_FAIL    = 30001
+	ERROR_UPLOAD_CHECK_IMAGE_FAIL   = 30002
+	ERROR_UPLOAD_CHECK_IMAGE_FORMAT = 30003
+)

+ 22 - 0
ex/msg.go

@@ -0,0 +1,22 @@
+package ex
+
+var MsgFlags = map[int]string{
+	SUCCESS:                         "ok",
+	ERROR:                           "fail",
+	INVALID_PARAMS:                  "请求参数错误",
+	ERROR_AUTH_CHECK_TOKEN_MISSING:  "Token缺失",
+	ERROR_AUTH_CHECK_TOKEN_FAIL:     "Token鉴权失败",
+	ERROR_UPLOAD_SAVE_IMAGE_FAIL:    "保存图片失败",
+	ERROR_UPLOAD_CHECK_IMAGE_FAIL:   "检查图片失败",
+	ERROR_UPLOAD_CHECK_IMAGE_FORMAT: "校验图片错误,图片格式或大小有问题",
+}
+
+// GetMsg get error information based on Code
+func GetMsg(code int) string {
+	msg, ok := MsgFlags[code]
+	if ok {
+		return msg
+	}
+
+	return MsgFlags[ERROR]
+}

+ 29 - 0
models/response.go

@@ -0,0 +1,29 @@
+package models
+
+import (
+	"mtp2_if/ex"
+
+	"github.com/gin-gonic/gin"
+)
+
+// Gin is gin.Context
+type Gin struct {
+	C *gin.Context
+}
+
+// Response 通用Response数据结构
+type Response struct {
+	Code int         `json:"code"`
+	Msg  string      `json:"msg"`
+	Data interface{} `json:"data"`
+}
+
+// Response setting gin.JSON
+func (g *Gin) Response(httpCode, errCode int, data interface{}) {
+	g.C.JSON(httpCode, Response{
+		Code: errCode,
+		Msg:  ex.GetMsg(errCode),
+		Data: data,
+	})
+	return
+}

+ 7 - 7
token/token.go

@@ -3,6 +3,7 @@ package token
 import (
 	"errors"
 	"fmt"
+	"mtp2_if/ex"
 	"mtp2_if/rediscli"
 	"net/http"
 	"strings"
@@ -31,21 +32,20 @@ func CheckToken(loginid string, token string) error {
 func Auth() gin.HandlerFunc {
 	return func(c *gin.Context) {
 		var code int
-		var msg string
 		var data interface{}
 
-		code = 0
+		code = ex.SUCCESS
 		token := c.GetHeader("token")
 		if token == "" {
-			code = 3001
-			msg = "缺少token"
+			// Token缺失
+			code = ex.ERROR_AUTH_CHECK_TOKEN_MISSING
 		} else {
 			// 获取loginid
 			s := strings.Split(token, "_")
 			loginid := s[0]
 			if err := CheckToken(loginid, token); err != nil {
-				code = 3002
-				msg = "token校验失败"
+				// Token错误
+				code = ex.ERROR_AUTH_CHECK_TOKEN_FAIL
 			}
 		}
 
@@ -53,7 +53,7 @@ func Auth() gin.HandlerFunc {
 		if code != 0 {
 			c.JSON(http.StatusUnauthorized, gin.H{
 				"code": code,
-				"msg":  msg,
+				"msg":  ex.GetMsg(code),
 				"data": data,
 			})