package config import ( "fmt" "log" "net" "os" "strconv" "github.com/joho/godotenv" ) type Config struct { GRPCPort int GRPCEnableReflection bool HTTPPort int LogLevel string DBHost string DBPort int DBUser string DBPassword string DBName string AuthSvcAddr string } func Load() (*Config, error) { _ = godotenv.Load() return &Config{ GRPCPort: mustGetInt("ACHIEVEMENTS_GRPC_PORT", 50057), GRPCEnableReflection: mustGetBool("ACHIEVEMENTS_GRPC_ENABLE_REFLECTION", false), HTTPPort: mustGetInt("ACHIEVEMENTS_HTTP_PORT", 8087), LogLevel: getEnv("LOG_LEVEL", "info"), DBHost: getEnv("POSTGRES_HOST", "localhost"), DBPort: mustGetInt("POSTGRES_PORT", 5432), DBUser: getEnv("POSTGRES_USERNAME", "postgres"), DBPassword: getEnv("POSTGRES_PASSWORD", "postgres"), DBName: getEnv("POSTGRES_DATABASE", "postgres"), AuthSvcAddr: getEnv("AUTH_SVC_ADDR", "localhost:50051"), }, nil } func getEnv(key, def string) string { if val := os.Getenv(key); val != "" { return val } return def } func mustGetInt(key string, def int) int { val := getEnv(key, strconv.Itoa(def)) n, err := strconv.Atoi(val) if err != nil { log.Fatalf("invalid int for %s: %v", key, err) } return n } func mustGetBool(key string, def bool) bool { val := getEnv(key, strconv.FormatBool(def)) b, err := strconv.ParseBool(val) if err != nil { log.Fatalf("invalid bool for %s: %v", key, err) } return b } func (c Config) BuildPostgresConnStr() string { return fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", c.DBHost, c.DBPort, c.DBUser, c.DBPassword, c.DBName) } func (c Config) BuildPostgresDSN() string { return fmt.Sprintf("postgresql://%s:%s@%s/%s?sslmode=disable", c.DBUser, c.DBPassword, net.JoinHostPort(c.DBHost, strconv.Itoa(c.DBPort)), c.DBName) }