diff --git a/pkg/config/config.go b/pkg/config/config.go new file mode 100644 index 0000000..1bb97ee --- /dev/null +++ b/pkg/config/config.go @@ -0,0 +1,54 @@ +package config + +import ( + "math/rand" + + "github.com/joho/godotenv" + "github.com/kelseyhightower/envconfig" + log "github.com/sirupsen/logrus" + "github.com/usefathom/fathom/pkg/datastore/sqlstore" +) + +type Config struct { + Database *sqlstore.Config + + Secret string +} + +func Parse(file string) *Config { + var cfg Config + var err error + + if file != "" { + err = godotenv.Load(file) + if err != nil && file != ".env" { + log.Fatalf("error parsing config file: %s", err) + } + } + + err = envconfig.Process("Fathom", &cfg) + if err != nil { + log.Fatalf("error parsing config from environment values: %s", err) + } + + // alias sqlite to sqlite3 + if cfg.Database.Driver == "sqlite" { + cfg.Database.Driver = "sqlite3" + } + + // if secret key is empty, use a randomly generated one + if cfg.Secret == "" { + cfg.Secret = randomString(40) + } + + return &cfg +} + +func randomString(len int) string { + bytes := make([]byte, len) + for i := 0; i < len; i++ { + bytes[i] = byte(65 + rand.Intn(25)) //A=65 and Z = 65+25 + } + + return string(bytes) +} diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go new file mode 100644 index 0000000..510f306 --- /dev/null +++ b/pkg/config/config_test.go @@ -0,0 +1,34 @@ +package config + +import ( + "os" + "testing" +) + +func TestParse(t *testing.T) { + // empty config, should not fatal + cfg := Parse("") + if cfg.Secret == "" { + t.Errorf("expected secret, got empty string") + } + + os.Setenv("FATHOM_DATABASE_DRIVER", "sqlite") + cfg = Parse("") + if cfg.Database.Driver != "sqlite3" { + t.Errorf("expected %#v, got %#v", "sqlite3", cfg.Database.Driver) + } + +} + +func TestRandomString(t *testing.T) { + r1 := randomString(10) + r2 := randomString(10) + + if r1 == r2 { + t.Errorf("expected two different strings, got %#v", r1) + } + + if l := len(r1); l != 10 { + t.Errorf("expected string of length %d, got string of length %d", 10, l) + } +}