11package config
22
33import (
4+ "os"
45 "path/filepath"
6+ "strconv"
57
68 "github.com/spf13/viper"
79)
@@ -62,6 +64,15 @@ func LoadConfig(configPath *string, configName ...string) (*Config, error) {
6264 // Load env variables
6365 v .AutomaticEnv ()
6466
67+ // Load env variables
68+ v .AutomaticEnv ()
69+ // Bind environment variables for nested postgres config
70+ v .BindEnv ("postgres.host" , "POSTGRES_HOST" )
71+ v .BindEnv ("postgres.user" , "POSTGRES_USER" )
72+ v .BindEnv ("postgres.db" , "POSTGRES_DB" )
73+ v .BindEnv ("postgres.port" , "POSTGRES_PORT" )
74+ v .BindEnv ("postgres.password" , "POSTGRES_PASSWORD" )
75+
6576 cfgName := "dev"
6677 if len (configName ) > 0 && configName [0 ] != "" {
6778 cfgName = configName [0 ]
@@ -81,6 +92,25 @@ func LoadConfig(configPath *string, configName ...string) (*Config, error) {
8192 }
8293 }
8394
95+ // Override with environment variables if they exist (env vars take precedence)
96+ if host := os .Getenv ("POSTGRES_HOST" ); host != "" {
97+ cfg .Postgres .Host = host
98+ }
99+ if user := os .Getenv ("POSTGRES_USER" ); user != "" {
100+ cfg .Postgres .User = user
101+ }
102+ if db := os .Getenv ("POSTGRES_DB" ); db != "" {
103+ cfg .Postgres .Database = db
104+ }
105+ if portStr := os .Getenv ("POSTGRES_PORT" ); portStr != "" {
106+ if port , err := strconv .Atoi (portStr ); err == nil {
107+ cfg .Postgres .Port = port
108+ }
109+ }
110+ if password := os .Getenv ("POSTGRES_PASSWORD" ); password != "" {
111+ cfg .Postgres .Password = password
112+ }
113+
84114 if err := ValidateConfig (cfg ); err != nil {
85115 return nil , err
86116 }
0 commit comments