1 Star 1 Fork 0

Jess/gin-auto-route

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
route.go 1.01 KB
一键复制 编辑 原始数据 按行查看 历史
jesuspan 提交于 2020-12-26 14:04 . pkg name优化
package ginAutoRoute
import (
"github.com/gin-gonic/gin"
"net/http"
"reflect"
"strings"
)
var methods = make(map[string]map[string]reflect.Value)
func AutoRoute(s interface{}) gin.HandlerFunc {
return func(c *gin.Context) {
action := c.Param("action")
realAction := strings.ToLower(action)
rt := reflect.TypeOf(s)
pkgName := rt.String()
v, ok := methods[pkgName][realAction]
if !ok && len(methods[pkgName]) == 0 {
rv := reflect.ValueOf(s)
methods[pkgName] = make(map[string]reflect.Value)
for i := 0; i < rv.NumMethod(); i++ {
fn := rv.Method(i)
ft := rt.Method(i)
methods[pkgName][strings.ToLower(ft.Name)] = fn
}
v, ok = methods[pkgName][realAction]
if !ok && len(methods[pkgName]) > 0 {
http.NotFound(c.Writer, c.Request)
c.Abort()
return
}
} else if !ok && len(methods[pkgName]) > 0 {
http.NotFound(c.Writer, c.Request)
c.Abort()
return
}
arguments := make([]reflect.Value, 1)
arguments[0] = reflect.ValueOf(c) // *gin.Context
v.Call(arguments)
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/wiifan/gin-auto-route.git
git@gitee.com:wiifan/gin-auto-route.git
wiifan
gin-auto-route
gin-auto-route
master

搜索帮助