golang 中间件的实现本质:
写一个func,接受handler并且返回handler
把私货写在func里面,从而实现把你要写的操作执行了之后,再把原有的流程进行下去
一个好的中间件有一个责任就是可插拔并且自足。
例子:
package main
import (
"fmt"
"github.com/devfeel/dotweb"
)
func main() {
app := dotweb.New()
// App注册中间件
app.Use(NewSessionAuth())
// 开启SESSION
app.HttpServer.SetEnabledSession(true)
// 设置路由 输出字符串 Hello Dotweb
app.HttpServer.GET("/", func(ctx dotweb.Context) error {
method := ctx.Request().Method
return ctx.WriteString("Hello Dotweb\n" + "Method:" + method)
})
//开启服务 端口号
fmt.Println("dotweb.StartServer => 8080")
err := app.StartServer(8080)
fmt.Println("dotweb.StartServer error => ", err)
}
// SessionAuth 结构体
type SessionAuth struct {
dotweb.BaseMiddlware
}
// Handle 处理程序
func (m *SessionAuth) Handle(ctx dotweb.Context) error {
fmt.Println("SessionID &