-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctx.go
51 lines (41 loc) · 960 Bytes
/
ctx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package ctx
import (
"context"
"fmt"
"os"
"os/signal"
)
type ConsoleAppContext struct {
ctx context.Context
cancel context.CancelFunc
osSigChan chan os.Signal
}
var consoleAppCtx *ConsoleAppContext
func init() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
osSigChan := make(chan os.Signal, 1)
consoleAppCtx = &ConsoleAppContext{ctx: ctx,
cancel: cancel,
osSigChan: osSigChan}
signal.Notify(osSigChan, os.Interrupt)
// trap Ctrl+C and call cancel on the context
}
func GetContext() context.Context {
return consoleAppCtx.ctx
}
func WaitOnCtrlCSignalOrCompletion() {
select {
case <-consoleAppCtx.osSigChan:
fmt.Println("program terminated because of user cancellation")
consoleAppCtx.cancel()
case <-consoleAppCtx.ctx.Done():
}
}
func CleanUp() {
consoleAppCtx.cleanUp()
}
func (consoleAppCtx *ConsoleAppContext) cleanUp() {
signal.Stop(consoleAppCtx.osSigChan)
consoleAppCtx.cancel()
}