恐慌:http:/(根路径)多次注册

huangapple go评论145阅读模式
英文:

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.Serverhttp.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.Handlehttp.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.

huangapple
  • 本文由 发表于 2022年10月25日 01:45:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/74184912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定