config.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package application
  2. import (
  3. "encoding/json"
  4. "git.sxidc.com/go-framework/baize/infrastructure"
  5. "git.sxidc.com/go-tools/utils/fileutils"
  6. "git.sxidc.com/service-supports/fserr"
  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. }
  21. func LoadFromJsonFile(jsonFilePath string) (Config, error) {
  22. if !fileutils.PathExists(jsonFilePath) {
  23. return Config{}, fserr.New("配置文件不存在")
  24. }
  25. jsonBytes, err := os.ReadFile(jsonFilePath)
  26. if err != nil {
  27. return Config{}, err
  28. }
  29. return loadFromJson(jsonBytes)
  30. }
  31. func LoadFromYamlFile(yamlFilePath string) (Config, error) {
  32. if !fileutils.PathExists(yamlFilePath) {
  33. return Config{}, fserr.New("配置文件不存在")
  34. }
  35. yamlBytes, err := os.ReadFile(yamlFilePath)
  36. if err != nil {
  37. return Config{}, err
  38. }
  39. return loadFromYaml(yamlBytes)
  40. }
  41. func LoadFromJson(jsonStr string) (Config, error) {
  42. return loadFromJson([]byte(jsonStr))
  43. }
  44. func LoadFromYaml(yamlStr string) (Config, error) {
  45. return loadFromYaml([]byte(yamlStr))
  46. }
  47. func loadFromJson(jsonBytes []byte) (Config, error) {
  48. conf := new(Config)
  49. err := json.Unmarshal(jsonBytes, conf)
  50. if err != nil {
  51. return Config{}, err
  52. }
  53. return *conf, nil
  54. }
  55. func loadFromYaml(yamlBytes []byte) (Config, error) {
  56. conf := new(Config)
  57. err := yaml.Unmarshal(yamlBytes, conf)
  58. if err != nil {
  59. return Config{}, err
  60. }
  61. return *conf, nil
  62. }