2018-10-25 00:36:39 +03:00
|
|
|
package interrupt
|
2018-10-24 00:00:55 +03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"syscall"
|
|
|
|
)
|
|
|
|
|
2018-10-27 12:51:50 +03:00
|
|
|
// Cleaner type refers to a function with no inputs that returns an error
|
2018-10-25 00:11:36 +03:00
|
|
|
type Cleaner func() error
|
2018-10-24 00:00:55 +03:00
|
|
|
|
2018-10-25 00:27:43 +03:00
|
|
|
var cleaners []Cleaner
|
2018-10-25 00:55:02 +03:00
|
|
|
var active = false
|
2018-10-24 00:00:55 +03:00
|
|
|
|
2018-10-27 12:51:50 +03:00
|
|
|
// RegisterCleaner is responsible for registering a cleaner function. When a function is registered, the Signal watcher is started in a goroutine.
|
2018-10-25 01:06:10 +03:00
|
|
|
func RegisterCleaner(f ...Cleaner) {
|
|
|
|
for _, fn := range f {
|
2018-10-26 00:07:02 +03:00
|
|
|
cleaners = append([]Cleaner{fn}, cleaners...)
|
2018-10-25 01:06:10 +03:00
|
|
|
if !active {
|
|
|
|
active = true
|
|
|
|
go func() {
|
|
|
|
ch := make(chan os.Signal, 1)
|
|
|
|
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
|
|
|
|
<-ch
|
|
|
|
// Prevent un-terminated ^C character in terminal
|
|
|
|
fmt.Println()
|
2018-10-27 12:51:50 +03:00
|
|
|
errl := clean()
|
2018-10-26 00:07:02 +03:00
|
|
|
for _, err := range errl {
|
|
|
|
fmt.Println(err)
|
|
|
|
}
|
2018-10-25 01:06:10 +03:00
|
|
|
os.Exit(1)
|
|
|
|
}()
|
|
|
|
}
|
2018-10-24 00:00:55 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-27 12:51:50 +03:00
|
|
|
// clean invokes all registered cleanup functions, and returns a list of errors, if they exist.
|
|
|
|
func clean() (errorlist []error) {
|
2018-10-24 00:00:55 +03:00
|
|
|
for _, f := range cleaners {
|
2018-10-26 00:07:02 +03:00
|
|
|
err := f()
|
|
|
|
if err != nil {
|
|
|
|
errorlist = append(errorlist, err)
|
|
|
|
}
|
2018-10-24 00:00:55 +03:00
|
|
|
}
|
2018-10-25 00:27:43 +03:00
|
|
|
cleaners = []Cleaner{}
|
2018-10-26 00:07:02 +03:00
|
|
|
return
|
2018-10-24 00:00:55 +03:00
|
|
|
}
|