go fiber: 多個全域性中介軟體的執行順序

刘宏缔的架构森林發表於2024-11-16

一,程式碼:

middleware.go

package middleware

import (
	"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 before

middle1 after
middle2 after
middle3 after

說明:在Next()之前的程式碼,按use的順序執行,
在Next()之後的程式碼,按相反的順序執行,

相關文章