config.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package config
  2. import (
  3. "github.com/spf13/viper"
  4. )
  5. var (
  6. defaultName = "config"
  7. defaultConfigType = "yaml"
  8. defaultPath = "."
  9. )
  10. func Default() {
  11. //引入viper配置文件
  12. viper.SetConfigName(defaultName) //defaultName := lib.AppName()
  13. viper.SetConfigType(defaultConfigType)
  14. viper.AddConfigPath(defaultPath)
  15. }
  16. func SetConfigInfo(name, suffix, path string) {
  17. viper.SetConfigName(name) //defaultName := lib.AppName()
  18. viper.SetConfigType(suffix)
  19. viper.AddConfigPath(path)
  20. }
  21. func Load() error {
  22. return viper.ReadInConfig()
  23. }
  24. func Store() error {
  25. err := viper.SafeWriteConfig()
  26. if err != nil {
  27. err = viper.WriteConfig()
  28. }
  29. return err
  30. }
  31. func Register(module string, key string, value any) {
  32. viper.SetDefault(module+"."+key, value)
  33. }
  34. func GetBool(module string, key string) bool {
  35. return viper.GetBool(module + "." + key)
  36. }
  37. func GetString(module string, key string) string {
  38. return viper.GetString(module + "." + key)
  39. }
  40. func GetInt(module string, key string) int {
  41. return viper.GetInt(module + "." + key)
  42. }
  43. func GetFloat(module string, key string) float64 {
  44. return viper.GetFloat64(module + "." + key)
  45. }
  46. func GetStringSlice(module string, key string) []string {
  47. return viper.GetStringSlice(module + "." + key)
  48. }
  49. func Set(module, key string, value any) {
  50. viper.Set(module+"."+key, value)
  51. }
  52. func Unmarshal(value any, arr ...string) error {
  53. key := ""
  54. for _, s := range arr {
  55. if len(key) != 0 {
  56. key += "."
  57. }
  58. key += s
  59. }
  60. if len(key) != 0 {
  61. return viper.UnmarshalKey(key, value)
  62. } else {
  63. return viper.Unmarshal(value)
  64. }
  65. }
  66. func ReadConfigAndFileExist() (bool, error) {
  67. if err := viper.ReadInConfig(); err != nil {
  68. if _, ok := err.(viper.ConfigFileNotFoundError); ok {
  69. // 配置文件未找到
  70. return false, nil
  71. } else {
  72. // 其他错误
  73. return true, err
  74. }
  75. }
  76. return true, nil
  77. }