Skip to content

Instantly share code, notes, and snippets.

@natural
Forked from bmizerany/http.go
Created December 12, 2013 17:36
Show Gist options
  • Save natural/7932035 to your computer and use it in GitHub Desktop.
Save natural/7932035 to your computer and use it in GitHub Desktop.
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