Back to articles
Beginners' guide to Go Contexts: The Magic Controller of Goroutines
How-ToSystems

Beginners' guide to Go Contexts: The Magic Controller of Goroutines

via Dev.toDebdut Chakraborty

We've all used contexts, usually by passing them to functions that require them, like HTTP handlers or database queries. But what exactly are contexts, and how do they work under the hood? In Go, a Context is essentially a signal. It travels through your functions to tell them when they should stop working because the data is no longer needed. The Basic Check The most fundamental way to use a context is to check its state manually. This is perfect for long-running loops or heavy calculations. If a function is a "one-off" and finishes instantly, a context doesn't add much value. However, for a loop like this: func process ( ctx context . Context ) { for i := range 1000000 { // check if the signal says we should stop if err := ctx . Err (); err != nil { fmt . Println ( "stopping early:" , err ) return } // simulate some work _ = i } } If we didn't have that if err := ctx.Err() check, the goroutine would keep spinning even if the user who started it has already disconnected or timed out.

Continue reading on Dev.to

Opens in a new tab

Read Full Article
2 views

Related Articles