英文:
How to create many http servers into one app?
问题
我想在一个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) {
io.WriteString(w, "Hello world two!")
}
func main() {
// 如何创建两个HTTP服务器实例并为它们添加处理程序?
http.HandleFunc("/", helloOne)
http.HandleFunc("/", helloTwo)
go http.ListenAndServe(":8001", nil)
http.ListenAndServe(":8002", nil)
}
要创建两个HTTP服务器实例并为它们添加处理程序,你可以使用http.ListenAndServe
函数来监听不同的端口。在上面的示例中,我们使用go
关键字在后台启动一个服务器实例,然后使用http.ListenAndServe
在当前线程中启动另一个服务器实例。这样,你就可以在两个不同的端口上访问这两个服务器。
英文:
I want create two http servers into one golang app. Example:
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)
}
How to create two http server instance and add handlers for them?
答案1
得分: 15
你需要创建单独的http.ServeMux
实例。调用http.ListenAndServe(port, nil)
会使用DefaultServeMux
(即共享的)。关于此的文档在这里:http://golang.org/pkg/net/http/#NewServeMux
示例:
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)
并以其他方式处理错误。
英文:
You'll need to create separate http.ServeMux
instances. Calling http.ListenAndServe(port, nil)
uses the DefaultServeMux
(i.e. shared). The docs for this are here: http://golang.org/pkg/net/http/#NewServeMux
Example:
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 {}
}
Wrapping the servers with log.Fatal
will cause the program to quit if one of the listeners doesn't function. If you wanted the program to stay up if one of the servers fails to start or crashes, you could err := http.ListenAndServe(port, mux)
and handle the error another way.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论