首页 > 解决方案 > 等待 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)
        }
    }
}

标签: gochannelgoroutinehttpservergo-gin

解决方案


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
}

推荐阅读