dongque8332 2015-07-02 05:34
浏览 63
已采纳

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

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条回答 默认 最新

  • dongyun65343 2015-07-02 05:43
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效