0 Star 0 Fork 0

shallot / Go开发工具集

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
router.go 1.52 KB
一键复制 编辑 原始数据 按行查看 历史
shallot 提交于 2024-01-08 13:58 . 移除gitee.com的引用。
package network
import (
"github.com/gin-gonic/gin"
)
// 通用路由处理函数
type RouterHandler[P any, R any] func(*gin.Context, P) (R, error)
// 通用路由处理的选项
type RouterOptions struct {
FileJsonKey string // 有值时表示是文件路由,记录Json字段存放的PostForm键名称
NoRequest bool // 无需解析请求,默认值false
NoResponse bool // 无需返回应答,默认值false
}
// 路由封装函数
func Router[P any, R any](
handler RouterHandler[P, R],
opt *RouterOptions,
) gin.HandlerFunc {
return func(c *gin.Context) {
var params P
if opt == nil {
opt = &RouterOptions{
FileJsonKey: "",
NoRequest: false,
NoResponse: false,
}
}
if !opt.NoRequest {
if len(opt.FileJsonKey) > 0 { // 文件,FORM表单
fileJsonStr, ok := c.GetPostForm(opt.FileJsonKey)
if !ok {
FailureGeneric(c, "文件请求参数%s不存在", opt.FileJsonKey)
return
}
if e := jsonUnmarshal([]byte(fileJsonStr), &params); e != nil {
FailureGeneric(c, "文件请求参数解析失败 %s", e.Error())
return
}
} else { // 普通API,JSON请求
if e := c.ShouldBindJSON(&params); e != nil {
FailureGeneric(c, "请求参数解析失败 %s", e.Error())
return
}
}
}
rsp, err := handler(c, params)
if !opt.NoResponse {
if err != nil {
if e, ok := err.(interface{ Code() int }); ok {
Failure(c, e.Code(), err.Error())
} else {
FailureGeneric(c, err.Error())
}
} else {
Success[R](c, rsp)
}
}
}
}
Go
1
https://gitee.com/gxsshallot/gotool.git
git@gitee.com:gxsshallot/gotool.git
gxsshallot
gotool
Go开发工具集
2324c52c6c14

搜索帮助