12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- package global
- import "github.com/spf13/viper"
- type Settings struct {
- vp *viper.Viper
- }
- var sections = make(map[string]interface{})
- // NewSetting 读取配置
- func NewSetting() (*Settings, error) {
- vp := viper.New()
- vp.SetConfigName("config")
- vp.AddConfigPath("./backend/configs")
- vp.SetConfigType("yaml")
- err := vp.ReadInConfig()
- if err != nil {
- return nil, err
- }
- s := &Settings{vp}
- return s, nil
- }
- // ReadSection 读取指定的一段
- func (s *Settings) ReadSection(k string, v interface{}) error {
- err := s.vp.UnmarshalKey(k, v)
- if err != nil {
- return err
- }
- if _, ok := sections[k]; !ok {
- sections[k] = v
- }
- return nil
- }
- // ReloadAllSection 重新加载
- func (s *Settings) ReloadAllSection() error {
- for k, v := range sections {
- err := s.ReadSection(k, v)
- if err != nil {
- return err
- }
- }
- return nil
- }
|