一,目录结构:
二,代码
1,中间件代码
package middlewareimport ("fmt""github.com/gofiber/fiber/v2""industry/config"
)// token校验
func CheckUser(c *fiber.Ctx) error {token:=c.Query("token")fmt.Println("token:",token)if token == "" {return c.Status(200).JSON(config.Error("参数token不存在"))} else {if token == "123" {var userId = 4c.Locals("userId", userId)} else {return c.Status(200).JSON(config.Error("参数token错误"))}}return c.Next()
}
2,控制器
func NewUserController() *UserController {return &UserController{}
}func (uc *UserController) GetUser(c *fiber.Ctx) error {fmt.Println("hello","user")userId := c.Locals("userId")str2 := fmt.Sprintf("%v", userId)fmt.Println(str2)// 处理获取用户的逻辑return c.SendString("获取用户信息userId:"+str2)
}func (uc *UserController) CreateUser(c *fiber.Ctx) error {// 处理创建用户的逻辑userId := c.Locals("userId")str2 := fmt.Sprintf("%v", userId)fmt.Println(str2)return c.SendString("创建用户:"+str2)
}
3,路由:
package routesimport ("github.com/gofiber/fiber/v2""industry/config""industry/controller""industry/middleware"
)func SetupRoutes(app *fiber.App) {//用户模块userController := controller.NewUserController()user := app.Group("/user")user.Get("/info" ,middleware.CheckUser, userController.GetUser)user.Get("/add", userController.CreateUser)//找不到路径时的处理app.Use(func(c *fiber.Ctx) error {return c.Status(fiber.StatusNotFound).JSON(config.Error("不存在的访问路径"))})}
也可以把中间件添加给整组,如下:
//用户模块userController := controller.NewUserController()user := app.Group("/user",middleware.CheckUser)user.Get("/info" , userController.GetUser)user.Get("/add", userController.CreateUser)