Hello. Please explain in what cases you need to use this package and why is it needed?
1 answer
A request came to you (maybe from an external service, from a browser or, maybe, from a part of your own program, it doesn't matter). Some function was called for processing, she called again, she still, she still.
And somewhere in the deep need to make a decision - what to answer the request. Or, perhaps, it’s time to give up and terminate (for example, by a timeout), or you didn’t want to wait so long and the connection was cut off and you don’t need to process it.
In the context of all the information that is needed for processing, to make a decision. Sometimes - the connection is terminated there. But first of all the context is a lot of information.
As a rule, this information can be put in context first, the upper function is mandatory. Nested functions can complement the context.
Somewhere at the very bottom, in the most deeply nested function, you, as a saucer in the context, contain a lot of information for making a decision.
You can do this by simply passing variables inside. But with each level, the number of variables can increase.
The context is not something that is obviously more convenient, but variously versatile. Although for simple cases, I would have done without it. With him all the same is not very convenient. For example, typical for contexts is storing values in map [string] interface {}, which makes it impossible for you to check types at the compilation stage. So in simple cases, you can do without this; instead of the context, using variables of well-defined and well-defined types will work more reliably. But in difficult cases these variables will be too many, they can be of different types, not all of them will always be used, so the map [string] interface {} variant is often used.
In the case of / x / net / context, it uses interfaces, which makes it seem less obvious, but more type-safe. The article https://habrahabr.ru/post/269299/ describes a little bit what alternative contexts are. All of them are easier to understand, more trivial, similar to the usual map [string] interface {}. But this context, though more brain-consuming, but more reliable, since part of the errors catches the compiler.
Typical use in web applications, for example (it is possible and not only in web applications, but this is me for example) - initially we put there the request data, preferably slightly processed. "/ api / v1 / labuda / 123" —for example RESTful API — getting labuda # 123 — put the Labuda {} object in the context, put the DatabaseConnection object on the next level, and retrieve the data at the very bottom using the DatabaseConnection and put it in the Labuda {}, the result is also returned to the top through the context.