zhufuyi / sponge

Sponge is a powerful Go development framework, it's easy to develop web and microservice projects.
https://go-sponge.com
MIT License
1.26k stars 125 forks source link

router 的使用请教 #63

Open hanwenbo opened 5 days ago

hanwenbo commented 5 days ago

假如我使用了 group.Use(middleware.Auth()) // all of the following routes use jwt authentication 那么这整个group就会验证权限, 但部分接口是不需要验证的,如果我在router.go里再单独去定义 会有点不方便,请问大哥有什么好的方法吗

func dishRouter(group *gin.RouterGroup, h handler.DishHandler) { //group.Use(middleware.Auth()) // all of the following routes use jwt authentication // or group.Use(middleware.Auth(middleware.WithVerify(verify))) // token authentication // .....这里额外还想特殊对待一些路由是否可以? }

zhufuyi commented 5 days ago

可以对指定路由添加鉴权中间件

func dishRouter(group *gin.RouterGroup, h handler.DishHandler) {
    group.POST("/dish", middleware.Auth(), h.Create)  // 添加了鉴权中间件
    group.DELETE("/dish/:id", h.DeleteByID) // 没有鉴权
}
hanwenbo commented 5 days ago

感谢~ 我去试试

hanwenbo commented 5 days ago

我发现一个问题,我不知道是不是bug

routers 文件夹有很多模块,那么init会自动初始化, 假如你给任意一个模块,比如user吧加一个

func userRouter(group *gin.RouterGroup, h handler.UserHandler) {
    // 需要认证的路由
    group.Use(AuthMiddleware())
    group.GET("/user/:id", AuthMiddleware(), h.GetByID)
    group.PUT("/user", AuthMiddleware(), h.Update)

}
func searchRouter(group *gin.RouterGroup, h handler.UserHandler) {
    // 注意 这里我没给group.Use(AuthMiddleware()),所以这个路由不需要认证,但实际它是验证了。
    group.GET("/search/:id", AuthMiddleware(), h.GetByID)
    group.PUT("/search", AuthMiddleware(), h.Update)
}

看作者的源码给我感觉是每个模块的group是分离的,但是实际操作来看不是

不确定这是不是bug