[英]Fetching Logged in User Info for display
我正在使用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)
您可以很容易地使用ctx.Values().Set/Get
在路由的处理程序或中间件之间进行共享。
// load session manager once
sess := 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
)以添加中间件(开始( Use
)或完成( Done
)),只需使用iris.Application
实例, app.Use/Done
.使用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 上有很多,希望你一切顺利!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.