config.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. return viper.SafeWriteConfig()
  26. }
  27. func Register(module string, key string, value any) {
  28. viper.SetDefault(module+"."+key, value)
  29. }
  30. func GetBool(module string, key string) bool {
  31. return viper.GetBool(module + "." + key)
  32. }
  33. func GetString(module string, key string) string {
  34. return viper.GetString(module + "." + key)
  35. }
  36. func GetInt(module string, key string) int {
  37. return viper.GetInt(module + "." + key)
  38. }
  39. func GetFloat(module string, key string) float64 {
  40. return viper.GetFloat64(module + "." + key)
  41. }
  42. func GetStringSlice(module string, key string) []string {
  43. return viper.GetStringSlice(module + "." + key)
  44. }
  45. func Set(module, key string, value any) {
  46. viper.Set(module+"."+key, value)
  47. }
  48. func IsExistConfigFile() bool {
  49. if err := viper.ReadInConfig(); err != nil {
  50. if _, ok := err.(viper.ConfigFileNotFoundError); ok {
  51. // 配置文件未找到
  52. return true
  53. } else {
  54. // 其他错误
  55. return false
  56. }
  57. }
  58. return false
  59. }