object.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. err := c.Viper.SafeWriteConfig()
  27. if err != nil {
  28. err = c.Viper.WriteConfig()
  29. }
  30. return err
  31. }
  32. func (c *config) Register(module, key string, value any) {
  33. c.Viper.SetDefault(module+"."+key, value)
  34. }
  35. func (c *config) GetBool(module, key string) bool {
  36. return c.Viper.GetBool(module + "." + key)
  37. }
  38. func (c *config) GetString(module, key string) string {
  39. return c.Viper.GetString(module + "." + key)
  40. }
  41. func (c *config) GetInt(module, key string) int {
  42. return c.Viper.GetInt(module + "." + key)
  43. }
  44. func (c *config) GetFloat(module, key string) float64 {
  45. return c.Viper.GetFloat64(module + "." + key)
  46. }
  47. func (c *config) GetStringSlice(module string, key string) []string {
  48. return c.Viper.GetStringSlice(module + "." + key)
  49. }
  50. func (c *config) Set(module, key string, value any) {
  51. c.Viper.Set(module+"."+key, value)
  52. }
  53. func (c *config) Unmarshal(value any, arr ...string) error {
  54. key := ""
  55. for _, s := range arr {
  56. if len(key) != 0 {
  57. key += "."
  58. }
  59. key += s
  60. }
  61. if len(key) != 0 {
  62. return c.Viper.UnmarshalKey(key, value)
  63. } else {
  64. return c.Viper.Unmarshal(value)
  65. }
  66. }
  67. func (c *config) ReadConfigAndFileExist() (bool, error) {
  68. if err := c.Viper.ReadInConfig(); err != nil {
  69. if _, ok := err.(viper.ConfigFileNotFoundError); ok {
  70. // 配置文件未找到
  71. return false, nil
  72. } else {
  73. // 其他错误
  74. return true, err
  75. }
  76. }
  77. return true, nil
  78. }