1package cleaner
2
3import (
4 "fmt"
5 "os"
6 "os/signal"
7 "syscall"
8)
9
10type t func() error
11
12var cleaners []t
13var inactive bool
14
15// Register a cleaner function. When a function is registered, the Signal watcher is started in a goroutine.
16func Register(f t) {
17 cleaners = append(cleaners, f)
18 if !inactive {
19 inactive = false
20 go func() {
21 ch := make(chan os.Signal, 1)
22 signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
23 <-ch
24 fmt.Println("")
25 clean()
26 os.Exit(1)
27 }()
28 }
29}
30
31// Clean invokes all registered cleanup functions
32func clean() {
33 fmt.Println("Cleaning")
34 for _, f := range cleaners {
35 _ = f()
36 }
37 cleaners = []t{}
38}