This question already has an answer here:
When building a custom server application it is better to be having a shutting down mechanism for ensuring all our running processes are stopped before the server down and it will also help in better in-memory management.
How can we build such a mechanism with Golang and its powers?
There is already a ,shutdown
function available in Golang my ibtension is to make developers think out of the box and create multiple
methods for do the same. It will help to make our golang community more better and stronger. Below I share one of my answer and hope you guys make more suggestions and answers..
As of Go 1.8, net/http.Server has a function Shutdown
which can be used to stop a server. Documentation and an example are available in the Go documentation.
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
)
func main() {
var srv http.Server
idleConnsClosed := make(chan struct{})
go func() {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
<-sigint
// We received an interrupt signal, shut down.
if err := srv.Shutdown(context.Background()); err != nil {
// Error from closing listeners, or context timeout:
log.Printf("HTTP server Shutdown: %v", err)
}
close(idleConnsClosed)
}()
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
// Error starting or closing listener:
log.Printf("HTTP server ListenAndServe: %v", err)
}
<-idleConnsClosed
}
document is https://golang.org/pkg/net/http/#Server.Shutdown.