代码拉取完成,页面将自动刷新
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), ¶ms); e != nil {
FailureGeneric(c, "文件请求参数解析失败 %s", e.Error())
return
}
} else { // 普通API,JSON请求
if e := c.ShouldBindJSON(¶ms); 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)
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。