您可以使用轻松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
为了添加中间件(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中提供了许多示例,希望您一切顺利!