go - 等待 gin HTTP 服务器启动
问题描述
我们正在使用 gin 在生产环境中公开一些 REST API。现在,一旦 HTTP 服务器启动,我必须做一些事情。
我对频道不是很熟悉,但下面给出的代码是我想要做的。一旦startHTPPRouter()
启动 HTTP 服务,我想向main()
. 基于这个信号,我想做一些其他的事情。
请让我知道我在下面给出的代码中做错了什么。
func startHTTPRouter(routerChannel chan bool){
router := gin.New()
// Many REST API routes definitions
router.Run("<port>")
routerChannel <- true // Is this gonna work ? Because Run() again launches a go routine for Serve()
}
func main() {
routerChannel := make(chan bool)
defer close(routerChannel)
go startHTTPRouter(routerChannel )
for {
select {
case <-routerChannel:
doStuff() // Only when the REST APIs are available.
time.Sleep(time.Second * 5)
default:
log.Info("Waiting for router channel...")
time.Sleep(time.Second * 5)
}
}
}
解决方案
gin.New().Run() 正在阻塞 API。gin 服务器直到退出才返回。
func startHTTPRouter(routerChannel chan bool) {
router := gin.New()
router.Run("<port>")
routerChannel <- true // Is this gonna work ? Because Run() again launches a go routine for Serve()
}
下面是 gin'Run() API。https://github.com/gin-gonic/gin/blob/master/gin.go
// Run attaches the router to a http.Server and starts listening and serving HTTP requests.
// It is a shortcut for http.ListenAndServe(addr, router)
// Note: this method will block the calling goroutine indefinitely unless an error happens.
func (engine *Engine) Run(addr ...string) (err error) {
defer func() { debugPrintError(err) }()
address := resolveAddress(addr)
debugPrint("Listening and serving HTTP on %s\n", address)
err = http.ListenAndServe(address, engine)
return
}
推荐阅读
- javascript - 使用 Angular 导航到文档中的特定位置
- api - 没有足够的权限在 LinkedIn Learning API 中访问 /me GET
- visual-studio-code - 如何更改主题元素颜色?
- java - 如何在 Java 中向我的 MDI GUI 添加弹出消息
- python - 如何将数据框重塑为 [colName, rowName, value] 格式?
- sql-server - 没有聚合或连接的最简单的“PIVOT”
- json - 从 JSON 文件读入字典
- django - 直接分配到多对多的前端
- c# - 在 C# 中为 Windows 服务设置计时器
- xml - 在 xml 文件中进行模板化