From ac7e418f2f6bb38d7b5ea09c4d955f7b7b8bdd62 Mon Sep 17 00:00:00 2001 From: Riccardo Montagnin Date: Wed, 30 Nov 2022 10:46:00 -0500 Subject: [PATCH] feat: allow setting Database URI from environmental variable --- database/postgresql/postgresql.go | 4 +++- types/env/const.go | 5 +++++ types/utils/env.go | 13 +++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 types/env/const.go create mode 100644 types/utils/env.go diff --git a/database/postgresql/postgresql.go b/database/postgresql/postgresql.go index dc9e1988..54e9f002 100644 --- a/database/postgresql/postgresql.go +++ b/database/postgresql/postgresql.go @@ -16,13 +16,15 @@ import ( "github.com/forbole/juno/v4/database" "github.com/forbole/juno/v4/types" "github.com/forbole/juno/v4/types/config" + "github.com/forbole/juno/v4/types/env" + "github.com/forbole/juno/v4/types/utils" ) // Builder creates a database connection with the given database connection info // from config. It returns a database connection handle or an error if the // connection fails. func Builder(ctx *database.Context) (database.Database, error) { - postgresDb, err := sqlx.Open("postgres", ctx.Cfg.URL) + postgresDb, err := sqlx.Open("postgres", utils.GetEnvOr(env.DatabaseURI, ctx.Cfg.URL)) if err != nil { return nil, err } diff --git a/types/env/const.go b/types/env/const.go new file mode 100644 index 00000000..09c3f9ec --- /dev/null +++ b/types/env/const.go @@ -0,0 +1,5 @@ +package env + +const ( + DatabaseURI = "JUNO_DATABASE_URL" +) diff --git a/types/utils/env.go b/types/utils/env.go new file mode 100644 index 00000000..e4d7c53c --- /dev/null +++ b/types/utils/env.go @@ -0,0 +1,13 @@ +package utils + +import ( + "os" +) + +// GetEnvOr returns the value of the ENV variable having the given key, or the provided orValue +func GetEnvOr(envKey string, orValue string) string { + if envValue := os.Getenv(envKey); envValue != "" { + return envValue + } + return orValue +}