Skip to content

Instantly share code, notes, and snippets.

@aquiseb
Last active September 12, 2022 19:54
Show Gist options
  • Save aquiseb/2f180213d310aa16b4b8c4e637be9441 to your computer and use it in GitHub Desktop.
Save aquiseb/2f180213d310aa16b4b8c4e637be9441 to your computer and use it in GitHub Desktop.
Golang context package examples
package main
import (
"bufio"
"context"
"fmt"
"log"
"os"
"time"
)
func withTimeOut() {
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
sleepAndTalk(ctx, 5*time.Second, "Hello withTimeOut!")
}
func withCancel() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
go func() {
s := bufio.NewScanner(os.Stdin)
s.Scan()
cancel()
}()
sleepAndTalk(ctx, 5*time.Second, "Hello withCancel!")
}
func background() {
ctx := context.Background()
sleepAndTalk(ctx, 5*time.Second, "Hello background!")
}
func sleepAndTalk(ctx context.Context, d time.Duration, s string) {
select {
case <-time.After(d):
fmt.Println(s)
case <-ctx.Done():
log.Println(ctx.Err())
}
}
func main() {
background()
withCancel()
withTimeOut()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment