full
This commit is contained in:
93
internal/pkg/config/config.go
Normal file
93
internal/pkg/config/config.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var File *Config
|
||||
|
||||
const ConfigDefaultFile = "config.dev.yaml"
|
||||
|
||||
type Config struct {
|
||||
App App `mapstructure:"app" json:"app" yaml:"app"`
|
||||
DB DB `mapstructure:"db" json:"db" yaml:"db"`
|
||||
Redis Redis `mapstructure:"redis" json:"redis" yaml:"redis"`
|
||||
Cors Cors `mapstructure:"cors" json:"cors" yaml:"cors"`
|
||||
JWT JWT `mapstructure:"jwt" json:"jwt" yaml:"jwt"`
|
||||
AliyunUpload AliyunUpload `mapstructure:"aliyunupload" json:"aliyunupload" yaml:"aliyunupload"`
|
||||
TencentUpload TencentUpload `mapstructure:"tencentupload" json:"tencentupload" yaml:"tencentupload"`
|
||||
Captcha Captcha `mapstructure:"captcha" json:"captcha"`
|
||||
Applet Applet `mapstructure:"applet" json:"applet" yaml:"applet"`
|
||||
Smb Smb `mapstructure:"smb" json:"smb" yaml:"smb"`
|
||||
}
|
||||
|
||||
func New(path string) (*Config, error) {
|
||||
fp := "."
|
||||
fn := ConfigDefaultFile
|
||||
if len(path) > 0 {
|
||||
fp, fn = filepath.Split(path)
|
||||
if len(fp) == 0 {
|
||||
fp = "."
|
||||
}
|
||||
}
|
||||
|
||||
v := viper.New()
|
||||
v.AddConfigPath(fp)
|
||||
v.SetConfigName(fn)
|
||||
v.SetConfigType("yaml")
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
v.WatchConfig()
|
||||
|
||||
var conf *Config
|
||||
v.OnConfigChange(func(e fsnotify.Event) {
|
||||
fmt.Println("config file changed:", e.Name)
|
||||
if err := v.Unmarshal(&conf); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
})
|
||||
|
||||
if err := v.Unmarshal(&conf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return conf, nil
|
||||
}
|
||||
|
||||
func Init(path string) error {
|
||||
fp := "."
|
||||
fn := ConfigDefaultFile
|
||||
if len(path) > 0 {
|
||||
fp, fn = filepath.Split(path)
|
||||
if len(fp) == 0 {
|
||||
fp = "."
|
||||
}
|
||||
}
|
||||
|
||||
v := viper.New()
|
||||
v.AddConfigPath(fp)
|
||||
v.SetConfigName(fn)
|
||||
v.SetConfigType("yaml")
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
v.WatchConfig()
|
||||
|
||||
v.OnConfigChange(func(e fsnotify.Event) {
|
||||
fmt.Println("config file changed:", e.Name)
|
||||
if err := v.Unmarshal(&File); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
})
|
||||
|
||||
if err := v.Unmarshal(&File); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user