1 Star 0 Fork 0

Wsage/go-framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
router.go 1.41 KB
一键复制 编辑 原始数据 按行查看 历史
王少奇 提交于 2021-09-09 16:47 . 恢复
package go_framework
import "net/http"
/**
路由结构
*/
type Route struct {
Controller func(ctx Ctx)
Middleware []Middleware
Route string
}
func (r Route) Run(){
http.HandleFunc(r.Route, r.handle(r.Controller))
}
//注册
func (r *Route) Register(f func(ctx Ctx), middleware []Middleware) *Route {
return r.RegisterController(f).RegisterMiddleware(middleware)
}
//只注册controller
func (r *Route) RegisterController(f func(ctx Ctx)) *Route {
r.Controller = f
return r
}
//只注册middleware
func (r *Route) RegisterMiddleware(middleware []Middleware) *Route {
if len(middleware) <= 0 {
return r
}
if r.Middleware == nil {
r.Middleware = middleware
return r
}
slice := make([]Middleware, len(r.Middleware)+len(middleware))
copy(slice, r.Middleware)
copy(slice[len(r.Middleware):], middleware)
r.Middleware = slice
return r
}
//执行方法
func (r *Route) handle(f func(ctx Ctx)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, request *http.Request) {
ctx := Ctx{Response: w, Request: request, Data: map[string]interface{}{}}
middleware:=r.Middleware
funcArr:=[]func(Ctx){}
funcArr=append(funcArr, func(ctx Ctx){
f(ctx)
});
//新增中间件的处理
j:=0
for i:=len(middleware)-1;i>=0;i--{
index:=i
t:=j
funcArr=append(funcArr, func(ctx Ctx){
middleware[index].Handle(ctx,funcArr[t]);
})
j++
}
funcArr[len(funcArr)-1](ctx)
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/scottq/go-framework.git
git@gitee.com:scottq/go-framework.git
scottq
go-framework
go-framework
v1.1.43-beta

搜索帮助