Skip to content

Instantly share code, notes, and snippets.

@LucasRoesler
Last active May 10, 2019 07:30
Show Gist options
  • Save LucasRoesler/4687feecee5cb5ed4eb66d7c930ab7e8 to your computer and use it in GitHub Desktop.
Save LucasRoesler/4687feecee5cb5ed4eb66d7c930ab7e8 to your computer and use it in GitHub Desktop.
Two possible call signatures for gracefully starting and ending the health server
// ListenAndServeMonitoring starts up an HTTP server serving /metrics and /health.
//
// When the context is cancelled, the server will be gracefully shutdown.
func ListenAndServeMonitoring(ctx context.Context, addr string, healthHandler http.Handler) error {
srv := monitoringServer(addr, healthHandler)
go func() {
<-ctx.Done()
shutdownContext, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
srv.Shutdown(shutdownContext)
}()
err := srv.ListenAndServe()
if err != nil {
log.Println(err)
}
return err
}
// StartMonitoring starts the health and metrics endpoints at the specified address.
//
// The server is started in the background and you then receive a channel of any errors and the
// shutdown method. This allows you to watch for errors and then decide when to stop the server.
func StartMonitoring(ctx context.Context, addr string, healthHandler http.Handler) (errs chan error, shutdown func(ctx context.Context) error) {
srv := monitoringServer(addr, healthHandler)
errs = make(chan error, 1)
go func() {
err := srv.ListenAndServe()
if err != nil {
errs <- err
}
close(errs)
}()
return errs, srv.Shutdown
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment