|
|
|
|
|
by openasocket
1698 days ago
|
|
They can be used to store data scoped to a particular request or unit of work, but most of the time that's not why you would use them. Mostly they are used to control tasks and stop things when needed. Imagine you have a server receiving requests. And for each requests there are multiple things you may have to do: logging metadata, checking the cache, pulling data from your database, etc. Some of that may be done in serial, and other parts might be done in parallel (maybe you've got an SQL database and also a KV store with some ancillary data and you want to grab data from both places at once). But you want to make sure this request doesn't block forever, you want to return a response to the user within a given maximum time frame (even if that is just a 504 Gateway Timeout response), and if you reach the time limit, or one of those things you are doing in parallel fails, you want to quickly shut everything else down. That's what contexts are for, in essence. You make a context object and have each of your independent processes use it. The context object provides a couple ways for you to check and see if the context has been cancelled. The Done() method gives you a channel you can poll on. The Err() method returns non-nil if the context was cancelled. So yeah if you have a bunch of different tasks you want to do and you want to be able to stop all of them at once, you want to use a context. |
|