I have a question regarding a specific sentence here - The withValue function should not be used for passing parameters to functions...
So if for example, I have an HTTP server with the common structure of
controller -> service -> repository.
I find myself passing too many parameters from one service to another. So my thinking was to create a global context object which will be available to all of them without the need to pass it as a parameter (of course all the data in it are related to a specific request)
But I am a bit confused now, the context.WithValue() should not be used for this case? and if not, do you have any idea how to achieve that goal?
I do not have a definite answer to your question, But you stated all the data are related to a specific request . creating a global context object might work fine! one of the reasons I advised not to use the withValue function as a parameter is that you loose typesafety at compile time since context values are basically stored as type interface{}! I hope this helps, You could check out this article for more about context peter.bourgon.org/blog/2016/07/11/...
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hello Ghvst and thank you for this great article!
I have a question regarding a specific sentence here -
The withValue function should not be used for passing parameters to functions...
So if for example, I have an HTTP server with the common structure of
controller -> service -> repository.
I find myself passing too many parameters from one service to another. So my thinking was to create a global
context
object which will be available to all of them without the need to pass it as a parameter (of course all the data in it are related to a specific request)But I am a bit confused now, the
context.WithValue()
should not be used for this case? and if not, do you have any idea how to achieve that goal?Thank a lot!
Hello Ron!
I am glad you enjoyed this post.
I do not have a definite answer to your question, But you stated all the data are related to a specific request . creating a global context object might work fine! one of the reasons I advised not to use the withValue function as a parameter is that you loose typesafety at compile time since context values are basically stored as type interface{}! I hope this helps, You could check out this article for more about context peter.bourgon.org/blog/2016/07/11/...