简体   繁体   中英

How to properly stop the web-server that comes with Go sdk?

What is the right way to shutdown the web-server that comes with the Go SDK?

Here's an example web service:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

That was pulled form here: https://golang.org/doc/articles/wiki/#tmp_3

However, I'd like to tear down this server and have it drain off any currently running requests. How is this done?

That's exactly what github.com/braintree/manners does. You look through the source but the gist of it is that they have a sync.WaitGroup that is incremented for every incoming connection and decremented upon completion. When you ask manners to stop the server it waits until everyone's out of the door.

If you need to strictly stick to the std lib then you can draw some inspiration from how manners does it but it's a really nice package and I would recommend just using it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM