package response import ( "github.com/gin-gonic/gin" "net/http" ) type Response struct { Code int `json:"code"` Msg string `json:"msg"` Data interface{} `json:"data"` } const ( SUCCESS = 200 ERROR = 500 UNAUTHORIZED = 401 NOT_FOUND = 404 BAD_REQUEST = 400 ) var MsgFlags = map[int]string{ SUCCESS: "操作成功", ERROR: "操作失败", UNAUTHORIZED: "未授权", NOT_FOUND: "资源不存在", BAD_REQUEST: "请求参数错误", } func GetMsg(code int) string { msg, ok := MsgFlags[code] if !ok { return MsgFlags[ERROR] } return msg } func Success(c *gin.Context, data interface{}) { c.JSON(http.StatusOK, Response{ Code: SUCCESS, Msg: "success", Data: data, }) } func Error(c *gin.Context, code int, msg string) { c.JSON(http.StatusOK, Response{ Code: code, Msg: msg, Data: nil, }) } func Unauthorized(c *gin.Context) { c.JSON(http.StatusUnauthorized, Response{ Code: UNAUTHORIZED, Msg: "未授权", Data: nil, }) }