Golang Custom Application Context

Hey, I had a question about golang context.

In my application I store a map of all my templates map[string]*template.Template in an ApplicationEngine struct, which is my application framework instance. I am currently using the standard context.Context to pass request scoped values between my middlewares and handlers. I need a way to access that map of templates in order to render a specific template file. What is the best way to do this? Is storing a map of templates even a good idea?

I am currently thinking of adopting a way similar to the gin framework’s context. Gin uses a custom struct that stores a pointer to gin.Engine, which is their application framework instance. They then have a HTML() function on the context struct, which accesses the template map stored in the gin.Engine pointer.

While my question is specific to my need, there is a broader discussion here. Should you use custom structs instead of the “standard” context.Context? Most web frameworks (gobuffalo, gin, echo) seem to handle it this way, but there seems to be no consensus on if it is a good idea, or even what should actually be stored in a context. A pointer to a applicationengine isn’t a request scoped value, so should it even be stored in a context? Maybe a global pointer instead? Or should I do it the easy way and pass the app engine pointer as an argument to my handlers?

I know that contexts are a controversial issue and just want to hear the available options. Any guidance would be greatly appreciated :smiley:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.