Lorenz Brun | 78e5905 | 2021-12-15 18:46:18 +0100 | [diff] [blame] | 1 | package clicontext |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "os" |
| 6 | "os/signal" |
| 7 | ) |
| 8 | |
| 9 | // WithInterrupt returns a context for use in a command-line utility. It gets |
| 10 | // cancelled if the user interrupts the command, for example by pressing |
| 11 | // Ctrl+C. |
| 12 | func WithInterrupt(parent context.Context) context.Context { |
| 13 | ctx, cancel := context.WithCancel(parent) |
| 14 | c := make(chan os.Signal, 1) |
| 15 | signal.Notify(c, os.Interrupt) |
| 16 | go func() { |
| 17 | <-c |
| 18 | cancel() |
| 19 | }() |
| 20 | return ctx |
| 21 | } |