config.go 1.8 KB

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