【问题标题】:Wait for gin HTTP server to start等待 gin HTTP 服务器启动
【发布时间】:2020-08-15 02:56:21
【问题描述】:

我们正在使用 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)
        }
    }
}

【问题讨论】:

  • starts 是什么意思? :P 一旦它在一个套接字上监听和接受?一旦它在听?

标签: go channel goroutine httpserver go-gin


【解决方案1】:

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
}

【讨论】:

    猜你喜欢
    • 2021-04-21
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    相关资源
    最近更新 更多