You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
81 lines
1.8 KiB
81 lines
1.8 KiB
|
1 month ago
|
package config
|
||
|
|
|
||
|
|
import (
|
||
|
|
"fmt"
|
||
|
|
"path/filepath"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"github.com/joho/godotenv"
|
||
|
|
"github.com/spf13/viper"
|
||
|
|
)
|
||
|
|
|
||
|
|
type AppConfig struct {
|
||
|
|
Name string `mapstructure:"name"`
|
||
|
|
Env string `mapstructure:"env"`
|
||
|
|
Port int `mapstructure:"port"`
|
||
|
|
}
|
||
|
|
|
||
|
|
type SQLiteConfig struct {
|
||
|
|
Path string `mapstructure:"path"`
|
||
|
|
}
|
||
|
|
|
||
|
|
type MySQLConfig struct {
|
||
|
|
Host string `mapstructure:"host"`
|
||
|
|
Port int `mapstructure:"port"`
|
||
|
|
User string `mapstructure:"user"`
|
||
|
|
Password string `mapstructure:"password"`
|
||
|
|
DBName string `mapstructure:"dbname"`
|
||
|
|
Params string `mapstructure:"params"`
|
||
|
|
}
|
||
|
|
|
||
|
|
type PostgresConfig struct {
|
||
|
|
Host string `mapstructure:"host"`
|
||
|
|
Port int `mapstructure:"port"`
|
||
|
|
User string `mapstructure:"user"`
|
||
|
|
Password string `mapstructure:"password"`
|
||
|
|
DBName string `mapstructure:"dbname"`
|
||
|
|
SSLMode string `mapstructure:"sslmode"`
|
||
|
|
}
|
||
|
|
|
||
|
|
type DatabaseConfig struct {
|
||
|
|
Driver string `mapstructure:"driver"`
|
||
|
|
SQLite SQLiteConfig `mapstructure:"sqlite"`
|
||
|
|
MySQL MySQLConfig `mapstructure:"mysql"`
|
||
|
|
Postgres PostgresConfig `mapstructure:"postgres"`
|
||
|
|
}
|
||
|
|
|
||
|
|
type Config struct {
|
||
|
|
App AppConfig `mapstructure:"app"`
|
||
|
|
Database DatabaseConfig `mapstructure:"database"`
|
||
|
|
}
|
||
|
|
|
||
|
|
func LoadConfig(configPath string) (*Config, error) {
|
||
|
|
v := viper.New()
|
||
|
|
|
||
|
|
envPath := filepath.Join(configPath, ".env")
|
||
|
|
_ = godotenv.Load(envPath) // ignore missing .env
|
||
|
|
|
||
|
|
v.AddConfigPath(configPath)
|
||
|
|
v.SetConfigName("config")
|
||
|
|
v.SetConfigType("yaml")
|
||
|
|
|
||
|
|
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||
|
|
v.AutomaticEnv()
|
||
|
|
|
||
|
|
if err := v.ReadInConfig(); err != nil {
|
||
|
|
return nil, fmt.Errorf("读取配置失败: %w", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
cfg := new(Config)
|
||
|
|
if err := v.Unmarshal(cfg); err != nil {
|
||
|
|
return nil, fmt.Errorf("解析配置失败: %w", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
if strings.TrimSpace(cfg.Database.Driver) == "" {
|
||
|
|
cfg.Database.Driver = "sqlite"
|
||
|
|
}
|
||
|
|
|
||
|
|
return cfg, nil
|
||
|
|
}
|
||
|
|
|