定义response的格式
type Response struct {
Code int `json:"code"`
Data interface{} `json:"data"`
Message string `json:"message"`
}
输出
func Result(code int, data interface{}, msg string, c *gin.Context) {
c.JSON(200, Response{
code,
data,
msg,
})
}
完整的代码
package response
import (
"github.com/gin-gonic/gin"
)
const (
SUCCESS = 0
ERROR = -1
)
type Response struct {
Code int `json:"code"`
Data interface{} `json:"data"`
Message string `json:"message"`
}
func Result(code int, data interface{}, msg string, c *gin.Context) {
c.JSON(200, Response{
code,
data,
msg,
})
}
func Ok(c *gin.Context) {
OkWithDetail("ok", gin.H{}, c)
}
func OkWithData(data interface{}, c *gin.Context) {
OkWithDetail("ok", data, c)
}
func OkWithMessage(msg string, c *gin.Context) {
OkWithDetail(msg, gin.H{}, c)
}
func OkWithDetail(msg string, data interface{}, c *gin.Context) {
Result(SUCCESS, data, msg, c)
}
func Fail(c *gin.Context) {
FailWithMessage("error", c)
}
func FailWithMessage(msg string, c *gin.Context) {
FailWithDetail(msg, gin.H{}, c)
}
func FailWithDetail(msg string, data interface{}, c *gin.Context) {
Result(ERROR, data, msg, c)
}
调用
type User struct {
Username string `json:"username" form:"username" binding:"required"`
Password string `json:"password" form:"password"`
}
func login(c *gin.Context){
username := c.PostForm("username")
password := c.PostForm("password")
var user User
err := c.ShouldBind(&user)
if err != nil {
response.FailWithDetail("error", err.Error(), c)
return
}
fmt.Printf("shouldBind: username=%s pwd=%v \n", user.Username, user.Password)
response.OkWithData(user, c)
}