增加mysql配置

This commit is contained in:
2026-06-21 01:54:43 +08:00
parent c82d4482d4
commit 126e1d9234
2 changed files with 11 additions and 12 deletions
+8 -8
View File
@@ -22,12 +22,14 @@ type Config struct {
// DatabaseConfig holds database-specific configuration.
type DatabaseConfig struct {
Type string `yaml:"type"` // "sqlite" (default) or "mysql"
DSN string `yaml:"dsn"` // MySQL connection string (ignored for sqlite)
DSN string `yaml:"dsn"` // MySQL connection string (required when type is "mysql")
}
// defaultPort is the fallback web server port.
const defaultPort = "8080"
// mysqlExampleDSN is written into new config files as a reference.
const mysqlExampleDSN = "user:password@tcp(127.0.0.1:3306)/blog_go?charset=utf8mb4&parseTime=True&loc=Local"
// getConfigPath returns the OS-aware config directory and config file path.
func getConfigPath() (dir, file string) {
if runtime.GOOS == "windows" {
@@ -49,7 +51,6 @@ func getDefaultStoragePath() string {
// generateSecret returns a random-ish hex string for the session secret.
func generateSecret() string {
// Use a combination of hostname + random to produce a unique secret.
hostname, _ := os.Hostname()
input := fmt.Sprintf("%s-%d", hostname, os.Getpid())
hash := sha256.Sum256([]byte(input))
@@ -61,8 +62,6 @@ func LoadConfig() *Config {
configDir, configFile := getConfigPath()
defaultPath := getDefaultStoragePath()
cfg := &Config{}
// Check if config file exists; create with defaults if not.
if _, err := os.Stat(configFile); os.IsNotExist(err) {
log.Printf("Config file not found at %s, creating with defaults...", configFile)
@@ -70,10 +69,10 @@ func LoadConfig() *Config {
log.Fatalf("Failed to create config directory %s: %v", configDir, err)
}
cfg = &Config{
cfg := &Config{
Database: DatabaseConfig{
Type: "sqlite",
DSN: "",
DSN: mysqlExampleDSN,
},
Port: defaultPort,
Path: defaultPath,
@@ -96,12 +95,13 @@ func LoadConfig() *Config {
data, err := os.ReadFile(configFile)
if err != nil {
log.Printf("Warning: could not read config file %s: %v, using defaults", configFile, err)
cfg := &Config{}
return applyDefaults(cfg, defaultPath)
}
cfg := &Config{}
if err := yaml.Unmarshal(data, cfg); err != nil {
log.Printf("Warning: malformed config file %s: %v, using defaults", configFile, err)
cfg = &Config{}
}
return applyDefaults(cfg, defaultPath)
+3 -4
View File
@@ -28,11 +28,10 @@ func InitDB(cfg *config.Config) *gorm.DB {
switch cfg.Database.Type {
case "mysql":
dsn := cfg.Database.DSN
if dsn == "" {
dsn = "root:password@tcp(127.0.0.1:3306)/blog_go?charset=utf8mb4&parseTime=True&loc=Local"
if cfg.Database.DSN == "" {
log.Fatalf("Database DSN is required when type is 'mysql'. Please set it in your config file.")
}
dialector = mysql.Open(dsn)
dialector = mysql.Open(cfg.Database.DSN)
default:
dbPath := filepath.Join(cfg.Path, "blog.db")
dialector = sqlite.Open(dbPath)