Last active
February 14, 2018 20:11
-
-
Save ash2k/2ce1579cc6502e20ce2b4a78e447d87f to your computer and use it in GitHub Desktop.
Clean shutdown of Go http server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func startStopServer(ctx context.Context, srv *http.Server, shutdownTimeout time.Duration) error { | |
var wg sync.WaitGroup | |
defer wg.Wait() // wait for goroutine to shutdown active connections | |
ctx, cancel := context.WithCancel(ctx) | |
defer cancel() | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
<-ctx.Done() | |
c, cancel := context.WithTimeout(context.Background(), shutdownTimeout) | |
defer cancel() | |
if srv.Shutdown(c) != nil { | |
srv.Close() | |
} | |
}() | |
err := srv.ListenAndServe() | |
if err != http.ErrServerClosed { | |
// Failed to start or dirty shutdown | |
return err | |
} | |
// Clean shutdown | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment