Skip to content

Commit

Permalink
Add ability to load database env from file
Browse files Browse the repository at this point in the history
  • Loading branch information
elliottminns committed Nov 14, 2024
1 parent 875adc8 commit baaf221
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
26 changes: 23 additions & 3 deletions internal/config/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"os"
"strconv"
"strings"
)

// Database holds the configuration data for setting up a connection to a
Expand All @@ -17,6 +18,25 @@ type Database struct {
SSLMode string
}

func loadPassword() (string, error) {
password, ok := os.LookupEnv("POSTGRES_PASSWORD")
if ok {
return password, nil
}

passwordFile, ok := os.LookupEnv("POSTGRES_PASSWORD_FILE")
if !ok {
return "", fmt.Errorf("no POSTGRES_PASSWORD or POSTGRES_PASSWORD_FILE env var set")
}

data, err := os.ReadFile(passwordFile)
if err != nil {
return "", fmt.Errorf("failed to read from password file: %w", err)
}

return strings.TrimSpace(string(data)), nil
}

// NewDatabase creates a database configuration based on the environment
// variables required. If any env variables are not set or are invalid then
// this method will throw an error.
Expand All @@ -26,9 +46,9 @@ func NewDatabase() (*Database, error) {
return nil, fmt.Errorf("no POSTGRES_USER env variable set")
}

password, ok := os.LookupEnv("POSTGRES_PASSWORD")
if !ok {
return nil, fmt.Errorf("no POSTGRES_PASSWORD env variable set")
password, err := loadPassword()
if err != nil {
return nil, fmt.Errorf("loading password: %w", err)
}

host, ok := os.LookupEnv("POSTGRES_HOST")
Expand Down
2 changes: 1 addition & 1 deletion internal/config/database_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func TestCreatingNewValidation(t *testing.T) {
os.Unsetenv("POSTGRES_PASSWORD")
},
ExpectedErr: fmt.Errorf(
"no POSTGRES_PASSWORD env variable set",
"loading password: no POSTGRES_PASSWORD or POSTGRES_PASSWORD_FILE env var set",
),
},
{
Expand Down

0 comments on commit baaf221

Please sign in to comment.