10篇带你手摸手封装gin框架(5)- responese统一封装

3,844 阅读2分钟

前言

这是我参与更文挑战的第5天,大家好,我是作曲家种太阳
上一篇我们讲到了Validator字段校验器功能
这篇我们介绍下最response统一返回,按照规定的格式讲数据返回

1. 概述

功能很简单,就是为了固定每次返回的json结构

{
    "code": 400,
    "data": {
        "name": "name为必填字段",
        "password": "password为必填字段"
    },
    "msg": "字段校验错误"
}

这样做的优点就是规范返回数据,前端使用解构赋值就可以取出想要的数据

字段类型概述
codeint自定义状态码(需要和前端商量)
msginterface{}信息字段,返回前端需要的toast提示
datainterface{}数据字段,返回前端所需要的数据

ps:之前我们写过 context.json() 这个函数,是给前端返回数据的函数,这里我们主要针对这个函数做二次封装

2. 编写Success函数

在 Response/response中添加

func Success(c *gin.Context, code int, msg interface{}, data interface{}) {
	c.JSON(http.StatusOK, map[string]interface{}{
		"code": code, // 自定义code
		"msg":  msg,  // message
		"data": data, // 数据
	})
	return
}

ps: 成功就统一返回200,所以在这里就没有加http状态码的位置参数,只有code自定义参数

3. 编写Err函数

// 返回失败
func Err(c *gin.Context, httpCode int, code int, msg string, jsonStr interface{}) {
	c.JSON(httpCode, map[string]interface{}{
		"code": code,
		"msg":  msg,
		"data": jsonStr,
	})
	return
}

4. 使用

(1).在 controller/user中的PasswordLogin函数中
把 c.json()函数这一段删除改换成:

    Response.Success(c, 200, "success", "test")

(2).修改HandleValidatorError函数
在 utils/validator 中 HandleValidatorError函数中
把 c.json()函数这一段删除改换成: image.png

http状态码和code自定义状态码的区别

  1. http状态码是200,204,400,404,500 这样http规范定义的状态码
  2. code只是个int类型数字,是和前端一起商量的状态码,比如 100010代表字段校验错误等等,是对http状态码一种详细的补充

最后-验证结果环节

(1).Success函数测试验证:
在postman输入(post请求):http://192.168.0.102:8022/v1/user/login?password=1123123123&name=13999189291

image.png

(2).Err函数测试验证:
在postman输入(post请求):http://192.168.0.102:8022/v1/user/login

image.png

做到这里说明本章节您已经掌握了,再接再接再厉哦~~

如果这系列的文章对你有有用,请点赞和留言吧~