等待gin HTTP服务器启动

问题描述 投票:0回答:1

我们正在使用杜松子酒在生产中公开一些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)
        }
    }
}
go channel httpserver goroutine gin
1个回答
0
投票

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
}
© www.soinside.com 2019 - 2024. All rights reserved.