Can I setup multi port from one web app with Go?

前端 未结 2 1653
误落风尘
误落风尘 2020-12-10 17:08

As I know, I can run simple web server with Golang just use http package, like

http.ListenAndServe(PORT, nil)

where PORT is TC

相关标签:
2条回答
  • 2020-12-10 17:31

    Here is a simple working Example:

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    func hello(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "hello")
    }
    
    func world(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "world")
    }
    
    func main() {
        serverMuxA := http.NewServeMux()
        serverMuxA.HandleFunc("/hello", hello)
    
        serverMuxB := http.NewServeMux()
        serverMuxB.HandleFunc("/world", world)
    
        go func() {
            http.ListenAndServe("localhost:8081", serverMuxA)
        }()
    
        http.ListenAndServe("localhost:8082", serverMuxB)
    }
    
    0 讨论(0)
  • 2020-12-10 17:47

    No, you cannot.

    You can however start multiple listeners on different ports

    go http.ListenAndServe(PORT, handlerA)
    http.ListenAndServe(PORT, handlerB)
    
    0 讨论(0)
提交回复
热议问题