douyan1972
2019-04-08 05:55
浏览 35
已采纳

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>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案

  • 我可以使用Go从一个Web应用程序设置多端口吗? \ r 1个答案

    我尝试将内部用法分开

    例如,在端口80中是外部,而在端口5487中是内部。

    我使用 github。 com / gorilla / mux 进行网址路由。

    我尝试创建两个不同的路由

      func main(){
     
    内部:= mux.NewRouter()
    外部:= mux.NewRouter()
     
    内部.HandleFunc(” / foo“,logging(foo))  
     internal.HandleFunc  (“ / bar”,日志记录(bar))
     
     external.HandleFunc(“ / monitor”,monitor())
     
     http.ListenAndServe(“:80”,内部)
     http.ListenAndServe(“  :8080“,外部)
    } 
     
       
     
     

    但是事实证明第二个服务器是无法访问的代码。

    那么如何在go中创建两个不同的端口?

    谢谢

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanlu1793 2019-04-08 05:59
    已采纳

    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
        }
    
    打赏 评论
  • dorpbn1027 2019-04-08 05:59

    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 
    
    打赏 评论