package config import ( "fmt" "path/filepath" "strings" "time" "github.com/fsnotify/fsnotify" "github.com/spf13/viper" ) func New(path string) (*Config, error) { v := viper.New() v.AddConfigPath(filepath.Dir(path)) v.SetConfigName(filepath.Base(path)) v.SetConfigType(strings.TrimPrefix(filepath.Ext(path), ".")) if err := v.ReadInConfig(); err != nil { return nil, err } v.WatchConfig() var config Config v.OnConfigChange(func(e fsnotify.Event) { fmt.Println("config file changed:", e.Name) if err := v.Unmarshal(&config); err != nil { fmt.Println(err) } }) if err := v.Unmarshal(&config); err != nil { return nil, err } return &config, nil } type Config struct { App struct { Host string `mapstructure:"host"` // 服务地址 Port int `mapstructure:"port"` // 服务端口 Prod bool `mapstructure:"prod"` // 是否正式 } `mapstructure:"app"` DB struct { Driver string `mapstructure:"driver"` // 数据库类型 Host string `mapstructure:"host"` // 数据库地址 Port int `mapstructure:"port"` // 数据库端口 Username string `mapstructure:"username"` // 数据库用户 Password string `mapstructure:"password"` // 数据库密码 DBName string `mapstructure:"db_name"` // 数据库名称 MaxIdleConns int `mapstructure:"max_idle_conns"` // 最大空闲连接数 MaxOpenConns int `mapstructure:"max_open_conns"` // 最大打开连接数 ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"` // 连接最大存活时间 ConnMaxIdleTime time.Duration `mapstructure:"conn_max_idle_time"` // 连接最大空闲时间 LogMode bool `mapstructure:"log_mode"` // 是否开启日志 } `mapstructure:"db"` Redis struct { Host string `mapstructure:"host"` // redis地址 Port int `mapstructure:"port"` // redis端口 Password string `mapstructure:"password"` // redis密码 DB int `mapstructure:"db"` // redis数据库 } `mapstructure:"redis"` Cors struct { Host string `mapstructure:"host"` } `mapstructure:"cors"` JWT struct { SigningKey string `mapstructure:"signing_key"` // jwt签名 ExpiresTime time.Duration `mapstructure:"expires_time"` // 过期时间 RefreshTime time.Duration `mapstructure:"refresh_time"` // 刷新过期时间 Issuer string `mapstructure:"issuer"` // 签发者 } `mapstructure:"jwt"` Captcha struct { OpenCaptcha int `mapstructure:"open_captcha"` // 是否开启防爆次数 ImgWidth int `mapstructure:"img_width"` // 验证码图片宽度 ImgHeight int `mapstructure:"img_height"` // 验证码图片高度 KeyLong int `mapstructure:"key_long"` // 验证码长度 } `mapstructure:"captcha"` }