Files

68 lines
1.6 KiB
Go
Raw Permalink Normal View History

package config
import (
"crypto/rand"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"github.com/joho/godotenv"
)
type Config struct {
Port string
GinMode string
DataDir string
SessionSecret string
MySQLHost string
MySQLPort string
MySQLUser string
MySQLPassword string
MySQLDatabase string
}
func Load() *Config {
// Load .env file if present (ignore error if missing)
godotenv.Load()
cfg := &Config{
Port: getEnv("PORT", "8080"),
GinMode: getEnv("GIN_MODE", "debug"),
DataDir: getEnv("DATA_DIR", "data"),
SessionSecret: getEnv("SESSION_SECRET", ""),
MySQLHost: getEnv("MYSQL_HOST", "127.0.0.1"),
MySQLPort: getEnv("MYSQL_PORT", "3306"),
MySQLUser: getEnv("MYSQL_USER", "root"),
MySQLPassword: getEnv("MYSQL_PASSWORD", ""),
MySQLDatabase: getEnv("MYSQL_DATABASE", "pr_helper"),
}
// Generate random session secret if not provided
if cfg.SessionSecret == "" {
b := make([]byte, 32)
rand.Read(b)
cfg.SessionSecret = hex.EncodeToString(b)
}
// Ensure data directories exist
os.MkdirAll(cfg.DataDir, 0o755)
os.MkdirAll(filepath.Join(cfg.DataDir, "repos"), 0o755)
return cfg
}
// MySQLDSN returns the MySQL Data Source Name for go-sql-driver/mysql.
func (c *Config) MySQLDSN() string {
return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
c.MySQLUser, c.MySQLPassword, c.MySQLHost, c.MySQLPort, c.MySQLDatabase)
}
func (c *Config) ReposDir() string {
return filepath.Join(c.DataDir, "repos")
}
func getEnv(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}