I'm attempting to use Gorm with an AWS RDS Postgres instance. I am unable to connect to the instance, but I am also not getting an error. The gorm.Open call never returns.
import (
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/jinzhu/gorm"
)
func initDB() {
db, err := gorm.Open("postgresql", "user:[email protected]:5432/db?connect_timeout=5")
if err != nil {
panic(err)
}
log.Printf("Connected")
defer db.Close()
}
I've also tried with the "host=host db=db user=user" style .Open call, which also did not return. It should be noted that I connect to this AWS instance with PGAdmin and SQL-Tabs all the time, so there is not an AWS Security rule issue. I am unsure what to do to get this to work.
Also worth noting: I saw in a different issue, it was suggested to switch gorm.Open to sql.Open to see what happens, and that also did not work.
Could you connect it via psql?
Yes, from the command line I connect just fine.
I've also tried switching back to the host=host user=user format from the docs, which is also not working.
Okay. I figured it out.
All of my DB initialization logic was in a function called from main(). If the call to initialize the DB was after http.ListenAndServe(":8080", Router), the gorm.Open call hangs. If I restructure my code like so:
func main() {
//some other stuff
initDB()
http.ListenAndServe(":8080", Router)
}
It connects successfully. @jinzhu do you have any idea why http.ListenAndServe would block gorm.Open from connecting?
_edit_ I'm told http.ListenAndServe blocks forever, which would obviously cause the initDB functionality to break.
Most helpful comment
Okay. I figured it out.
All of my DB initialization logic was in a function called from
main(). If the call to initialize the DB was afterhttp.ListenAndServe(":8080", Router), thegorm.Opencall hangs. If I restructure my code like so:It connects successfully. @jinzhu do you have any idea why
http.ListenAndServewould blockgorm.Openfrom connecting?_edit_ I'm told
http.ListenAndServeblocks forever, which would obviously cause the initDB functionality to break.