在前面我们介绍过,返回的格式一般都要固定,所以一般来说我们的返回格式都是:
{ "code": 200, "message": "请求成功", "data": null }
在前面的案例里面我们也是这么来写的,但是大家发现问题没有,也就是在需要返回的时候,我们总是构造各种c.json(xxx)这样子的代码,试想一下,项目够大,我们是不是会写非常多这样的代码呢?例如:
所以这里大家试想一下,能否可以精简呢?答案是可以的,我们比如在responsejson.go文件中统一定义下fail和ok的方法,在其他地方使用的时候直接用是不是更方便呢?下面我们来演示一下:
一、定义公共的fail和ok方法
这里我们的responsejson.go文件中定义两个公共的方法,分别是fail和ok,示例代码如下:
type Result struct { Code int `json:"code"` Message string `json:"message"` Data any `json:"data"` } /* * 错误返回 */ func Fail(c *gin.Context, code int, message string) { c.JSON(http.StatusOK, Result{ Code: code, Message: message, Data: nil, }) c.Abort() } /* * 正确返回 */ func Ok(c *gin.Context, data any) { c.JSON(http.StatusOK, Result{ Code: http.StatusOK, Message: "请求成功", Data: data, }) }
二、调用
接下来我们在需要使用的地方进行调用即可,例如:
func ListGoods(c *gin.Context) { username, _ := c.Get("username") log.Println("通过中间件解析获取到的username是:", username) goods := service.ListAllGoods() middleware.Ok(c, goods) } func GlobalErrorMiddleware() gin.HandlerFunc { return func(c *gin.Context) { //先执行请求 c.Next() // 发生了错误 if len(c.Errors) > 0 { //获取最后一个error 返回 err := c.Errors.Last() Fail(c, http.StatusInternalServerError, err.Error()) return } } }
三、测试验证
接下来我们验证下看看效果:
这样做是不是很方便呢?最后按照惯例,附上本案例的源码,登陆后即可下载。
还没有评论,来说两句吧...