登录
首页 >  Golang >  Go问答

等候 gin HTTP 服务器的启动

来源:stackoverflow

时间:2024-03-05 16:27:25 435浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《等候 gin HTTP 服务器的启动》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我们正在使用 gin 在生产中公开一些 rest api。现在,一旦 http 服务器启动,我就必须做一些事情。

我对频道不太熟悉,但下面给出的代码是我想要做的。一旦 starthtpprouter() 启动 http 服务,我想向 main() 发送信号。基于这个信号我想做一些其他的事情。

请让我知道我在下面给出的代码中做错了什么。

func startHTTPRouter(routerChannel chan bool){
    router := gin.New()
    // Many REST API routes definitions
    router.Run("")
    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("")
    routerchannel <- true  // is this gonna work ? because run() again launches a go routine for serve()
}

下面是 gin'run() api。 37186​​3771

// 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
}

到这里,我们也就讲完了《等候 gin HTTP 服务器的启动》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>