我们正在使用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)
}
}
}
答案 0 :(得分:0)
gin.New()。Run()阻止了API。杜松子酒服务器直到退出都不会返回。
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
}