This little Go program does not run the defer statement when you interrupt by pressing ctrl-C:
package main
import "fmt"
func main() {
defer fmt.Println("Shutting down...")
for {
}
}
> go run interrupt.go
^Csignal: interrupt
>
You have to actually trap the signal and handle it. Fortunately that’s super simple in Go:
package main
import "fmt"
import "os"
import "os/signal"
var shutdown = make(chan struct{})
func main() {
defer fmt.Println("Shutting down...")
go func () {
waitForInterrupt := make(chan os.Signal, 1)
signal.Notify(waitForInterrupt, os.Interrupt)
<-waitForInterrupt
close(shutdown)
}()
for {
select {
case <-shutdown:
return
default:
}
}
}
> go run trapped_interrupt.go
^CShutting down...
>
References
You can learn more about…
- …channels in the Tour of Go
- …signals in the Go docs
- …this pattern in this StackOverflow answer