stopper := util.NewStopper() go func() { for { select { case <-stopper.ShouldStop(): return default: // do some work } } }() // ... // stop the goroutine and cleanup resources stopper.Stop()
stopper := util.NewStopper() http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { select { case <-stopper.ShouldStop(): // serve a 503 error during shutdown w.WriteHeader(http.StatusServiceUnavailable) default: // serve the request as normal fmt.Fprintln(w, "Hello, World!") } }) server := http.Server{ Addr: ":8080", Handler: nil, // use default HTTP multiplexer } go func() { err := server.ListenAndServe() if err != nil && err != http.ErrServerClosed { log.Fatalf("server error: %v", err) } }() // ... // shut down the server gracefully err := server.Shutdown(context.Background()) if err != nil { log.Fatalf("server shutdown error: %v", err) } stopper.Stop()In this example, the `ShouldStop` method is used to serve a 503 error during shutdown, rather than accepting new connections. The `Shutdown` method is used to gracefully shut down the server, and the `Stop` method is used to stop the goroutine and cleanup resources. Overall, the `Stopper` package from `github.com/cockroachdb/cockroach/util` is a useful library for graceful shutdown of Go programs, especially for long-running tasks or servers.