Go启动多个端口服务

910 次浏览次阅读
没有评论

go 的 net/http 包可以通过 ListenAndServe 创建 http 服务。如果需要启动多个端口服务可以使用 http.NewServeMux 监听多个端口. NewServeMux 返回的是 ServeMux 指针(ServeMux 路由管理器)。通过创建 goroutine 启动多端口服务


func main() {aMux := http.NewServeMux()
    aMux.HandleFunc("/a/", AHandler)
    server := &http.Server{
        Addr:    ":9091",
        Handler: aMux,
    }
    go server.ListenAndServe()

    bMux := http.NewServeMux()
    bMux.HandleFunc("/b/", BHandler)
    server = &http.Server{
        Addr:    ":9093",
        Handler: bMux,
    }
    go server.ListenAndServe()

    log.Fatal(server.ListenAndServe())

}
正文完
 0
评论(没有评论)