我正在使用https://github.com/kataras/iris Go 网络框架。我有:
- 用户注册
- 用户验证并登录
- 会话创建并
username使用用户键设置(表和结构)username
现在,这是我的登录用户代码:
// Loaded All DB and other required value above
allRoutes := app.Party("/", logThisMiddleware, authCheck) {
allRoutes.Get("/", func(ctx context.Context) {
ctx.View("index.html");
});
}
在 authcheck 中间件中
func authcheck(ctx context.Context) {
// Loaded session.
// Fetched Session key "isLoggedIn"
// If isLoggedIn == "no" or "" (empty)
// Redirected to login page
// else
ctx.Next()
}
我的会话功能
func connectSess() *sessions.Sessions {
// Creating Gorilla SecureCookie Session
// returning session
}
现在,我的问题是,如何将 Logged User 值共享给模板中的所有路由。我当前的选择是:
// Loaded all DB and required value
allRoutes := app.Party("/", logThisMiddleware, authCheck) {
allRoutes.Get("/", func(ctx context.Context) {
// Load Session again
// Fetch username stored in session
// Run Query against DB
// Share the user struct value.
// Example ctx.ViewData("user", user)
ctx.View("index.html");
});
allRoutes.Get("dashboard", func(ctx context.Context) {
// Load Session again
// Fetch username stored in session
// Run Query against DB
// Share the user struct value.
// Example ctx.ViewData("user", user)
ctx.View("index.html");
});
}
但是上面代码的问题是,我将不得不为每条路线编写会话,并为我运行的每条路线再次运行查询,而不是共享。
我觉得,必须有更好的方法来做到这一点,而不是为每个路由加载会话两次,其中一个在authCheck中间件中,第二个在内部allRoutes.Get路由中。
我需要关于如何优化这一点的想法,并且只需编写一次代码而不是在下面为每条路线重复,就可以将用户数据共享到模板
// Load Session again
// Fetch username stored in session
// Run Query against DB
// Share the user struct value.
// Example ctx.ViewData("user", user)