Files
PR-Helper/config/config.go
T
wonder 00c1839635 feat: migrate database from SQLite to MySQL with .env configuration
- Replace go-sqlite3 with go-sql-driver/mysql (pure Go, no CGO needed)
- Add joho/godotenv for .env file loading
- Rewrite database/db.go with MySQL-compatible DDL (BIGINT AUTO_INCREMENT, InnoDB, utf8mb4)
- Convert all SQLite-specific SQL: INSERT OR IGNORE → INSERT IGNORE,
  INSERT OR REPLACE → INSERT ... ON DUPLICATE KEY UPDATE,
  datetime('now') → NOW(), date arithmetic → DATE_SUB()
- Add MySQL config fields to config.go (host/port/user/password/database)
- Add .env.example with connection parameter template
- Update Dockerfile: remove CGO/gcc/musl dependency, smaller build
- Update docker-compose.yml: add MySQL service container with healthcheck
- Update CLAUDE.md documentation
2026-06-20 22:40:46 +08:00

68 lines
1.6 KiB
Go

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
}