config.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package common
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "goiot-pkg/tools"
  6. "gopkg.in/yaml.v2"
  7. "io/ioutil"
  8. "os"
  9. "path"
  10. "runtime"
  11. )
  12. var ConfigInfo *configModel
  13. //serverModel get server information from config.yml
  14. type serverModel struct {
  15. Mode string `yaml:"mode"` // run mode
  16. Host string `yaml:"host"` // server host
  17. Port string `yaml:"port"` // server port
  18. TokenExpire int64 `yaml:"token_expire"` // token expire seconds
  19. }
  20. //logModel get log information from config.yml
  21. type logModel struct {
  22. Compress int `yaml:"compress"`
  23. ConsoleStdout int `yaml:"console_stdout"`
  24. FileStdout int `yaml:"file_stdout"`
  25. Level string `yaml:"level"`
  26. LocalTime int `yaml:"local_time"`
  27. MaxAge int `yaml:"max_age"`
  28. MaxBackups int `yaml:"max_backups"`
  29. MaxSize int `yaml:"max_size"`
  30. Path string `yaml:"path"`
  31. }
  32. type configModel struct {
  33. Server *serverModel `yaml:"server"`
  34. Log *logModel `yaml:"log"`
  35. FileServUrl string
  36. }
  37. // LoadConfigInformation load config information for application
  38. func LoadConfigInformation() error {
  39. var err error
  40. // 先读取config.yml配置文件
  41. // 获取当前是debug模式还是release模式, 根据模式读取不同的Apollo配置
  42. var filePath string
  43. wr, _ := os.Getwd()
  44. if runtime.GOOS == "windows" {
  45. filePath = wr + "\\conf\\config.yml"
  46. } else {
  47. filePath = path.Join(path.Join(wr, "conf"), "config.yml")
  48. }
  49. var configData []byte
  50. configData, err = ioutil.ReadFile(filePath)
  51. if err != nil {
  52. fmt.Printf(" config file read failed: %s", err)
  53. return err
  54. }
  55. err = yaml.Unmarshal(configData, &ConfigInfo)
  56. if err != nil {
  57. fmt.Printf(" config parse failed: %s", err)
  58. return err
  59. }
  60. SetGinMode(ConfigInfo.Server.Mode)
  61. return err
  62. }
  63. func LoadApolloConfig() (*tools.ApolloConfig, error) {
  64. var err error
  65. // 连接Apollo
  66. err = tools.NewApollo()
  67. if err != nil {
  68. return nil, err
  69. }
  70. // 获取Apollo配置
  71. var config *tools.ApolloConfig
  72. config, err = tools.GetApolloConfig()
  73. if err != nil {
  74. return nil, err
  75. }
  76. // 按需加载应用配置信息
  77. loadAppConfig(tools.GetApollo().GetNameSpace("application"))
  78. return config, nil
  79. }
  80. func SetGinMode(mode string) {
  81. if mode == "debug" {
  82. gin.SetMode(gin.DebugMode)
  83. } else if mode == "release" {
  84. gin.SetMode(gin.ReleaseMode)
  85. }
  86. }
  87. func loadAppConfig(m map[string]interface{}) {
  88. if fileServ, ok := m["fileserv_url"]; ok {
  89. ConfigInfo.FileServUrl = fileServ.(string)
  90. }
  91. }