config.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package g
  2. import (
  3. "fmt"
  4. "log"
  5. "sync"
  6. "github.com/toolkits/file"
  7. "gopkg.in/yaml.v2"
  8. )
  9. type GlobalConfig struct {
  10. Debug bool `yaml:"debug"`
  11. SmsEnabled bool `yaml:"smsEnabled"`
  12. Remain int `yaml:"remain"`
  13. Rpc *RpcConfig `yaml:"rpc"`
  14. Web *WebConfig `yaml:"web"`
  15. Worker *WorkerConfig `yaml:"worker"`
  16. Smtp *SmtpConfig `yaml:"smtp"`
  17. WeChat *WeChatConfig `yaml:"wechat"`
  18. }
  19. type MysqlConfig struct {
  20. Addr string `yaml:"addr"`
  21. Idle int `yaml:"idle"`
  22. Max int `yaml:"max"`
  23. }
  24. type RpcConfig struct {
  25. Listen string `yaml:"listen"`
  26. }
  27. type WebConfig struct {
  28. Addrs []string `yaml:"addrs"`
  29. Timeout int `yaml:"timeout"`
  30. Interval int `yaml:"interval"`
  31. }
  32. type WorkerConfig struct {
  33. Sms int `yaml:"sms"`
  34. Mail int `yaml:"mail"`
  35. WeChat int `yaml:"wechat"`
  36. }
  37. type SmtpConfig struct {
  38. Enabled bool `yaml:"enabled"`
  39. Addr string `yaml:"addr"`
  40. Username string `yaml:"username"`
  41. Password string `yaml:"password"`
  42. From string `yaml:"from"`
  43. Tls bool `yaml:"tls"`
  44. }
  45. type WeChatConfig struct {
  46. Enabled bool `yaml:"enabled"`
  47. ToParty string `yaml:"toparty"`
  48. AgentId int `yaml:agentid`
  49. CorpId string `yaml:corpid`
  50. CorpSecret string `yaml:corpsecret`
  51. }
  52. var (
  53. Config *GlobalConfig
  54. configLock = new(sync.RWMutex)
  55. )
  56. func Parse(cfg string) error {
  57. if cfg == "" {
  58. return fmt.Errorf("use -c to specify configuration file")
  59. }
  60. if !file.IsExist(cfg) {
  61. return fmt.Errorf("configuration file %s is not exists", cfg)
  62. }
  63. configContent, err := file.ToTrimString(cfg)
  64. if err != nil {
  65. return fmt.Errorf("read configuration file %s fail %s", cfg, err.Error())
  66. }
  67. var c GlobalConfig
  68. err = yaml.Unmarshal([]byte(configContent), &c)
  69. if err != nil {
  70. return fmt.Errorf("parse configuration file %s fail %s", cfg, err.Error())
  71. }
  72. configLock.Lock()
  73. defer configLock.Unlock()
  74. Config = &c
  75. if Config.Remain < 10 {
  76. Config.Remain = 30
  77. }
  78. log.Println("load configuration file", cfg, "successfully")
  79. return nil
  80. }