config.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package config
  2. import (
  3. "errors"
  4. "io/ioutil"
  5. "os"
  6. "strings"
  7. "github.com/ghodss/yaml"
  8. "github.com/zu1k/proxypool/pkg/tool"
  9. )
  10. var configFilePath = "config.yaml"
  11. type ConfigOptions struct {
  12. Domain string `json:"domain" yaml:"domain"`
  13. CFEmail string `json:"cf_email" yaml:"cf_email"`
  14. CFKey string `json:"cf_key" yaml:"cf_key"`
  15. SourceFiles []string `json:"source-files" yaml:"source-files"`
  16. }
  17. // Config 配置
  18. var Config ConfigOptions
  19. // Parse 解析配置文件,支持本地文件系统和网络链接
  20. func Parse(path string) error {
  21. if path == "" {
  22. path = configFilePath
  23. } else {
  24. configFilePath = path
  25. }
  26. fileData, err := ReadFile(path)
  27. if err != nil {
  28. return err
  29. }
  30. Config = ConfigOptions{}
  31. err = yaml.Unmarshal(fileData, &Config)
  32. if err != nil {
  33. return err
  34. }
  35. // 部分配置环境变量优先
  36. if domain := os.Getenv("DOMAIN"); domain != "" {
  37. Config.Domain = domain
  38. }
  39. if cfEmail := os.Getenv("CF_API_EMAIL"); cfEmail != "" {
  40. Config.CFEmail = cfEmail
  41. }
  42. if cfKey := os.Getenv("CF_API_KEY"); cfKey != "" {
  43. Config.CFKey = cfKey
  44. }
  45. return nil
  46. }
  47. // 从本地文件或者http链接读取配置文件内容
  48. func ReadFile(path string) ([]byte, error) {
  49. if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
  50. resp, err := tool.GetHttpClient().Get(path)
  51. if err != nil {
  52. return nil, errors.New("config file http get fail")
  53. }
  54. defer resp.Body.Close()
  55. return ioutil.ReadAll(resp.Body)
  56. } else {
  57. if _, err := os.Stat(path); os.IsNotExist(err) {
  58. return nil, err
  59. }
  60. return ioutil.ReadFile(path)
  61. }
  62. }