📥Request context
Request's context was already demonstrated previously. This page gives some tips about general approach to passing objects to handlers. Request context may not always be the best option: it's type-unsafe (you must do explicit type-assertion), it's verbose, . It might sometimes be quite a challenge to update the value in runtime.
Let's consider we need a dynamic web-page. We are going to use the html/template
for it. Reading the file with it would be quite expensive and inefficient, but storing it all the time in memory is also not a good choice, as at the development stage we would like to see the changes instantly. In this case, we can simply make our handler a method to a structure, which would contain our *html.Template
and mutex in order to synchronize access:
Simply share the same underlying structure for multiple handlers and protect it by mutex. This is currently the only way to do DI.
Last updated