我正在尝试在我的 go lang 应用程序中创建 2 个 HTTP 服务器,这就是我尝试实现它的方式:
package main
import (
"net/http"
)
func main() {
server := http.Server{
Addr: ":9000",
//Handler: http.HandleFunc("/", hello)
}
server.ListenAndServe()
server2 := http.Server{
Addr: ":8000",
//Handler: http.HandleFunc("/", hello)
}
server2.ListenAndServe()
}
我遇到的问题是,当我转到浏览器向 http://localhost:9000/
发出请求时,它运行了,但是当我向 http 发出请求时://localhost:8000/
我收到“无法访问网站”。为什么我不能在 Go 中创建 HTTP 服务器的实例?
最佳答案
就像Tim Cooper是说 ListenAndServe
正在阻塞,因此第一个服务器启动,但随后不会继续进行第二个调用。解决这个问题的一个简单方法是在它自己的 goroutine 中启动 server
func main() {
server := http.Server{
Addr: ":9000",
//Handler: http.HandleFunc("/", hello)
}
go server.ListenAndServe()
server2 := http.Server{
Addr: ":8000",
//Handler: http.HandleFunc("/", hello)
}
server2.ListenAndServe()
}
关于go - 在 Go 中创建多个 http 服务器实例不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57631954/