package http import ( "log" "github.com/gin-gonic/gin" ) type ResponseData struct { Code int `json:"code"` Message string `json:"msg"` Data interface{} `json:"data"` } func Success(c *gin.Context, data interface{}) { c.JSON(200, ResponseData{Code: 0, Message: "success", Data: data}) } func ErrorWithData(c *gin.Context, code int, err error, data interface{}) { if code == 0 { Success(c, err) return } if err == nil { c.AbortWithStatusJSON(200, ResponseData{Code: code, Message: "failed", Data: data}) return } c.AbortWithStatusJSON(200, ResponseData{Code: code, Message: err.Error(), Data: data}) } func Error(c *gin.Context, code int, err error) { if code == 0 { Success(c, err) return } if err == nil { c.AbortWithStatusJSON(200, ResponseData{Code: code, Message: "failed"}) return } log.Println(err) c.AbortWithStatusJSON(200, ResponseData{Code: code, Message: err.Error()}) } func Response(c *gin.Context, res bool) { if res { Success(c, res) return } Error(c, 400, nil) } // OutRedirect 重定向 func Redirect(c *gin.Context, code int, loc string) { if code < 301 || code > 308 || code == 304 { code = 303 } c.Redirect(code, loc) // c.Abort() } func ResponseBytes(c *gin.Context, data []byte) { // c.Abort() c.Writer.Write(data) }