Skip to content

Instantly share code, notes, and snippets.

@bmizerany
Last active December 22, 2015 16:39
Show Gist options
  • Save bmizerany/6501084 to your computer and use it in GitHub Desktop.
Save bmizerany/6501084 to your computer and use it in GitHub Desktop.
Graceful shutdown example in regards to https://groups.google.com/forum/#!topic/golang-nuts/vLHWa5sHnCE
package main
func main() {
// ... setup ...
l, err := net.Listen("tcp", *laddr)
if err != nil {
log.Fatal(err)
}
sig := make(chan os.Signal)
signal.Notify(sig, os.Signal(syscall.SIGTERM))
graceful := make(chan bool, 1)
go func() {
tick := time.Tick(time.Minute)
for {
select {
case <-sig:
measure.Count("SIGTERM")
graceful <- true
l.Close()
return
case <-tick:
things.Flush()
}
}
}()
var wg sync.WaitGroup
m := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
wg.Add(1)
defer wg.Done()
http.DefaultServeMux.ServeHTTP(w, r)
})
defer things.Flush()
err := http.Serve(l, m)
wg.Wait() // maybe time this out, in case a request is hanging?
if err != nil {
select {
case <-graceful:
// There is a race here still, I think. The server
// could have errored between sending on graceful and
// l.Close() - I'm not sure I care.
default:
log.Fatal(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment