gpt4 book ai didi

http - 这个 goroutine 是如何失败的?

转载 作者:行者123 更新时间:2023-12-01 22:30:41 25 4
gpt4 key购买 nike

func serveApp() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(resp http.ResponseWriter, req *http.Request) {
fmt.Fprintln(resp, "Hello, QCon!")
})
http.ListenAndServe("0.0.0.0:8080", mux)
}

func serveDebug() {
http.ListenAndServe("127.0.0.1:8001", http.DefaultServeMux)
}

func main() {
go serveDebug()
serveApp()
}

However, serveDebug is run in a separate goroutine and if it returnsjust that goroutine will exit while the rest of the program continueson. Your operations staff will not be happy to find that they cannotget the statistics out of your application when they want too becausethe /debug handler stopped working a long time ago.


我是 Golang 和一般编码的新手。我在网上看到一篇文章,找到了这段代码。我将它复制并粘贴到我的编辑器中,然后键入 go run main.go。该程序永远运行,没有任何错误。我可以毫无问题地 curl 它。为什么代码不好?我是一个菜鸟,我正在努力更好地理解这一点,如果这可以用简单的术语来解释,那就太好了。

最佳答案

该程序创建两个 HTTP 服务器来响应接收到不同端口的流量。调试服务器在单独的 goroutine 中运行,无法检测该服务器是否发生故障。该程序可能会继续与应用服务器一起运行服务。
如果其中一个失败,更好的实现是停止两台服务器:

stop:=make(chan struct{},2)
go func() {
defer func() {
stop<-struct{}{}
}()
serveDebug()
}()

go func() {
defer func() {
stop <-struct{}{}
}{}
serveApp()
}()
<-stop
上面,程序将创建两个 goroutine 并阻塞在 <-stop直到有人写信到 channel 。如果任何一个服务器发生故障,goroutine 将写入 channel ,这将解除阻塞 <-stop ,所以程序将退出。

关于http - 这个 goroutine 是如何失败的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63732349/

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