This is a creation in Article, where the information may have evolved or changed.
I'm glad that go 1.8 has been released, it's a day to celebrate.
How to gracefully turn off the topic that the HTTP service has been mentioned and discussed in Go web development, today's release of Go 1.8 has finally brought us this feature.
This is described in the documentation:
func (srv *Server) Shutdown(ctx context.Context) error
Shutdown
A non-disruptive shutdown is active on the connection, and then a smooth stop service. The processing flow is as follows:
First off, all listening.
Then close all the idle connections
Then wait indefinitely for the connection to finish to idle and close
If a timeout is provided with a timeout Context
, a Context
time-out error will be returned before the service is closed
It is important to note that you Shutdown
do not attempt to close or wait for a hijacked
connection, such as WebSockets
. If necessary, the caller needs to handle waits and shutdowns, such as long connection types, separately.
In fact, you just Shutdown
have to call the method.
Simple example:
// main.gopackage mainimport ( "fmt" "log" "net/http" "os" "os/signal" "syscall" "time")func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World, %v\n", time.Now()) }) s := &http.Server{ Addr: ":8080", Handler: http.DefaultServeMux, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } go func() { log.Println(s.ListenAndServe()) log.Println("server shutdown") }() // Handle SIGINT and SIGTERM. ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) log.Println(<-ch) // Stop the service gracefully. log.Println(s.Shutdown(nil)) // Wait gorotine print shutdown message time.Sleep(time.Second * 5) log.Println("done.")}
To run the program:
go run main.go
Then ctrl + c
terminate the program and print out the following information:
2017/02/17 11:36:28 interrupt2017/02/17 11:36:28 <nil>2017/02/17 11:36:28 http: Server closed2017/02/17 11:36:28 server shutdown
As you can see, the service is shut down correctly.
Before there was no Shutdown
method, the ctrl + c
abruptly was terminated, and then there was no more.
For more information, see the official documentation:
Https://golang.org/pkg/net/ht ...