config.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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.Warning(
  20. "使用默认配置运行 ", err.Error(),
  21. " 配置参考 https://github.com/jxhczhl/JsRpc/blob/main/config.yaml")
  22. }
  23. return conf
  24. }
  25. func initConf(path string) (ConfStruct, error) {
  26. defaultConf := ConfStruct{
  27. BasicListen: `:12080`,
  28. HttpsServices: HttpsConfig{
  29. IsEnable: false,
  30. HttpsListen: `:12443`,
  31. },
  32. DefaultTimeOut: DefaultTimeout,
  33. RouterReplace: RouterReplace{
  34. IsEnable: false,
  35. ReplaceRoute: "",
  36. },
  37. }
  38. if !utils.IsExists(path) {
  39. return defaultConf, errors.New("config path not found")
  40. }
  41. file, _ := os.Open(path) // 因为上面已经判断了 文件是存在的 所以这里不用捕获错误
  42. defer func(file *os.File) {
  43. err := file.Close()
  44. if err != nil {
  45. }
  46. }(file)
  47. conf := ConfStruct{}
  48. decoder := yaml.NewDecoder(file)
  49. err := decoder.Decode(&conf)
  50. if err != nil {
  51. return defaultConf, err
  52. }
  53. DefaultTimeout = conf.DefaultTimeOut
  54. return conf, nil
  55. }
  56. type ConfStruct struct {
  57. BasicListen string `yaml:"BasicListen"`
  58. HttpsServices HttpsConfig `yaml:"HttpsServices"`
  59. DefaultTimeOut int `yaml:"DefaultTimeOut"`
  60. CloseLog bool `yaml:"CloseLog"`
  61. CloseWebLog bool `yaml:"CloseWebLog"`
  62. Mode string `yaml:"Mode"`
  63. Cors bool `yaml:"Cors"`
  64. RouterReplace RouterReplace `yaml:"RouterReplace"`
  65. }
  66. // HttpsConfig 代表HTTPS相关配置的结构体
  67. type HttpsConfig struct {
  68. IsEnable bool `yaml:"IsEnable"`
  69. HttpsListen string `yaml:"HttpsListen"`
  70. PemPath string `yaml:"PemPath"`
  71. KeyPath string `yaml:"KeyPath"`
  72. }
  73. type RouterReplace struct {
  74. IsEnable bool `yaml:"IsEnable"`
  75. ReplaceRoute string `yaml:"ReplaceRoute"`
  76. }