doumeng3188 2019-03-10 14:41
浏览 125

等待gin HTTP服务器启动

We are using gin to expose some REST APIs in production. Now I have to do some stuff once the HTTP server starts.

I am not very familiar with channels, but given below code is what I'm trying to do. Once the startHTPPRouter() starts the HTTP service, I want to send a signal to main(). Based on that signal I want to do some other stuffs.

Please let me know what wrong I'm doing in the given below code.

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)
        }
    }
}
  • 写回答

1条回答 默认 最新

  • duanliao6789 2019-03-10 16:04
    关注

    gin.New().Run() is blocking API. gin server is not returned until exit.

    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()
    }
    

    Below is 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
    ", address)
        err = http.ListenAndServe(address, engine)
        return
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测