config.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package pkg
  2. import (
  3. "errors"
  4. "github.com/allanpk716/ChineseSubFinder/internal/types"
  5. "github.com/spf13/viper"
  6. "strings"
  7. "sync"
  8. )
  9. // GetConfig 统一获取配置的接口
  10. func GetConfig() *types.Config {
  11. configOnce.Do(func() {
  12. configViper, err := initConfigure()
  13. if err != nil {
  14. panic("GetConfig - initConfigure " + err.Error())
  15. }
  16. config, err = readConfig(configViper)
  17. if err != nil {
  18. panic("GetConfig - readConfig " + err.Error())
  19. }
  20. // 读取用户自定义的视频后缀名列表
  21. for _, customExt := range strings.Split(config.CustomVideoExts, ",") {
  22. customVideoExts = append(customVideoExts, "."+customExt)
  23. }
  24. })
  25. return config
  26. }
  27. // initConfigure 初始化配置文件实例
  28. func initConfigure() (*viper.Viper, error) {
  29. v := viper.New()
  30. v.SetConfigName("config") // 设置文件名称(无后缀)
  31. v.SetConfigType("yaml") // 设置后缀名 {"1.6以后的版本可以不设置该后缀"}
  32. v.AddConfigPath(".") // 设置文件所在路径
  33. err := v.ReadInConfig()
  34. if err != nil {
  35. return nil, errors.New("error reading config:" + err.Error())
  36. }
  37. return v, nil
  38. }
  39. // readConfig 读取配置文件
  40. func readConfig(viper *viper.Viper) (*types.Config, error) {
  41. conf := &types.Config{}
  42. err := viper.Unmarshal(conf)
  43. if err != nil {
  44. return nil, err
  45. }
  46. return conf, nil
  47. }
  48. var (
  49. config *types.Config
  50. configOnce sync.Once
  51. )