object.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package config
  2. import "github.com/spf13/viper"
  3. type config struct {
  4. Viper *viper.Viper
  5. }
  6. func New() *config {
  7. var c config
  8. c.Viper = viper.New()
  9. c.Viper.SetConfigName(defaultName) //defaultName := lib.AppName()
  10. c.Viper.SetConfigType(defaultConfigType)
  11. c.Viper.AddConfigPath(defaultPath)
  12. return &c
  13. }
  14. func NewConfig(name, suffix, path string) *config {
  15. var c config
  16. c.Viper = viper.New()
  17. c.Viper.SetConfigName(name) //defaultName := lib.AppName()
  18. c.Viper.SetConfigType(suffix)
  19. c.Viper.AddConfigPath(path)
  20. return &c
  21. }
  22. func (c *config) Load() error {
  23. return c.Viper.ReadInConfig()
  24. }
  25. func (c *config) Store() error {
  26. return c.Viper.SafeWriteConfig()
  27. }
  28. func (c *config) Register(module, key string, value any) {
  29. c.Viper.SetDefault(module+"."+key, value)
  30. }
  31. func (c *config) GetBool(module, key string) bool {
  32. return c.Viper.GetBool(module + "." + key)
  33. }
  34. func (c *config) GetString(module, key string) string {
  35. return c.Viper.GetString(module + "." + key)
  36. }
  37. func (c *config) GetInt(module, key string) int {
  38. return c.Viper.GetInt(module + "." + key)
  39. }
  40. func (c *config) GetFloat(module, key string) float64 {
  41. return c.Viper.GetFloat64(module + "." + key)
  42. }
  43. func (c *config) GetStringSlice(module string, key string) []string {
  44. return c.Viper.GetStringSlice(module + "." + key)
  45. }
  46. func (c *config) Set(module, key string, value any) {
  47. c.Viper.Set(module+"."+key, value)
  48. }
  49. func (c *config) ReadConfigAndFileExist() (bool, error) {
  50. if err := c.Viper.ReadInConfig(); err != nil {
  51. if _, ok := err.(viper.ConfigFileNotFoundError); ok {
  52. // 配置文件未找到
  53. return false, nil
  54. } else {
  55. // 其他错误
  56. return true, err
  57. }
  58. }
  59. return true, nil
  60. }