Skip to content

Commit b19d069

Browse files
committed
Add config from environment
1 parent 7cb66b7 commit b19d069

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

main.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,17 @@ func readConfig(cfile io.Reader, conf *config) {
103103
}
104104
}
105105

106+
// applyEnvOverrides updates config fields from environment variables when set.
107+
func applyEnvOverrides(conf *config) {
108+
if port := os.Getenv("PORT"); port != "" {
109+
conf.Listen = ":" + port
110+
}
111+
112+
if databaseURL := os.Getenv("DATABASE_URL"); databaseURL != "" {
113+
conf.DB = databaseURL
114+
}
115+
}
116+
106117
// setupServeMux returns a set up http.Handler.
107118
func setupServeMux(db *sql.DB) http.Handler {
108119
mux := http.NewServeMux()
@@ -187,6 +198,7 @@ func main() {
187198
var err error
188199

189200
readConfigFile("config.json", &conf)
201+
applyEnvOverrides(&conf)
190202

191203
if conf.Debug {
192204
logLevel.Set(slog.LevelDebug)

main_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,48 @@ func TestConfigFromFile(t *testing.T) {
7878
readConfigFile("config.json.sample", conf)
7979
}
8080

81+
func TestApplyEnvOverrides(t *testing.T) {
82+
t.Run("overrides when env vars are set", func(t *testing.T) {
83+
t.Setenv("PORT", "1234")
84+
t.Setenv("DATABASE_URL", "postgres://db.example/urlredir")
85+
86+
c := &config{
87+
Listen: ":9999",
88+
DB: "host=/run/postgresql dbname=urlredir",
89+
}
90+
91+
applyEnvOverrides(c)
92+
93+
if c.Listen != ":1234" {
94+
t.Fatalf("Listen = %q, want %q", c.Listen, ":1234")
95+
}
96+
97+
if c.DB != "postgres://db.example/urlredir" {
98+
t.Fatalf("DB = %q, want %q", c.DB, "postgres://db.example/urlredir")
99+
}
100+
})
101+
102+
t.Run("keeps config when env vars are unset", func(t *testing.T) {
103+
t.Setenv("PORT", "")
104+
t.Setenv("DATABASE_URL", "")
105+
106+
c := &config{
107+
Listen: ":8080",
108+
DB: "host=/run/postgresql dbname=urlredir",
109+
}
110+
111+
applyEnvOverrides(c)
112+
113+
if c.Listen != ":8080" {
114+
t.Fatalf("Listen = %q, want %q", c.Listen, ":8080")
115+
}
116+
117+
if c.DB != "host=/run/postgresql dbname=urlredir" {
118+
t.Fatalf("DB = %q, want %q", c.DB, "host=/run/postgresql dbname=urlredir")
119+
}
120+
})
121+
}
122+
81123
func TestSetupServeMux(t *testing.T) {
82124
t.Parallel()
83125

0 commit comments

Comments
 (0)