gomog/internal/config/config.go

117 lines
2.2 KiB
Go

package config
import (
"os"
"gopkg.in/yaml.v3"
)
// Config 应用配置
type Config struct {
Server ServerConfig `yaml:"server"`
Database DatabaseConfig `yaml:"database"`
Log LogConfig `yaml:"log"`
}
// ServerConfig 服务器配置
type ServerConfig struct {
HTTPAddr string `yaml:"http_addr"`
TCPAddr string `yaml:"tcp_addr"`
Mode string `yaml:"mode"` // dev, prod
}
// DatabaseConfig 数据库配置
type DatabaseConfig struct {
Type string `yaml:"type"` // dm8, sqlite, postgres
DSN string `yaml:"dsn"` // 数据源名称
MaxOpen int `yaml:"max_open"` // 最大打开连接数
MaxIdle int `yaml:"max_idle"` // 最大空闲连接数
}
// LogConfig 日志配置
type LogConfig struct {
Level string `yaml:"level"` // debug, info, warn, error
Format string `yaml:"format"` // json, text
}
// DefaultConfig 默认配置
func DefaultConfig() *Config {
return &Config{
Server: ServerConfig{
HTTPAddr: ":8080",
TCPAddr: ":27017",
Mode: "dev",
},
Database: DatabaseConfig{
Type: "sqlite",
DSN: "gomog.db",
MaxOpen: 10,
MaxIdle: 5,
},
Log: LogConfig{
Level: "info",
Format: "text",
},
}
}
// Load 从文件加载配置
func Load(path string) (*Config, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
config := DefaultConfig()
decoder := yaml.NewDecoder(file)
if err := decoder.Decode(config); err != nil {
return nil, err
}
return config, nil
}
// Save 保存配置到文件
func (c *Config) Save(path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
encoder := yaml.NewEncoder(file)
return encoder.Encode(c)
}
// Validate 验证配置
func (c *Config) Validate() error {
// 验证服务器地址
if c.Server.HTTPAddr == "" && c.Server.TCPAddr == "" {
return ErrNoServerAddress
}
// 验证数据库类型
switch c.Database.Type {
case "sqlite", "postgres", "dm8":
// 有效
default:
return ErrInvalidDatabaseType
}
// 验证 DSN
if c.Database.DSN == "" {
return ErrEmptyDSN
}
// 设置默认值
if c.Database.MaxOpen <= 0 {
c.Database.MaxOpen = 10
}
if c.Database.MaxIdle <= 0 {
c.Database.MaxIdle = 5
}
return nil
}