一,代码:
middleware.go
package middlewareimport ("fmt""github.com/gofiber/fiber/v2"
)func Middle1(c *fiber.Ctx) error {fmt.Println("middle1 before")err:=c.Next()fmt.Println("middle1 after")return err
}func Middle2(c *fiber.Ctx) error {fmt.Println("middle2 before")err:=c.Next()fmt.Println("middle2 after")return err
}func Middle3(c *fiber.Ctx) error {fmt.Println("middle3 before")err:=c.Next()fmt.Println("middle3 after")return err
}
routes.go
func SetupRoutes(app *fiber.App) {//注意顺序app.Use(middleware.Middle3)app.Use(middleware.Middle2)app.Use(middleware.Middle1)...
二,测试效果:
middle3 before
middle2 before
middle1 beforemiddle1 after
middle2 after
middle3 after
说明:在Next()之前的代码,按use的顺序执行,
在Next()之后的代码,按相反的顺序执行,