英文:
panic: http: multiple registrations for / (root path)
问题
我正在尝试在不同的端口上启动两个HTTP服务器,但无法使用相同的模式:
handlerFunc1 := http.HandlerFunc(hello1)
http.Handle("/", handlerFunc1)
server1 := &http.Server{
Addr: "localhost:8081",
Handler: handlerFunc1,
}
go server1.ListenAndServe()
http.HandleFunc("/", hello2)
go http.ListenAndServe(":8082", nil)
你知道吗,我已经尝试使用(如你所见)http.Server
和http.ListenAndServe
。
英文:
I am trying to start two http server on different ports, but unable to use the same pattern:
handlerFunc1 := http.HandlerFunc(hello1)
http.Handle("/", handlerFunc1)
server1 := &http.Server{
Addr: "localhost:8081",
Handler: handlerFunc1,
}
go server1.ListenAndServe()
http.HandleFunc("/", hello2)
go http.ListenAndServe(":8082", nil)
Do you know how, I have tried using(as you can see) http.Server
and http.ListenAndServe
答案1
得分: 3
对于其他进步的开发者来说,这段代码是有效的:
mux1 := http.NewServeMux()
mux1.HandleFunc("/", hello1)
go http.ListenAndServe(":8081", mux1)
mux2 := http.NewServeMux()
mux2.HandleFunc("/", hello2)
go http.ListenAndServe(":8082", mux2)
感谢@mkopriva的评论:
对于每个服务器使用不同的
http.ServeMux
实例。ServeMux类型实现了http.Handler接口,因此您可以将其作为http.ListenAndServe
的最后一个参数,或者作为http.Server
结构体的Handler
字段。http.Handle
和http.HandleFunc
都使用http.DefaultServeMux
,而ServeMux类型只允许每个模式一个处理程序。
英文:
Well for any other progressive developer this works:
mux1 := http.NewServeMux()
mux1.HandleFunc("/", hello1)
go http.ListenAndServe(":8081", mux1)
mux2 := http.NewServeMux()
mux2.HandleFunc("/", hello2)
go http.ListenAndServe(":8082", mux2)
Thanks to @mkopriva's comment:
> Use a different http.ServeMux
instance for each server. The ServeMux type implements the http.Handler interface, so you can use that as the last argument to http.ListenAndServe
or as the Handler
field of the http.Server
struct. The http.Handle
and http.HandleFunc
both use the http.DefaultServeMux
and the ServeMux type allows only one handler per pattern.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论