Skip to content

Instantly share code, notes, and snippets.

@instabledesign
Last active August 7, 2019 06:25
Show Gist options
  • Save instabledesign/494ffc8bafd5781bb4d43dbe2111cc30 to your computer and use it in GitHub Desktop.
Save instabledesign/494ffc8bafd5781bb4d43dbe2111cc30 to your computer and use it in GitHub Desktop.
package signal
import (
"os"
"os/signal"
)
// This is a really small signal subscriber
// Signal subscriber that allows you to attach a callback to an `os.Signal` notification.
// Usefull to react to any os.Signal.
// It returns an `unsubscribe` function that stops the goroutine and clean allocated object
//
// Example:
// unsubscriber := signal.subscribe(func(s os.Signal) {
// fmt.Println("process as been asked to be stopped")
// }, os.SIGSTOP)
//
// call "unsubscriber()" in order to detach your callback and clean memory
//
// /!\ CAUTION /!\
// If you call it with second arg to `nil`, no signal will be listened
// signal.subscribe(func(s os.Signal) {fmt.Println("NEVER BE CALLED")}, nil)
func Subscribe(callback func(os.Signal), signals ...os.Signal) func() {
signalChan := make(chan os.Signal, 1)
stopChan := make(chan bool, 1)
signal.Notify(signalChan, signals...)
go func() {
for {
select {
case <-stopChan:
signal.Stop(signalChan)
close(stopChan)
close(signalChan)
return
case sig := <-signalChan:
callback(sig)
}
}
}()
return func() {
stopChan <- true
}
}
@instabledesign
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment