方式1
package main
import (
"fmt"
"net/http"
)
// 中间件函数类型
type MiddlewareFunc func(http.HandlerFunc) http.HandlerFunc
// 自定义中间件1
func LoggerMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
fmt.Println("Logging:", req.Method, req.URL.Path)
next(w, req)
}
}
// 自定义中间件2
func LoggerMiddleware2(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
fmt.Println("Logging2:", req.Method, req.URL.Path)
next(w, req)
}
}
// 使用中间件
func UseMiddleware(handler http.HandlerFunc, middleware ...MiddlewareFunc) http.HandlerFunc {
for i := len(middleware) - 1; i >= 0; i-- {
handler = middleware[i](handler)
}
return handler
}
// 处理请求的处理程序
func myHandler(w http.ResponseWriter, req *http.Request) {
fmt.Println("do handler")
w.Write([]byte("Hello, World!"))
}
func main() {
// 创建一个个中间件处理程序
handlerWithMiddleware := UseMiddleware(myHandler, LoggerMiddleware, LoggerMiddleware2)
http.HandleFunc("/", handlerWithMiddleware)
fmt.Println("Server is running on localhost:8080")
http.ListenAndServe(":8080", nil)
}
方式2 推荐
package main
import (
"fmt"
"math"
)
const abortIndex = math.MaxInt8 / 2
// 中间件结构体
type Context struct {
Handlers []func(c *Context) //需要执行的方法切片
index int8 //偏移量
}
// 注册方法到中间件
func (this *Context) Use(f func(c *Context)) {
this.Handlers = append(this.Handlers, f)
}
// 执行下一个方法
func (this *Context) Next() {
if this.index < int8(len(this.Handlers)) {
this.index++
this.Handlers[this.index](this)
}
}
// 执行handlers里面的第一个方法
func (this *Context) Run() {
this.Handlers[0](this)
}
func (this *Context) GET(path string, f func(c *Context)) {
this.Handlers = append(this.Handlers, f)
}
// 终止
func (this *Context) Abort() {
this.index = abortIndex
}
//主方法
func main() {
c := &Context{}
c.Use(MiddlewareOne())
c.Use(MiddlewareTwo())
c.GET("/get", func(c *Context) {
fmt.Println("执行具体方法")
})
c.Run()
}
//中间件一
func MiddlewareOne() func(c *Context) {
return func(c *Context) {
fmt.Println("MiddlerOne Start")
c.Next()
fmt.Println("MiddlerOne End")
}
}
//中间件二
func MiddlewareTwo() func(c *Context) {
return func(c *Context) {
fmt.Println("MiddlerTwo Start")
c.Next()
fmt.Println("MiddlerTwo End")
}
}
//中间件三
func MiddlewareThree() func(c *Context) {
return func(c *Context) {
fmt.Println("MiddlerThree Start")
c.Next()
fmt.Println("MiddlerThree End")
}
}