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

前端 未结 2 1658
误落风尘
误落风尘 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)
    }
    

提交回复
热议问题