gpt4 book ai didi

go - 等待 gin HTTP 服务器启动

转载 作者:数据小太阳 更新时间:2023-10-29 03:20:17 25 4
gpt4 key购买 nike

我们正在使用 gin 来公开生产中的一些 REST API。现在我必须在 HTTP 服务器启动后做一些事情。

我对 channel 不是很熟悉,但下面给出的代码是我想要做的。 startHTTPRouter() 启动 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
}

关于go - 等待 gin HTTP 服务器启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55088810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com