config.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package application
  2. import (
  3. "encoding/json"
  4. "git.sxidc.com/go-framework/baize/framework/core/infrastructure"
  5. "git.sxidc.com/go-tools/utils/fileutils"
  6. "github.com/pkg/errors"
  7. "gopkg.in/yaml.v3"
  8. "os"
  9. )
  10. type Config struct {
  11. ApiConfig `json:"api" yaml:"api"`
  12. InfrastructureConfig `json:"infrastructure" yaml:"infrastructure"`
  13. }
  14. type ApiConfig struct {
  15. UrlPrefix string `json:"url_prefix" yaml:"url_prefix"`
  16. Port string `json:"port" yaml:"port"`
  17. LogSkipPaths []string `json:"log_skip_paths" yaml:"log_skip_paths"`
  18. }
  19. type InfrastructureConfig struct {
  20. Database infrastructure.DatabaseConfig `json:"database" yaml:"database"`
  21. Cache infrastructure.CacheConfig `json:"cache" yaml:"cache"`
  22. MessageQueue infrastructure.MessageQueueConfig `json:"message_queue" yaml:"message_queue"`
  23. }
  24. func LoadFromJsonFile(jsonFilePath string) (Config, error) {
  25. if !fileutils.PathExists(jsonFilePath) {
  26. return Config{}, errors.New("配置文件不存在")
  27. }
  28. jsonBytes, err := os.ReadFile(jsonFilePath)
  29. if err != nil {
  30. return Config{}, err
  31. }
  32. return loadFromJson(jsonBytes)
  33. }
  34. func LoadFromYamlFile(yamlFilePath string) (Config, error) {
  35. if !fileutils.PathExists(yamlFilePath) {
  36. return Config{}, errors.New("配置文件不存在")
  37. }
  38. yamlBytes, err := os.ReadFile(yamlFilePath)
  39. if err != nil {
  40. return Config{}, err
  41. }
  42. return loadFromYaml(yamlBytes)
  43. }
  44. func LoadFromJson(jsonStr string) (Config, error) {
  45. return loadFromJson([]byte(jsonStr))
  46. }
  47. func LoadFromYaml(yamlStr string) (Config, error) {
  48. return loadFromYaml([]byte(yamlStr))
  49. }
  50. func loadFromJson(jsonBytes []byte) (Config, error) {
  51. conf := new(Config)
  52. err := json.Unmarshal(jsonBytes, conf)
  53. if err != nil {
  54. return Config{}, errors.New(err.Error())
  55. }
  56. return *conf, nil
  57. }
  58. func loadFromYaml(yamlBytes []byte) (Config, error) {
  59. conf := new(Config)
  60. err := yaml.Unmarshal(yamlBytes, conf)
  61. if err != nil {
  62. return Config{}, errors.New(err.Error())
  63. }
  64. return *conf, nil
  65. }