Skip to content

Instantly share code, notes, and snippets.

@orian
Last active May 17, 2018 10:28
Show Gist options
  • Save orian/fa81bf79744227fe6766c1529b747eca to your computer and use it in GitHub Desktop.
Save orian/fa81bf79744227fe6766c1529b747eca to your computer and use it in GitHub Desktop.
An example of server shutdown from handler func.
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
)
func main() {
server := &http.Server{}
mux := http.NewServeMux()
idleConnsClosed := make(chan struct{})
shutdown := func() {
log.Printf("shutdown")
ctx, canc := context.WithTimeout(context.Background(), 2*time.Second)
defer canc()
if err := server.Shutdown(ctx); err != nil {
log.Printf("shutdown: %s", err)
} else {
log.Println("shutdown: ok")
}
time.Sleep(10 * time.Second)
log.Printf("ok, waited")
close(idleConnsClosed)
}
mux.HandleFunc("/stopAsync", func(w http.ResponseWriter, r *http.Request) {
log.Printf("stop handler")
fmt.Fprint(w, "stop handler")
go shutdown()
})
mux.HandleFunc("/stop", func(w http.ResponseWriter, r *http.Request) {
log.Printf("stop handler")
fmt.Fprint(w, "stop handler")
shutdown()
})
server.Handler = mux
server.Addr = ":8080"
if err := server.ListenAndServe(); err != nil {
log.Printf("err: %s\n", err)
if err == http.ErrServerClosed {
log.Println("wait for shutdown to end")
<-idleConnsClosed
}
}
log.Printf("done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment