您可以使用轻松
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)更容易 阅读和理解 。
我 还
注意到,
;在功能的最后使用的是您的编辑器和
gopre工具,它们会删除它们,当您使用Go编程语言编写程序时,您不应该这样做,而是全部删除
;。
最后,请阅读文档和示例,我们在https://github.com/kataras/iris/tree/master/_examples中提供了许多示例,希望您一切顺利!



