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()
}
相关推荐
xcLeigh3 小时前
Go入门:无类型常量与类型常量的区别
服务器·开发语言·golang
泡沫冰@3 小时前
GO 语言基础
开发语言·算法·golang
骇客野人8 小时前
电商商城微服务架构设计方案(SpringCloud/Go+Vue3+MySQL+ES+RocketMQ)
spring cloud·微服务·golang
码农大叔的博客8 小时前
golang示例:for九九乘法表
开发语言·算法·golang
圣殿骑士-Khtangc9 小时前
Go-sync-Pool对象池最佳实践与源码分析
golang
互联网中的一颗神经元9 小时前
01. Go 内存管理全景架构
java·jvm·golang
有脚就行9 小时前
第24篇-Go-gRPC推理服务-高性能跨语言通信
开发语言·人工智能·后端·golang
圣殿骑士-Khtangc1 天前
Go-Mutex源码解析从自旋到饥饿模式的完整演进
golang
圣殿骑士-Khtangc1 天前
Go大厂面试真题精讲之并发安全Map的实现方案
golang
运维开发笔记1 天前
3.8 Go switch 语句学习笔记
golang