Quotidien Shaarli

Tous les liens d'un jour sur une page.

August 18, 2019

Database connect loop in Go | There is no magic here

Today I wanted to talk about a useful pattern I started to use in my Go programs. Suppose you have some service that needs to connect to the database. This is how it probably looks like:
db, err := sqlx.Connect("postgres", DSN) if err != nil { return nil, errors.Wrap(err, "failed to connect to db") } Nice and familiar but why fail immediately? We can certainly do better!
We can just wait a little bit for a database in a loop because databases may come up later tha our service.

The power of defer in Go: on entry

How to use the defer function in Golang to execute code at the beginning and the end of any function.