Golang Gorilla mux如何处理不同的端口? [重复]

This question already has an answer here:

I try to separate internal use and external use API in different port.

For example external in port 80 , and internal in port 5487.

I use github.com/gorilla/mux for url routing.

I try to create two different route

func main() {

    internal := mux.NewRouter()
    external := mux.NewRouter()

    internal.HandleFunc("/foo", logging(foo))
    internal.HandleFunc("/bar", logging(bar))

    external.HandleFunc("/monitor", monitor())

    http.ListenAndServe(":80", internal)
    http.ListenAndServe(":8080", external)
}

But it's turn out that the second server is unreachable code.

So how can I create two different port in go ?

Thanks

</div>

Use goroutine.

    package main

    import (
        "net/http"

        "github.com/gorilla/mux"
    )

    func main() {

        internal := mux.NewRouter()
        external := mux.NewRouter()

        internal.HandleFunc("/foo", logging(foo))
        internal.HandleFunc("/bar", logging(bar))

        external.HandleFunc("/monitor", monitor())

        go http.ListenAndServe(":80", internal)

        go http.ListenAndServe(":8080", external)

        select{} // block forever to prevent exiting
    }

try go routines :)

Agreed, to wait and listen you can add a channel which will continue to listen infinietly

infinite_wait := make(chan string)

go func(){
    http.ListenAndServe(":80", internal)
}()

go func(){
    http.ListenAndServe(":8080", external)
}() 

<-infinite_wait