Golang gin框架中间件c.JSON返回结果后终止返回

gin框架中间件c.JSON返回结果后还是会继续执行之后的方法,我们可以用c.Abort()来终止后续的处理

go 复制代码
func MiddlewareFunction(c *gin.Context) {
    // 假设有某种条件下需要返回错误
    if someCondition {
        c.JSON(http.StatusBadRequest, gin.H{"error": "some error message"})
        c.Abort() // 终止后续处理
        return
    }
 
    // 如果没有错误,则继续后续处理
    c.Next() // 继续执行其他的middleware和handlers
}
 
func main() {
    r := gin.Default()
 
    // 使用MiddlewareFunction
    r.Use(MiddlewareFunction)
 
    // 其他的handlers
    r.GET("/", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"message": "success"})
    })
 
    // 启动服务器
    r.Run()
}
相关推荐
o0o_-_2 天前
【go/gopls/mcp】官方gopls内置mcp server使用
开发语言·后端·golang
又菜又爱玩呜呜呜~3 天前
go使用反射获取http.Request参数到结构体
开发语言·http·golang
希望20173 天前
Golang | http/server & Gin框架简述
http·golang·gin
NG WING YIN4 天前
Golang關於信件的
开发语言·深度学习·golang
silver98864 天前
再谈golang的sql链接dsn
mysql·golang
刘媚-海外4 天前
Go语言开发AI应用
开发语言·人工智能·golang·go
deepwater_zone4 天前
Go语言核心技术
后端·golang
二哈不在线4 天前
代码随想录二刷之“动态规划”~GO
算法·golang·动态规划