config.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package config
  2. import (
  3. "JsRpc/utils"
  4. "errors"
  5. "flag"
  6. log "github.com/sirupsen/logrus"
  7. "gopkg.in/yaml.v3"
  8. "os"
  9. )
  10. var DefaultTimeout = 30
  11. func ReadConf() ConfStruct {
  12. var ConfigPath string
  13. // 定义命令行参数-c,后面跟着的是默认值以及参数说明
  14. flag.StringVar(&ConfigPath, "c", "config.yaml", "指定配置文件的路径")
  15. // 解析命令行参数
  16. flag.Parse()
  17. conf, err := initConf(ConfigPath)
  18. if err != nil {
  19. log.Errorln("读取配置文件错误,将使用默认配置运行。 ", err.Error())
  20. }
  21. return conf
  22. }
  23. func initConf(path string) (ConfStruct, error) {
  24. defaultConf := ConfStruct{
  25. BasicListen: `:12080`,
  26. HttpsServices: HttpsConfig{
  27. IsEnable: false,
  28. HttpsListen: `:12443`,
  29. },
  30. DefaultTimeOut: DefaultTimeout,
  31. }
  32. if !utils.IsExists(path) {
  33. return defaultConf, errors.New("config path not found")
  34. }
  35. file, _ := os.Open(path) // 因为上面已经判断了 文件是存在的 所以这里不用捕获错误
  36. defer func(file *os.File) {
  37. err := file.Close()
  38. if err != nil {
  39. }
  40. }(file)
  41. conf := ConfStruct{}
  42. decoder := yaml.NewDecoder(file)
  43. err := decoder.Decode(&conf)
  44. if err != nil {
  45. return defaultConf, err
  46. }
  47. return conf, nil
  48. }
  49. type ConfStruct struct {
  50. BasicListen string `yaml:"BasicListen"`
  51. HttpsServices HttpsConfig `yaml:"HttpsServices"`
  52. DefaultTimeOut int `yaml:"DefaultTimeOut"`
  53. CloseLog bool `yaml:"CloseLog"`
  54. CloseWebLog bool `yaml:"CloseWebLog"`
  55. Mode string `yaml:"Mode"`
  56. Cors bool `yaml:"Cors"`
  57. }
  58. // HttpsConfig 代表HTTPS相关配置的结构体
  59. type HttpsConfig struct {
  60. IsEnable bool `yaml:"IsEnable"`
  61. HttpsListen string `yaml:"HttpsListen"`
  62. PemPath string `yaml:"PemPath"`
  63. KeyPath string `yaml:"KeyPath"`
  64. }