2026-06-18 22:48:16 +08:00
|
|
|
package config
|
|
|
|
|
|
|
|
|
|
import (
|
2026-06-20 21:57:46 +08:00
|
|
|
"crypto/rand"
|
|
|
|
|
"encoding/hex"
|
2026-06-20 22:40:46 +08:00
|
|
|
"fmt"
|
2026-06-18 22:48:16 +08:00
|
|
|
"os"
|
|
|
|
|
"path/filepath"
|
2026-06-20 22:40:46 +08:00
|
|
|
|
|
|
|
|
"github.com/joho/godotenv"
|
2026-06-18 22:48:16 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type Config struct {
|
2026-06-20 21:57:46 +08:00
|
|
|
Port string
|
|
|
|
|
GinMode string
|
|
|
|
|
DataDir string
|
|
|
|
|
SessionSecret string
|
2026-06-20 22:40:46 +08:00
|
|
|
MySQLHost string
|
|
|
|
|
MySQLPort string
|
|
|
|
|
MySQLUser string
|
|
|
|
|
MySQLPassword string
|
|
|
|
|
MySQLDatabase string
|
2026-06-18 22:48:16 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func Load() *Config {
|
2026-06-20 22:40:46 +08:00
|
|
|
// Load .env file if present (ignore error if missing)
|
|
|
|
|
godotenv.Load()
|
|
|
|
|
|
2026-06-18 22:48:16 +08:00
|
|
|
cfg := &Config{
|
2026-06-20 21:57:46 +08:00
|
|
|
Port: getEnv("PORT", "8080"),
|
|
|
|
|
GinMode: getEnv("GIN_MODE", "debug"),
|
|
|
|
|
DataDir: getEnv("DATA_DIR", "data"),
|
|
|
|
|
SessionSecret: getEnv("SESSION_SECRET", ""),
|
2026-06-20 22:40:46 +08:00
|
|
|
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"),
|
2026-06-20 21:57:46 +08:00
|
|
|
}
|
|
|
|
|
// Generate random session secret if not provided
|
|
|
|
|
if cfg.SessionSecret == "" {
|
|
|
|
|
b := make([]byte, 32)
|
|
|
|
|
rand.Read(b)
|
|
|
|
|
cfg.SessionSecret = hex.EncodeToString(b)
|
2026-06-18 22:48:16 +08:00
|
|
|
}
|
|
|
|
|
// Ensure data directories exist
|
|
|
|
|
os.MkdirAll(cfg.DataDir, 0o755)
|
|
|
|
|
os.MkdirAll(filepath.Join(cfg.DataDir, "repos"), 0o755)
|
|
|
|
|
return cfg
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-20 22:40:46 +08:00
|
|
|
// 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)
|
2026-06-18 22:48:16 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
}
|