This commit is contained in:
2026-06-23 11:23:33 +08:00
parent 5f8c7be5ac
commit a316932d3f
2 changed files with 56 additions and 8 deletions
+20 -4
View File
@@ -14,7 +14,7 @@ import (
// Config holds all application configuration.
type Config struct {
Database DatabaseConfig `yaml:"database"`
Port string `yaml:"port"`
Web WebConfig `yaml:"web"`
Path string `yaml:"path"`
Secret string `yaml:"secret"`
}
@@ -25,6 +25,12 @@ type DatabaseConfig struct {
DSN string `yaml:"dsn"` // MySQL connection string (required when type is "mysql")
}
// WebConfig holds web-server listening configuration.
type WebConfig struct {
Port string `yaml:"port"` // TCP port, "" or "0" to disable
Socket string `yaml:"socket"` // Unix socket path, "" to disable
}
const defaultPort = "8080"
// mysqlExampleDSN is written into new config files as a reference.
@@ -64,6 +70,13 @@ func generateSecret() string {
return fmt.Sprintf("%x", hash)
}
// getDefaultSocketPath returns the OS-aware default unix socket path.
func getDefaultSocketPath() string {
if runtime.GOOS == "linux" {
return "/opt/blog_go/web.sock"
}
return ""
}
// LoadConfig reads the config file or creates one with defaults.
func LoadConfig() *Config {
configDir, configFile := getConfigPath()
@@ -81,7 +94,10 @@ func LoadConfig() *Config {
Type: "sqlite",
DSN: mysqlExampleDSN,
},
Port: defaultPort,
Web: WebConfig{
Port: defaultPort,
Socket: getDefaultSocketPath(),
},
Path: defaultPath,
Secret: generateSecret(),
}
@@ -116,8 +132,8 @@ func LoadConfig() *Config {
// applyDefaults fills zero-value fields with sensible defaults.
func applyDefaults(cfg *Config, defaultPath string) *Config {
if cfg.Port == "" {
cfg.Port = defaultPort
if cfg.Web.Port == "" {
cfg.Web.Port = defaultPort
}
if cfg.Database.Type == "" {
cfg.Database.Type = "sqlite"