如何停止 http.ListenAndServe()
技术问答
211 人阅读
|
0 人回复
|
2023-09-12
|
我在用 Gorilla Web Toolkit 中的 Mux 库和捆绑 Go http 服务器。
' F, }( }6 c+ E2 h8 X" s" Q问题是,在我的应用程序中,HTTP 服务器只是一个组件,我需要自己决定停止和启动。$ h% M" y) | z& Z
当我调用http.ListenAndServe(fmt.Sprintf(":%d",service.Port()),service.router)当时,我似乎无法阻止服务器运行。 B) A } R s6 ]! |9 [
我知道过去一直是个问题,但现在还是这样吗?有新的解决方案吗?
, J! W5 j4 t5 L2 m
8 i: W/ G* U" j( g! g+ l 解决方案:
# Z7 R* |8 E3 F0 o) Y D% h 关闭(在 Go 1.8 介绍),一个更具体的例子:
! I7 l8 ^4 l7 m2 yerr) 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")}[/code] 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")}[/code] |
|
|
|
|
|