gpt4 book ai didi

go - 如何停止 http.ListenAndServe()

转载 作者:IT老高 更新时间:2023-10-28 12:58:11 27 4
gpt4 key购买 nike

我正在使用来自 Gorilla Web Toolkit 的 Mux 库以及捆绑的 Go http 服务器。

问题是,在我的应用程序中,HTTP 服务器只是一个组件,需要我自行决定停止和启动。

当我调用 http.ListenAndServe(fmt.Sprintf(":%d", service.Port()), service.router) 时,它会阻塞,我似乎无法阻止服务器运行.

我知道这在过去一直是个问题,现在仍然如此吗?有没有新的解决方案?

最佳答案

关于优雅关闭(在 Go 1.8 中引入),一个更具体的例子:

package main

import (
"context"
"io"
"log"
"net/http"
"sync"
"time"
)

func startHttpServer(wg *sync.WaitGroup) *http.Server {
srv := &http.Server{Addr: ":8080"}

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "hello world\n")
})

go func() {
defer wg.Done() // let main know we are done cleaning up

// always returns error. ErrServerClosed on graceful close
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
// unexpected error. port in use?
log.Fatalf("ListenAndServe(): %v", err)
}
}()

// returning reference so caller can call Shutdown()
return srv
}

func main() {
log.Printf("main: starting HTTP server")

httpServerExitDone := &sync.WaitGroup{}

httpServerExitDone.Add(1)
srv := startHttpServer(httpServerExitDone)

log.Printf("main: serving for 10 seconds")

time.Sleep(10 * time.Second)

log.Printf("main: stopping HTTP server")

// now close the server gracefully ("shutdown")
// timeout could be given with a proper context
// (in real world you shouldn't use TODO()).
if err := srv.Shutdown(context.TODO()); err != nil {
panic(err) // failure/timeout shutting down the server gracefully
}

// wait for goroutine started in startHttpServer() to stop
httpServerExitDone.Wait()

log.Printf("main: done. exiting")
}

关于go - 如何停止 http.ListenAndServe(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39320025/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com