config.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package application
  2. import (
  3. "encoding/json"
  4. "git.sxidc.com/go-framework/baize/infrastructure/database/operations"
  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 InfrastructureDatabase
  20. }
  21. type InfrastructureDatabase struct {
  22. Operations *operations.Config
  23. }
  24. func LoadFromJsonFile(jsonFilePath string) (Config, error) {
  25. if !fileutils.PathExists(jsonFilePath) {
  26. return Config{}, fserr.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{}, fserr.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{}, err
  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{}, err
  63. }
  64. return *conf, nil
  65. }