如何停止 http.ListenAndServe()
技术问答
258 人阅读
|
0 人回复
|
2023-09-12
|
我在用 Gorilla Web Toolkit 中的 Mux 库和捆绑 Go http 服务器。# l. s. c( v' U( f5 d- B9 Z
问题是,在我的应用程序中,HTTP 服务器只是一个组件,我需要自己决定停止和启动。 {/ c `- A% i& r8 C5 o9 b0 ~
当我调用http.ListenAndServe(fmt.Sprintf(":%d",service.Port()),service.router)当时,我似乎无法阻止服务器运行。5 R+ B; u$ c" x9 g% c
我知道过去一直是个问题,但现在还是这样吗?有新的解决方案吗?" a, q1 O9 }; Q8 i. N8 }7 N d
3 [2 J# V6 r+ n 解决方案: " i _ O" J# G( p. s& y6 r0 i6 u
关闭(在 Go 1.8 介绍),一个更具体的例子:
8 ]2 H. z1 X) {0 Werr) 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] |
|
|
|
|
|