config.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 ReadConfigAndFileExist() (bool, error) {
  53. if err := viper.ReadInConfig(); err != nil {
  54. if _, ok := err.(viper.ConfigFileNotFoundError); ok {
  55. // 配置文件未找到
  56. return false, nil
  57. } else {
  58. // 其他错误
  59. return true, err
  60. }
  61. }
  62. return true, nil
  63. }