Skip to content

Instantly share code, notes, and snippets.

@rogerwelin
Created May 20, 2021 13:13
Show Gist options
  • Save rogerwelin/b644c046730158cd24e45dadc0396dea to your computer and use it in GitHub Desktop.
Save rogerwelin/b644c046730158cd24e45dadc0396dea to your computer and use it in GitHub Desktop.
context sigint
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"time"
)
func doSomethingAwesome(ctx context.Context, msg string) {
for {
select {
case <-ctx.Done():
// run cleanup logic here
log.Println(ctx.Err())
fmt.Println("shutting down gracefully - running cleanup")
return
default:
time.Sleep(200 * time.Millisecond)
fmt.Print(".")
}
}
}
func main() {
// create context that listens for SIGINT from OS
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
doSomethingAwesome(ctx, "ello")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment