57 lines
1.2 KiB
Go
57 lines
1.2 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
)
|
|
|
|
type Config struct {
|
|
Server ServerConfig `json:"server"`
|
|
Storage StorageConfig `json:"storage"`
|
|
}
|
|
|
|
type ServerConfig struct {
|
|
Address string `json:"address"` // 监听地址,如 :8080
|
|
Debug bool `json:"debug"` // 是否开启调试模式
|
|
}
|
|
|
|
type StorageConfig struct {
|
|
RootPath string `json:"root_path"` // 数据存储目录
|
|
}
|
|
|
|
// LoadFromFlags 从命令行参数加载配置
|
|
func LoadFromFlags(debug bool, address, dataDir string) (*Config, error) {
|
|
cfg := &Config{
|
|
Server: ServerConfig{
|
|
Address: address,
|
|
Debug: debug,
|
|
},
|
|
Storage: StorageConfig{
|
|
RootPath: dataDir,
|
|
},
|
|
}
|
|
|
|
// 确保存储目录存在
|
|
if err := os.MkdirAll(cfg.Storage.RootPath, 0755); err != nil {
|
|
return nil, fmt.Errorf("failed to create data directory %s: %w", cfg.Storage.RootPath, err)
|
|
}
|
|
|
|
return cfg, nil
|
|
}
|
|
|
|
// Load 从环境变量加载配置(保留向后兼容)
|
|
func Load() (*Config, error) {
|
|
address := getEnv("ADDRESS", ":8080")
|
|
dataDir := getEnv("DATA_DIR", "./storage")
|
|
debug := getEnv("DEBUG", "false") == "true"
|
|
|
|
return LoadFromFlags(debug, address, dataDir)
|
|
}
|
|
|
|
func getEnv(key, defaultValue string) string {
|
|
if value := os.Getenv(key); value != "" {
|
|
return value
|
|
}
|
|
return defaultValue
|
|
}
|