gin abort不能阻止后续代码的问题

在校验参数时发现参数错误和正确的json一起输出了出来导致前端解析错误
代码如下:

//utils.go
//返回json字符串
func ReturnJson(code int16, msg string, data interface{}, c *gin.Context) {
	c.JSON(200, gin.H{
		"code": code,
		"msg":  msg,
		"data": data,
	})
}
//bce.go
//翻译
func Translate(c *gin.Context) {
	type TranslateJson struct {
		TplId int    `json:"tplId"`
		Lang  string `json:"lang"`
		All   int    `json:"All"`
	}
	translate := TranslateJson{}
	err := c.BindJSON(&translate)
	if err != nil {
		panic(err)
	}
	if templateLangConfig[translate.Lang] == nil {
		utils.ReturnJson(-21003, "未找到该语种", nil, c)
	}
	utils.ReturnJson(0, "ok", nil, c)
}

以上同时输出了 {“code”:-21003,“data”:null,“msg”:“未找到该语种”}{“code”:0,“data”:null,“msg”:“ok”}导致前端解析失败了
后边百度说是需要调用gin.context.Abort() ,但是我加上后并没有作用,而且打印c.IsAborted()为true仍然继续执行。。。
来看下官方介绍:

//Abort prevents pending handlers from being called. 
//Note that this will not stop the current handler. 
//Let's say you have an authorization middleware that validates that the current request is authorized. 
//If the authorization fails (ex: the password does not match), 
//call Abort to ensure the remaining handlers for this request are not called.
func (c *Context)Abort()

意思大概是说abort只是阻止挂起函数,并不会停止当前的函数,那么其实就很简单了,只要在utils.returnJson后加上return即可。。。

if templateLangConfig[translate.Lang] == nil {
	utils.ReturnJson(-21003, "未找到该语种", nil, c)
	return 
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值