Skip to content

Instantly share code, notes, and snippets.

@andreleoni
Created August 11, 2020 01:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreleoni/9c6819eb7b4f7c914ac4faa080551a09 to your computer and use it in GitHub Desktop.
Save andreleoni/9c6819eb7b4f7c914ac4faa080551a09 to your computer and use it in GitHub Desktop.
context studies
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(
context.Background(),
time.Duration(3*time.Second))
defer cancel()
go func(ctx context.Context) {
defer cancel()
simulate a process that takes 2 second to complete
time.Sleep(1 * time.Second)
}(ctx)
select {
case <-ctx.Done():
switch ctx.Err() {
case context.DeadlineExceeded:
fmt.Println("context timeout exceeded")
case context.Canceled:
// spew.Dump(context)
fmt.Println("context cancelled by force. whole process is complete")
}
case <-time.After(2 * time.Second): // Successfully
fmt.Println("without error")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment