Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created July 12, 2012 02:41
Show Gist options
  • Save jordanorelli/3095334 to your computer and use it in GitHub Desktop.
Save jordanorelli/3095334 to your computer and use it in GitHub Desktop.
gracefully handle SIGINT on a Go webserver
package main
import (
"net"
"log"
"net/http"
"io"
"time"
"os"
"os/signal"
"syscall"
"fmt"
"sync"
)
type Handler struct {
net.Listener
sync.WaitGroup
}
func (h *Handler)ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.Add(1)
defer h.Done()
time.Sleep(time.Duration(5e9))
io.WriteString(w, "hey")
}
func main() {
handler := new(Handler)
var err error
handler.Listener, err = net.Listen("tcp", ":8000")
if err != nil {
log.Fatal(err)
}
c := make(chan os.Signal)
signal.Notify(c, syscall.SIGINT)
go func(quit chan os.Signal) {
<-quit
fmt.Println("Received SIGINT")
handler.Wait()
handler.Close()
os.Exit(0)
}(c)
if err := http.Serve(handler, handler); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment