123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package resopnse
- import (
- "net/http"
- "github.com/gin-gonic/gin"
- )
- // 这里定义的状态码
- type Rescode int64
- // 在const里使用了iota自增
- const (
- CodeSuccess Rescode = 1000 + iota
- CodeInvalidParam
- CodeUserExist
- CodeUserNotExist
- CodeNotMatch
- CodeServerBusy
- )
- // 给对应状态码加上消息
- var codeMsgMap = map[Rescode]string{
- CodeSuccess: "success",
- CodeInvalidParam: "请求参数错误",
- CodeUserExist: "用户名已存在",
- CodeUserNotExist: "用户不存在",
- CodeNotMatch: "用户名或密码错误",
- CodeServerBusy: "服务器繁忙",
- // 比如数据库连接错误啥的,前端不用知道,
- // 就说服务器繁忙就行
- }
- // 获得对应状态码的消息
- func (c Rescode) GetMsg() string {
- msg, ok := codeMsgMap[c]
- if !ok {
- msg = codeMsgMap[CodeServerBusy]
- }
- return msg
- }
- /*
- 封装响应方法,固定格式,方便前端
- {
- "code": , //程序中的错误码
- "msg": ,// 错误的提示信息
- "data":{} //数据
- }
- */
- type ResopnseDate struct {
- Code Rescode `json:"code"`
- Msg interface{} `json:"msg"`
- Date interface{} `json:"data"`
- }
- func ResponseError(c *gin.Context, code Rescode) {
- //只有状态码
- c.JSON(http.StatusOK, &ResopnseDate{
- Code: code,
- Msg: code.GetMsg(),
- Date: nil,
- })
- }
- func ResponseErrorWithMsg(c *gin.Context, code Rescode, msg interface{}) {
- //有状态码和自己的信息
- c.JSON(http.StatusOK, &ResopnseDate{
- Code: code,
- Msg: msg,
- Date: nil,
- })
- }
- func ResopnseSuccess(c *gin.Context, data interface{}) {
- //成功以后返回的,自带数据
- c.JSON(http.StatusOK, &ResopnseDate{
- Code: CodeSuccess,
- Msg: CodeSuccess.GetMsg(),
- Date: data,
- })
- }
|