我是一名 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
杜松子酒的东西。欢迎任何帮助或建议