Skip to content

Instantly share code, notes, and snippets.

@Nydan
Last active December 21, 2020 19:19
Show Gist options
  • Save Nydan/c39a0f873fb1d763d2d6523e26082b00 to your computer and use it in GitHub Desktop.
Save Nydan/c39a0f873fb1d763d2d6523e26082b00 to your computer and use it in GitHub Desktop.
Golang http server with gracefull exit.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
router := http.NewServeMux()
router.Handle("/", index())
listenAddr := ":8080"
srv := http.Server{
Addr: listenAddr,
Handler: router,
}
done := make(chan bool)
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT)
signal.Notify(quit, syscall.SIGTERM)
go func() {
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Keep Alive disabled when server is shutting down
srv.SetKeepAlivesEnabled(false)
if err := srv.Shutdown(ctx); err != nil {
log.Printf("failed to shutting down gracefully: %v\n", err)
}
close(done)
}()
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Printf("can't listend on address: %s, err: %+v\n", listenAddr, err)
}
<-done
fmt.Println("server stopped gracefully")
}
func index() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Put 3 second sleep here for testing, is it still serving http request after interupt signal
time.Sleep(3 * time.Second)
fmt.Fprintln(w, "hello there")
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment