Go to global variables that are not covered by goroutines
I write CMS in go and have session type (user ID, page content to be rendered, etc.) Ideally, I want this type to be a global variable, so I don't have to propagate it through all nested functions, but having a global variable like this obviously means that every new session will overwrite its predecessor, which will be an epic failure for unnecessary
Some languages provide a way to keep global variables in a thread. The thread remains in the thread (that is, the global value is sandboxed in the thread) Although I know goroutines have no threads, I just want to know if there is a similar method for me to use, or if I have to pass a local pointer to my session type through different nested routines
I guess the channel won't do that? From what I can collect (please correct me if I am wrong here), but they are basically just a safe way to share global variables?
Editor: I forgot this question! Anyway, any curious person's update This question was written back when I first started using go. CMS is basically my first project I come from a c background familiar with POSIX threads, but I soon realized that a better way is to write code in the pattern function design and pass the session object as a pointer in the function parameter This gives me the context - sensitive local scope I focus on and minimizes the amount of data I copy However, as a 7-year-old project and a project just turning to go, it can be said that the project can be significantly rewritten anyway because there are many mistakes This is another day's focus - at present it works and I have enough other projects
Solution
You will want to use something like context:
http://blog.golang.org/context
Basically, the pattern is to create a context for everything you want to do (in your case, a web request.) Use context Withvalue embeds multiple variables in the context It is then always passed as the first parameter to other methods that work further in other goroutines
Getting the required variables from the context is to call context Value from any goroutine Link from above:
I have an implementation where I explicitly send variables as method parameters, and I find that embedding these variables using context significantly cleans up my code
Using context is also helpful because it provides a way to end long-running tasks by using the concept of channel, selection, and completion channel Please refer to this article for a good basic review and Implementation:
http://blog.golang.org/pipelines
I suggest reading the pipeline article first to understand how to manage the communication between goroutines, and then the context article to better understand how to upgrade and start embedded variable passing
Good luck!