git.zd.zone/hrpc/hrpc@v0.0.12/life/life.go (about) 1 // Package life will control the life of the program 2 // If you have some cleaning operations that the program needs to handle 3 package life 4 5 import ( 6 "os" 7 "os/signal" 8 "syscall" 9 ) 10 11 // Listener is a type of func() 12 type Listener func() 13 14 var ( 15 exitListeners []Listener 16 restartListeners []Listener 17 ) 18 19 // WhenExit will register a set of destructor functions 20 func WhenExit(liss ...Listener) { 21 exitListeners = append(exitListeners, liss...) 22 } 23 24 // WhenRestart ... 25 func WhenRestart(liss ...Listener) { 26 restartListeners = append(restartListeners, liss...) 27 } 28 29 // Start should be used at the end of main() function because it will block the program waitting for signals 30 func Start() { 31 c := make(chan os.Signal, 1) 32 signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) 33 for { 34 switch <-c { 35 case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT: 36 for _, lis := range exitListeners { 37 lis() 38 } 39 return 40 case syscall.SIGHUP: 41 for _, lis := range restartListeners { 42 lis() 43 } 44 default: 45 // Others 46 return 47 } 48 } 49 }