Skip to content

Instantly share code, notes, and snippets.

@s8508235
Last active January 18, 2024 21:01
Show Gist options
  • Save s8508235/bc248d046d5001d5cae46cc39066cdf5 to your computer and use it in GitHub Desktop.
Save s8508235/bc248d046d5001d5cae46cc39066cdf5 to your computer and use it in GitHub Desktop.
gracefully shutdown go web server with error group
package main
import (
"context"
"fmt"
"net/http"
"os/signal"
"syscall"
"time"
// "github.com/gorilla/mux"
"github.com/gin-gonic/gin"
"golang.org/x/sync/errgroup"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
// you can also use other HTTP router
router := gin.Default()
router.GET("/", func(c *gin.Context) {
time.Sleep(100 * time.Millisecond)
c.String(http.StatusOK, "Welcome Gin Server")
})
// router := mux.NewRouter()
// router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// time.Sleep(100 * time.Millisecond)
// w.WriteHeader(http.StatusOK)
// fmt.Fprintf(w, "Welcome Mux server")
// })
srv := &http.Server{
Addr: ":8080",
Handler: router,
}
errWg, errCtx := errgroup.WithContext(ctx)
errWg.Go(func() error {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
return err
}
return nil
})
errWg.Go(func() error {
<-errCtx.Done()
// https://gist.github.com/s8508235/bc248d046d5001d5cae46cc39066cdf5?permalink_comment_id=4360249#gistcomment-4360249
return srv.Shutdown(context.Background())
})
err := errWg.Wait()
if err == context.Canceled || err == nil {
fmt.Println("gracefully quit server")
} else if err != nil {
fmt.Println(err)
}
}
@fasmat
Copy link

fasmat commented Nov 6, 2022

Are you sure you can pass errCtx to srv.Shutdown here https://gist.github.com/s8508235/bc248d046d5001d5cae46cc39066cdf5#file-gracefully_shutdown_server-go-L48-L52 ?

I think this should just be:

	errWg.Go(func() error {
		<-errCtx.Done()
		// no need to call stop, either the `ctx` is already cancelled or will be cancelled by the `defer` statement above
		return srv.Shutdown(context.Background()) // do not pass errCtx here, otherwise srv drops all connections instead of gracefully closing them, you can pass a new `context.WithTimeout` to limit how long the shutdown should take
	})

This way the err returned from errWg.Wait() should also be nil if the shutdown went well. If it is context.Canceled then srv.Shutdown couldn't gracefully shut down and dropped connections.

@s8508235
Copy link
Author

s8508235 commented Dec 2, 2022

Are you sure you can pass errCtx to srv.Shutdown here https://gist.github.com/s8508235/bc248d046d5001d5cae46cc39066cdf5#file-gracefully_shutdown_server-go-L48-L52 ?

I think this should just be:

	errWg.Go(func() error {
		<-errCtx.Done()
		// no need to call stop, either the `ctx` is already cancelled or will be cancelled by the `defer` statement above
		return srv.Shutdown(context.Background()) // do not pass errCtx here, otherwise srv drops all connections instead of gracefully closing them, you can pass a new `context.WithTimeout` to limit how long the shutdown should take
	})

This way the err returned from errWg.Wait() should also be nil if the shutdown went well. If it is context.Canceled then srv.Shutdown couldn't gracefully shut down and dropped connections.

Thanks for your correction!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment