I'm building a REST server in Go and using mongoDB as my database (but this question is actually related to any other external resource).
I want my server to start and respond, even if the database is not up yet (not when the database is down after the server started - this is a different issue, much easier one).
So my dao package includes a connection go-routine that receives a boolean channel, and write 'true' to the channel when it successfully connected to the database. If the connection failed, the go-routine will keep trying every X seconds.
When I use this package with another software I wrote, that is a just a command-line program, I'm using select with timeout:
dbConnected := make(chan bool)
storage.Connect(dbConnected)
timeout := time.After(time.Minute)
select {
case <-dbConnected:
createReport()
case <-timeout:
log.Fatalln("Can't connect to the database")
}
I want to use the same packge in a server, but I don't want to fail the whole server. Instead, I want to start the server with handler that returns 503 SERVER BUSY
, until the server is connected to the database, and then start serve requests normally. Is there a simple way to implement this logic in go standard library? Using solutions like gorilla is an option, but the server is simple with very few APIs, and gorilla is a bit overkill.
== edited: ==
I know I can use a middleware but I don't know how to do that without sharing data between the main method and the handlers. That why I'm using the channel in the first place.