diff --git a/config.dev.toml b/config.dev.toml index cfc5ba5a..5ed2f2e3 100755 --- a/config.dev.toml +++ b/config.dev.toml @@ -71,8 +71,8 @@ StorageType = "memory" #TLSKeyFile = "server.key" # Port sets the port the proxy listens on -# Env override: ATHENS_PORT -# Note that PORT needs to be prefixed by : +# Env override: ATHENS_PORT or PORT +# The PORT must be a number or a number prefixed by ":" Port = ":3000" # The endpoint for a package registry in case of a proxy cache miss diff --git a/pkg/config/config.go b/pkg/config/config.go index c782cc0f..672816df 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -160,12 +160,27 @@ func envOverride(config *Config) error { if err != nil { return err } + portEnv := os.Getenv("PORT") + // ATHENS_PORT takes precedence over PORT + if portEnv != "" && os.Getenv("ATHENS_PORT") == "" { + config.Port = portEnv + } if config.Port == "" { config.Port = defaultPort } return nil } +func ensurePortFormat(s string) string { + if len(s) == 0 { + return "" + } + if s[0] != ':' { + return ":" + s + } + return s +} + func validateConfig(config Config) error { validate := validator.New() err := validate.StructExcept(config, "Storage") diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index dea1bbe2..7393d40e 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -114,6 +114,34 @@ func TestEnvOverridesPreservingPort(t *testing.T) { } } +func TestEnvOverridesPORT(t *testing.T) { + conf := &Config{Port: ""} + oldVal := os.Getenv("PORT") + defer os.Setenv("PORT", oldVal) + os.Setenv("PORT", "5000") + err := envOverride(conf) + if err != nil { + t.Fatalf("Env override failed: %v", err) + } + if conf.Port != "5000" { + t.Fatalf("expected PORT env to be 5000 but got %v", conf.Port) + } +} + +func TestEnsurePortFormat(t *testing.T) { + port := "3000" + expected := ":3000" + given := ensurePortFormat(port) + if given != expected { + t.Fatalf("expected ensurePortFormat to add a colon to %v but got %v", port, given) + } + port = ":3000" + given = ensurePortFormat(port) + if given != expected { + t.Fatalf("expected ensurePortFormat to not add a colon when it's present but got %v", given) + } +} + func TestStorageEnvOverrides(t *testing.T) { expStorage := &StorageConfig{ Disk: &DiskConfig{