Golang(iris webframework)在处理程序之间共享

huangapple go评论74阅读模式
英文:

Golang (iris webframework) share between handlers

问题

我目前正在使用iris web框架,由于问题跟踪器上无法提问,社区聊天也没有活跃,所以我希望在这里得到帮助。

我需要将数据传递给c.Render函数。

我有一个处理程序,用于检查用户是否已登录。如果用户未登录,我应该在HTML页面中添加一个额外的按钮。

iris.Use(userHandler{})

type userHandler struct{
    Allow bool
}

func (u userHandler) Serve(c *iris.Context) {
    ...
	if isLogged {
		// 当我从另一个中间件(c.Next)调用c.Render时,它应该知道用户已登录
	}
	c.Next()
}

所以是否可以向c.Render函数添加一些默认数据?

英文:

I am currently using the iris web framework and since questions cannot be asked on the issue tracker and the community chat is dead I am asking this here hoping someone helps me out.

I need to pass data to the c.Render function

I have a handler that checks if the user is logged or not. If its not logged I should add an extra button to the html page

iris.Use(userHandler{})

type userHandler struct{
    Allow bool
}

func (u userHandler) Serve(c *iris.Context) {
    ...
	if isLogged {
		// When I call from another middleware (c.Next) c.Render it should know that the user is logged in
	}
	c.Next()
}

So is it possible to add some default data to the c.Render function?

答案1

得分: 2

// 检索本地存储或先前的处理程序,
// 这是处理程序可以共享值的方式,使用上下文的Values()方法。
logged := ctx.Values().Get("logged")

// 设置模板数据 {{.isLogged}}
ctx.ViewData("isLogged", logged)

// 最后,渲染mypage.html
ctx.View("mypage.html")

"logged" 可以通过以下方式设置为您的中间件/任何先前的处理程序:

ctx.Values().Set("logged", false)

所有这些都在示例中有描述,欢迎您在这里探索其中一些:https://github.com/kataras/iris/tree/master/_examples

Happy Coding!

英文:
// retrieve local storage or previous handler,
// this is how handlers can share values, with the context's Values().
logged := ctx.Values().Get("logged")

// set template data {{.isLogged}}
ctx.ViewData("isLogged", logged)

// and finally, render the mypage.html
ctx.View("mypage.html")

"logged" can be set to your middleware/any previous handler by:

ctx.Values().Set("logged", false)

All these are described to the examples, you're welcome to explore some of those there: https://github.com/kataras/iris/tree/master/_examples

Happy Coding!

huangapple
  • 本文由 发表于 2016年9月11日 07:33:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/39431521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定