config.go 1.6 KB

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