object.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 viper.GetStringSlice(module + "." + key)
  45. }
  46. func (c *config) Set(module, key string, value any) {
  47. viper.Set(module+"."+key, value)
  48. }