当前位置: > > > > Golang Gorilla mux 如何处理不同的端口?
Golang Gorilla mux 如何处理不同的端口?
来源:stackoverflow
2024-04-29 13:09:35
0浏览
收藏
对于一个Golang开发者来说,牢固扎实的基础是十分重要的,米云就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《Golang Gorilla mux 如何处理不同的端口?》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!
问题内容
我尝试在不同的端口中分离内部使用和外部使用的api。
例如端口 80 中的外部和端口 5487 中的内部。
我使用 github.com/gorilla/mux 进行 url 路由。
我尝试创建两条不同的路线
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)
}
但事实证明第二个服务器是无法访问的代码。
那么如何在 go 中创建两个不同的端口?
谢谢
解决方案
使用 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
}
尝试 go 例程 🙂
infinite_wait := make(chan string)
go func(){
http.ListenAndServe(":80", internal)
}()
go func(){
http.ListenAndServe(":8080", external)
}()
<-infinite_wait
理论要掌握,实操不能落!以上关于《Golang Gorilla mux 如何处理不同的端口?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注米云公众号吧!
