go-api-framework
go基于gin三层架构web框架
三层架构模式
func RegisterHandler(业务最终函数,怎么取参数,怎么处理业务结果) func(context *gin.Context) {
xxxxxoooo
}
这个就是最终的结果
unc RegisterHandler(业务最终函数,怎么取参数,怎么处理业务结果) func(context *gin.Context) { 参数:=怎么取参数() 业务结果:=业务最终函数(参数) 怎么处理业务结果(业务结果) }
首先要定义原型
业务最终函数
type Endpoint func(ctx context.Context,request interface{}) (response interface{}, err error)
一律使用interface{} 。这样可以处理不同的类型
怎么取参数 :
type EncodeRequestFunc func(*gin.Context, interface{}) (interface{}, error)
怎么处理响应:
type DecodeResponseFunc func(*gin.Context, interface{}) error
然后写成这样
func RegisterHandler(endpoint Endpoint,encodeFunc EncodeRequestFunc,decodeFunc DecodeResponseFunc) func(context *gin.Context){ return func(context *gin.Context) { req,err:=encodeFunc(context,nil) if err!=nil{ context.JSON(500,gin.H{"error":"param err"+err.Error()}) return } res,err:=endpoint(context,req) if err!=nil{ context.JSON(500,gin.H{"error":err}) }else{ err:=decodeFunc(context,res) if err!=nil{ context.JSON(500,gin.H{"error":err}) } } } }
最终核心结构:
package App import ( "context" "fmt" "github.com/gin-gonic/gin" ) type Middleware func(Endpoint) Endpoint //业务最终函数原型 type Endpoint func(ctx context.Context,request interface{}) (response interface{}, err error) //怎么取参数 type EncodeRequestFunc func(*gin.Context) (interface{}, error) //怎么处理业务结果 type DecodeResponseFunc func(*gin.Context, interface{}) error func RegisterHandler(endpoint Endpoint,encodeFunc EncodeRequestFunc, decodeFunc DecodeResponseFunc) func(context *gin.Context){ return func(context *gin.Context) { defer func() { if r:=recover();r!=nil{ fmt.Fprintln(gin.DefaultWriter,fmt.Sprintf("fatal error:%s",r)) context.JSON(500,gin.H{"error":fmt.Sprintf("fatal error:%s",r)}) return } }() //参数:=怎么取参数(context) //业务结果,error:=业务最终函数(context,参数) // // //怎么处理业务结果(业务结果) req,err:=encodeFunc(context) //获取参数 if err!=nil{ context.JSON(400,gin.H{"error":"param error:"+err.Error()}) return } rsp,err:=endpoint(context,req) //执行业务过程 if err!=nil{ fmt.Fprintln(gin.DefaultWriter,"response error:",err) context.JSON(400,gin.H{"error":"response error:"+err.Error()}) return } err=decodeFunc(context,rsp) //处理 业务执行 结果 if err!=nil{ context.JSON(500,gin.H{"error":"server error:"+err.Error()}) return } } }
github地址:https://github.com/sunlongv520/go-api-framework
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/p/12906177.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能