简体   繁体   中英

Golang (iris webframework) share between handlers

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?

// 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM