config.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. }
  18. type InfrastructureConfig struct {
  19. Database infrastructure.DatabaseConfig `json:"database" yaml:"database"`
  20. Cache infrastructure.CacheConfig `json:"cache" yaml:"cache"`
  21. }
  22. func LoadFromJsonFile(jsonFilePath string) (Config, error) {
  23. if !fileutils.PathExists(jsonFilePath) {
  24. return Config{}, errors.New("配置文件不存在")
  25. }
  26. jsonBytes, err := os.ReadFile(jsonFilePath)
  27. if err != nil {
  28. return Config{}, err
  29. }
  30. return loadFromJson(jsonBytes)
  31. }
  32. func LoadFromYamlFile(yamlFilePath string) (Config, error) {
  33. if !fileutils.PathExists(yamlFilePath) {
  34. return Config{}, errors.New("配置文件不存在")
  35. }
  36. yamlBytes, err := os.ReadFile(yamlFilePath)
  37. if err != nil {
  38. return Config{}, err
  39. }
  40. return loadFromYaml(yamlBytes)
  41. }
  42. func LoadFromJson(jsonStr string) (Config, error) {
  43. return loadFromJson([]byte(jsonStr))
  44. }
  45. func LoadFromYaml(yamlStr string) (Config, error) {
  46. return loadFromYaml([]byte(yamlStr))
  47. }
  48. func loadFromJson(jsonBytes []byte) (Config, error) {
  49. conf := new(Config)
  50. err := json.Unmarshal(jsonBytes, conf)
  51. if err != nil {
  52. return Config{}, errors.New(err.Error())
  53. }
  54. return *conf, nil
  55. }
  56. func loadFromYaml(yamlBytes []byte) (Config, error) {
  57. conf := new(Config)
  58. err := yaml.Unmarshal(yamlBytes, conf)
  59. if err != nil {
  60. return Config{}, errors.New(err.Error())
  61. }
  62. return *conf, nil
  63. }