Go 如何在一个应用程序中创建多个http服务器?
我想在一个golang应用程序中创建两个http服务器。例如:Go 如何在一个应用程序中创建多个http服务器?,go,Go,我想在一个golang应用程序中创建两个http服务器。例如: package main import ( "io" "net/http" ) func helloOne(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Hello world one!") } func helloTwo(w http.ResponseWriter, r *http.Request) {
package main
import (
"io"
"net/http"
)
func helloOne(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello world one!")
}
func helloTwo(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello world two!")
}
func main() {
// how to create two http server instatce?
http.HandleFunc("/", helloOne)
http.HandleFunc("/", helloTwo)
go http.ListenAndServe(":8001", nil)
http.ListenAndServe(":8002", nil)
}
如何创建两个http服务器实例并为它们添加处理程序?您需要创建单独的
http.ServeMux
实例。调用http.ListenAndServe(port,nil)使用DefaultServeMux
(即共享)。有关此操作的文档如下所示:
例如:
func main() {
r1 := http.NewServeMux()
r1.HandleFunc("/", helloOne)
r2 := http.NewServeMux()
r2.HandleFunc("/", helloTwo)
go func() { log.Fatal(http.ListenAndServe(":8001", r1))}()
go func() { log.Fatal(http.ListenAndServe(":8002", r2))}()
select {}
}
如果其中一个侦听器不工作,则使用
log.Fatal
包装服务器将导致程序退出。如果希望程序在其中一台服务器无法启动或崩溃时保持运行,则可以err:=http.ListenAndServe(port,mux)
并以另一种方式处理错误。second instance go log.Fatal(http.ListenAndServe(:8002,r2))不会启动。当我转到localhost:8002时,该网页不可用。您只运行日志。在其自己的goroutine中进行致命调用。对ListendService的调用仍然发生在主Goroutine上,并将被阻止。已修复。在我的手机上敲定。现在应该可以工作了。空的select{}
是一种无限期阻塞的快速方法。