github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/config/option.go (about)

     1  package config
     2  
     3  import (
     4  	"log"
     5  	"path/filepath"
     6  
     7  	"github.com/fsnotify/fsnotify"
     8  )
     9  
    10  func WithPrefix(name string) Option {
    11  	return func(cfg *Config) {
    12  		//cfg.Prefix = name
    13  	}
    14  }
    15  
    16  func WithFileName(fileName string) Option {
    17  	return func(cfg *Config) {
    18  		cfg.Core().FileName = fileName
    19  	}
    20  }
    21  
    22  // 保存新配置数据
    23  func WithConfig(model IConfig) Option {
    24  	return func(cfg *Config) {
    25  		err := cfg.SaveFromModel(model)
    26  		if err != nil {
    27  			log.Fatal(err)
    28  		}
    29  	}
    30  }
    31  
    32  // 监听配置文件变动
    33  func WithWatcher() Option {
    34  	return func(cfg *Config) {
    35  		core := cfg.Core()
    36  		// 监视文件
    37  		if core.FileName == "" {
    38  			core.FileName = CONFIG_FILE_NAME //filepath.Join(AppPath, CONFIG_FILE_NAME)
    39  		}
    40  		core.fmt.v.SetConfigFile(filepath.Join(AppPath, core.FileName))
    41  		core.fmt.v.WatchConfig()
    42  		core.fmt.v.OnConfigChange(func(e fsnotify.Event) {
    43  			if e.Op == fsnotify.Write {
    44  				cfg.Reload() // 重新加载配置
    45  			}
    46  		})
    47  	}
    48  }
    49  
    50  // 当无配置文件时不自动创建配置文件
    51  func WithNoAutoCreateFile() Option {
    52  	return func(cfg *Config) {
    53  		cfg.AutoCreateFile = false
    54  	}
    55  }