package api import ( "cockData/server/log" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" ) const ( ResponseCodeSuccess = 200 ResponseCodeErrorInternal = 30000 // 内部错误 ResponseCodeErrorParams = 30001 // 参数错误 ResponseCodeErrorSession = 30002 // 会话失效 ) // Response 通用返回结构 type Response struct { Code int `json:"code"` Msg string `json:"message"` Data interface{} `json:"data"` } func CreateSuccessResponse(data interface{}) *Response { return &Response{ Code: ResponseCodeSuccess, Msg: "Success", Data: data, } } func CreateErrorResponse(code int, msg string) *Response { log.Infof("返回错误%d,%s", code, msg) return &Response{ Code: code, Msg: msg, Data: "", } } func CreateParamsErrorResponse() *Response { return CreateErrorResponse(ResponseCodeErrorParams, "参数错误") } func CreateInternalErrorResponse() *Response { return CreateErrorResponse(ResponseCodeErrorInternal, "内部错误") } func CreateSessionErrorResponse() *Response { return CreateErrorResponse(ResponseCodeErrorSession, "会话失效") } func CheckParams(context *gin.Context, obj interface{}) error { err := context.ShouldBindBodyWith(&obj, binding.JSON) log.Infof("请求参数 %s", obj) if err != nil { ResponseApi(context, *CreateParamsErrorResponse()) } return err } func ResponseApiWithError(context *gin.Context, rep *Response, err error) { if err != nil { ResponseApi(context, *CreateInternalErrorResponse()) } else { ResponseApi(context, *rep) } } // ResponseApi 创建一个200返回并中断context func ResponseApi(context *gin.Context, response Response) { log.Warnf("应答:%+v", response) context.AbortWithStatusJSON(200, response) }