Context
Context is a way of passing information or enforcing timeouts when calling functions throughout your application as a single requests goes from layer to layer. This is usually passed as the first parameter in your functions if being used.
go
// create an empty context
ctx := context.Background()
// append value to context
ctx = context.WithValue(ctx, "key", "value")
value := ctx.Value("key")
Timeouts
go
ctx, cancel := context.WithTimeout(context.Background(), 2 * time.Second)
defer cancel() // can call before timeout
go longRunningFunc(ctx)
select {
case <-ctx.Done():
fms.Println("done blocking main thread also!")
}
time.Sleep(2*time.Second)
func longRunningFunc(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("timed out")
return
default:
fmt.Println("still processing")
}
time.Sleep(1*time.Second)
}
}