2025-05-28 16:19:21 +08:00

91 lines
2.5 KiB
Go

package config
import (
"errors"
"time"
"github.com/spf13/viper"
)
type Config struct {
Server ServerConfig `mapstructure:"server"`
Database DatabaseConfig `mapstructure:"database"`
Log LogConfig `mapstructure:"log"`
Monitoring MonitoringConfig `mapstructure:"monitoring"`
}
type ServerConfig struct {
Port string `mapstructure:"port"`
Mode string `mapstructure:"mode"`
HospitalCode string `mapstructure:"hospital_code"`
ReadTimeout time.Duration `mapstructure:"read_timeout"`
WriteTimeout time.Duration `mapstructure:"write_timeout"`
MaxConnNum int `mapstructure:"max_conn_num"`
}
type DatabaseConfig struct {
Driver string `mapstructure:"driver"`
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
DBName string `mapstructure:"dbname"`
Charset string `mapstructure:"charset"`
ParseTime bool `mapstructure:"parseTime"`
Loc string `mapstructure:"loc"`
MaxIdleConns int `mapstructure:"max_idle_conns"`
MaxOpenConns int `mapstructure:"max_open_conns"`
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"`
}
type LogConfig struct {
Level string `mapstructure:"level"`
Format string `mapstructure:"format"`
OutputPath string `mapstructure:"output_path"`
MaxSize int `mapstructure:"max_size"`
MaxAge int `mapstructure:"max_age"`
MaxBackups int `mapstructure:"max_backups"`
Compress bool `mapstructure:"compress"`
}
type MonitoringConfig struct {
Enabled bool `mapstructure:"enabled"`
PrometheusPort string `mapstructure:"prometheus_port"`
}
var GlobalConfig Config
func Init() error {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath("./config")
if err := viper.ReadInConfig(); err != nil {
return err
}
if err := viper.Unmarshal(&GlobalConfig); err != nil {
return err
}
// 验证配置项
if err := validate(); err != nil {
return err
}
return nil
}
func validate() error {
if GlobalConfig.Server.Port == "" {
return errors.New("server port is required")
}
if GlobalConfig.Server.HospitalCode == "" {
return errors.New("hospital code is required")
}
if GlobalConfig.Database.Host == "" {
return errors.New("database host is required")
}
return nil
}