获取登录的用户信息以显示
我正在使用https://github.com/kataras/iris
Go网络框架。我有:
- 用户注册
- 用户已验证并登录
- 创建会话并
username
使用用户键(表和结构)进行设置username
现在,这是我用于登录用户的代码:
// Loaded All DB and other required value aboveallRoutes := 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
}
现在,我的问题是,如何将“已记录的用户”值共享给模板中的所有路由。我当前的选项是:
// Loaded all DB and required valueallRoutes := 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)
回答:
您可以使用轻松ctx.Values().Set/Get
使路由的处理程序或中间件之间共享某些内容。
// load session manager oncesess := connectSess()
func authCheck(ctx context.Context) {
session := sess.Start(ctx)
// Load your user here.
// [...]
// Save the returning user to the local storage of this handlers chain, once.
ctx.Values().Set("user", user) // <-- IMPORTANT
}
app.Get("/", func(ctx context.Context) {
// Get the user from our handlers chain's local storage.
user := ctx.Values().Get("user") // <-- IMPORTANT
// Bind the "{{.user}}" to the user instance.
ctx.ViewData("user", user)
// Render the template file.
ctx.View("index.html")
})
app.Get("dashboard", func(ctx context.Context) {
// The same, get the user from the local storage...
user := ctx.Values().Get("user") // <-- IMPORTANT
ctx.ViewData("user", user)
ctx.View("index.html")
})
但我有一些 ,如果您有更多时间请阅读。
当您位于根目录“
/”上时,不必.Party
为了添加中间件(begin(Use
)或finish(Done
))而为它()创建一个参与者,只需使用iris.Application
实例app.Use/Done
。
不要这样写:
allRoutes := app.Party("/", logThisMiddleware, authCheck) { allRoutes.Get("/", myHandler)
}
改为:
app.Use(logThisMiddleware, authCheck)app.Get("/", myHandler)
更容易 。
我
注意到,;
在功能的最后使用的是您的编辑器和gocode
工具,它们会删除它们,当您使用Go编程语言编写程序时,您不应该这样做,而是全部删除;
。
最后,请阅读文档和示例,我们在https://github.com/kataras/iris/tree/master/_examples中提供了许多示例,希望您一切顺利!
以上是 获取登录的用户信息以显示 的全部内容, 来源链接: utcz.com/qa/398027.html