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