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

标签 http go concurrency

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 returns just that goroutine will exit while the rest of the program continues on. Your operations staff will not be happy to find that they cannot get the statistics out of your application when they want too because the /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/

相关文章:

http - 为什么在 Git Bash 上找不到 ncat?

go - golang 中的复制并发安全吗?

string - 具有字符串索引的多级 slice

linux - 路径查找和写入并发问题

c# - 不依赖于 HttpWebRequest 的 HTTP 库

java - 带重定向的 URL 编码(元音变音)(302 暂时移动)

java - 使用 ICAP 和 Java 发送文件并接收响应

string - 为什么这种从 rune 字符串到整数的转换不起作用?

java - 在继续之前强制方法完成

.net - Reactive Framework (Rx) 与 .NET 4 中的任务有什么关系?