在校验参数时发现参数错误和正确的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
}