如何在一个应用程序中创建多个HTTP服务器?

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

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.

huangapple
  • 本文由 发表于 2015年7月2日 13:34:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/31176307.html
匿名

发表评论

匿名网友

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

确定