【发布时间】:2022-01-05 06:49:32
【问题描述】:
我是一名 nodejs 开发人员,目前正在学习 golang 以扩展我的知识。在 express 中,我们可以使用路由器作为中间件。
使用特定中间件创建用户路由器:
// ** routes/userRoutes.js
// import authontication
// import handlers
const userRoutes = express.Router()
userRoutes.use(auth.protect) // ** middleware here
userRoutes.get('/', handlers.getUsers}
userRoutes.post('/create-voter', handlers.createUser}
export default userRoutes
我们可以在 app.js 中使用这个路由作为中间件。 (可能是我写错了)
// app.js
const app = express();
app.use(express.json()); // a middleware
app.use(morgan('dev')); // a middleware
app.use('/api/users', userRoutes) // route as middleware
这样,每条路由(例如“用户”、“评论”)都可以放置在具有特定中间件和端点的文件中。
我试图在 gin-gonic/gin 中实现相同的逻辑。 我试过了:
func bookRoutesInit() *gin.Engine {
route := gin.New()
route.GET("/users", controllers.GetBooks)
return route
}
func startServer() {
app := gin.New()
bookRoutes := bookRoutesInit()
utils.ConnectDatabase()
app.Use(bookRoutes) /*
Error: cannot use bookRoutes (variable of type *gin.Engine)
as gin.HandlerFunc value in argument to app.Use
*/
app.Run(":5500")
}
我发现只有gin.HandlerFunc可以用作中间件。我需要类似express.Router 的杜松子酒。欢迎任何帮助或建议
【问题讨论】:
-
Gin(和其他 Go web 框架)中的中间件与您在 express 中的理解不同。您想要的可能是一种很好地分隔路线组的方法
-
@blackgreen 谢谢。至少这是我在做更多研究后得出的结论
-
@blackgreen 是的。您建议的答案实际上解决了我的问题
-
作为记录,在某种程度上可以使用类似于中间件的方式使用 Gin
Engine,但我认为这是针对非常专业的用例。 ——好吧,我会继续建议复制然后