Last active
September 12, 2022 19:54
-
-
Save aquiseb/2f180213d310aa16b4b8c4e637be9441 to your computer and use it in GitHub Desktop.
Golang context package examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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