HTTP.Server 关机导致运行时错误

HTTP.Server Shutdown Causes Runtime Error

我在 darwin/amd64 上有一个用 Go 1.9.2 编写的 goroutine 导致运行时错误:无效的内存地址或 nil 指针取消引用。我认为这是因为某种与例程退出顺序相关的竞争条件,但我不确定。

主应用程序正在做几件事,所以我将网络服务器作为 goroutine 启动,然后侦听来自父进程的退出信号并尝试在返回之前彻底关闭所有内容。

函数如下:

// WebServer defines the handler endpoints and launches the web server listener
func WebServer(wg *sync.WaitGroup) {

    // Make sure the exit is noted
    defer wg.Done()

    // Endpoint, handler function
    http.HandleFunc("/version", WebShowVersion)

    // Go forth and serve
    // Define the server struct
    srv := &http.Server{Addr: ":8080"}

    // Now go serve
    chnToLogger <- "Launching web server on port 8080"
    go func() {
        err := srv.ListenAndServe()
        if err != nil &&
            err.Error() != "http: Server closed" {

            // There...was an error
            chnToLoggerError <- "Error launching web server: " + err.Error()
        }
    }()

    // Listen for a shutdown
    for {
        select {
        case <-chnQuitNow:

            // Shut down the process
            chnToLogger <- "Shutting down web server process"
            if err := srv.Shutdown(nil); err != nil {

                // There was a problem shutting down gracefully
                chnToLoggerError <- "Error shutting down web server: " + err.Error()
                return
            }

            // Done
            chnToLogger <- "Web server has shut down now"
            return

        default:
            continue
        }
    }

    // Done
    return
}

恐慌状态:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x28 pc=0x11f7e61]

goroutine 10 [running]:
net/http.(*Server).Shutdown(0xc420158000, 0x0, 0x0, 0x0, 0x0)
    /usr/local/go/src/net/http/server.go:2506 +0x1b1
main.WebServer(0xc4200164a0)
    /Users/me/go/src/testproj/webhandling.go:45 +0x146
created by main.main
    /Users/me/go/src/testproj/main.go:94 +0x3d6

webhandling.go中的第45行是:

if err := srv.Shutdown(nil); err != nil {

虽然它的触发并不一致,但它似乎只有在我启动程序并使用网络客户端拉取 localhost:8080/version 几次时才会发生,这让我想知道是否 srv.Shutdown(nil) 正在尝试关闭具有引用但已经退出的连接?

1) 是否可以让服务器在从 goroutine 返回之前安全和完全地关闭 web 服务器进程?

2) 是什么导致触发不一致的运行时错误?

切勿使用 nil 上下文。使用 context.Background() or context.TODO().