Handling Ctrl-Z's and SIGTERM's With Go

Jul 12, 2015 Golang


When working with blocking/waiting Golang binaries, you’ll be met with the following when you attempt to interrupt it:

Spitfire $ go run test.go
2016/01/31 21:46:52 --> Starting Second server on port: 9090
2016/01/31 21:46:52 --> Starting First server on port: 8080
^Cexit status 2

This might not be a huge problem, but if you’re vendor’ing out code to customers, I personally feel it’s unprofessional. It does not give comfort to the end-user in your abilities.

To solve this problem, we can create a Go channel that will listen for an Interrupt or SIGTERM.


// Stop things when you ctl-c, and other ways, because.
term := make(chan os.Signal)
signal.Notify(term, os.Interrupt, syscall.SIGTERM)
go func() {
  select {
  case <-term:
    // Print out a message
    log.Println("==> Stopping services")

    // Cleanup GC

    // Handle other specific stuff like closing HTTP sockets
    // that may persist

comments powered by Disqus