Catching Ctrl-C by trapping operating system signals in Go
May 15, 2021
It’s easy to forget that Ctrl-C (or other non-drastic program termination signals) doesn’t have to mean that your program has to terminate on the spot without getting a chance to say goodbye. The tragedy is that your program won’t even run its deferred cleanup functions on exit by default when hit by Ctrl-C:
Go provides signal.Notify in its standard library so that we can catch operating systems via a channel. But even better (for this purpose) is signal.NotifyContext, with which we can create a context that will fire when an interrupt signal is raised:
An as easy as that, we can cleanup our Go programs gracefully.