Connecting Go app to App Engine Cloud SQL (Postgres)

Just putting this here because I’ve been looking for hours without finding the right connection string. So basically if you’re using sqlx for example you’re going to need a connection string for your go app.

The easiest thing is to place this as an environment var in your app.yaml. In order to do this your app.yaml might look like this:

runtime: go111
env_variables:
  DATABASE_URL: "postgres://username:password@/databasename?host=/cloudsql/example:us-central1:example123"

After /cloudsql/ you’ll have your instancename (hint just run gcloud sql instances describe yourproject) from the command line and you’ll find a “connectionName” key, that’s the one

the trick was to 1) not use a host but /databasename directly and 2) using host= and not socket or unix_socket

N.B. This will work with a STANDARD GAE + Cloud Postgres

In the Go code it’s as simple as:

  
url := os.Getenv("DATABASE_URL")
DB, err = sqlx.Open("postgres", url)