diff --git a/backend/env.go b/backend/env.go new file mode 100644 index 0000000..2effd2e --- /dev/null +++ b/backend/env.go @@ -0,0 +1,21 @@ +package main + +import ( + "os" + "strconv" + "strings" +) + +// envInt64 returns the parsed environment value or fallback when the variable +// is unset, empty, or not a valid base-10 int64. +func envInt64(name string, fallback int64) int64 { + value := strings.TrimSpace(os.Getenv(name)) + if value == "" { + return fallback + } + parsed, err := strconv.ParseInt(value, 10, 64) + if err != nil { + return fallback + } + return parsed +} diff --git a/backend/env_test.go b/backend/env_test.go new file mode 100644 index 0000000..fb554ba --- /dev/null +++ b/backend/env_test.go @@ -0,0 +1,33 @@ +package main + +import "testing" + +func TestEnvInt64(t *testing.T) { + tests := []struct { + name string + value string + fallback int64 + want int64 + }{ + {name: "valid", value: "1234567890123", fallback: 7, want: 1234567890123}, + {name: "trimmed", value: " 42 ", fallback: 7, want: 42}, + {name: "empty", value: "", fallback: 7, want: 7}, + {name: "invalid", value: "not-a-number", fallback: 7, want: 7}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Setenv("COLLABTABLE_TEST_ENV_INT64", test.value) + if got := envInt64("COLLABTABLE_TEST_ENV_INT64", test.fallback); got != test.want { + t.Fatalf("envInt64() = %d, want %d", got, test.want) + } + }) + } +} + +func TestEnvInt64UsesFallbackWhenUnset(t *testing.T) { + t.Setenv("COLLABTABLE_TEST_ENV_INT64", "") + if got := envInt64("COLLABTABLE_TEST_ENV_INT64_UNSET", 99); got != 99 { + t.Fatalf("envInt64() = %d, want 99", got) + } +}