config.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package config
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "sync"
  8. "time"
  9. "github.com/eryajf/chatgpt-dingtalk/public/logger"
  10. )
  11. // Configuration 项目配置
  12. type Configuration struct {
  13. // gtp apikey
  14. ApiKey string `json:"api_key"`
  15. // 请求的 URL 地址
  16. BaseURL string `json:"base_url"`
  17. // 使用模型
  18. Model string `json:"model"`
  19. // 会话超时时间
  20. SessionTimeout time.Duration `json:"session_timeout"`
  21. // 默认对话模式
  22. DefaultMode string `json:"default_mode"`
  23. // 代理地址
  24. HttpProxy string `json:"http_proxy"`
  25. }
  26. var config *Configuration
  27. var once sync.Once
  28. // LoadConfig 加载配置
  29. func LoadConfig() *Configuration {
  30. once.Do(func() {
  31. // 从文件中读取
  32. config = &Configuration{}
  33. f, err := os.Open("config.json")
  34. if err != nil {
  35. logger.Danger(fmt.Errorf("open config err: %+v", err))
  36. return
  37. }
  38. defer f.Close()
  39. encoder := json.NewDecoder(f)
  40. err = encoder.Decode(config)
  41. if err != nil {
  42. logger.Warning(fmt.Errorf("decode config err: %v", err))
  43. return
  44. }
  45. // 如果环境变量有配置,读取环境变量
  46. apiKey := os.Getenv("APIKEY")
  47. baseURL := os.Getenv("BASE_URL")
  48. model := os.Getenv("MODEL")
  49. sessionTimeout := os.Getenv("SESSION_TIMEOUT")
  50. defaultMode := os.Getenv("DEFAULT_MODE")
  51. httpProxy := os.Getenv("HTTP_PROXY")
  52. if apiKey != "" {
  53. config.ApiKey = apiKey
  54. }
  55. if baseURL != "" {
  56. config.BaseURL = baseURL
  57. }
  58. if sessionTimeout != "" {
  59. duration, err := strconv.ParseInt(sessionTimeout, 10, 64)
  60. if err != nil {
  61. logger.Danger(fmt.Sprintf("config session timeout err: %v ,get is %v", err, sessionTimeout))
  62. return
  63. }
  64. config.SessionTimeout = time.Duration(duration) * time.Second
  65. } else {
  66. config.SessionTimeout = time.Duration(config.SessionTimeout) * time.Second
  67. }
  68. if defaultMode != "" {
  69. config.DefaultMode = defaultMode
  70. }
  71. if httpProxy != "" {
  72. config.HttpProxy = httpProxy
  73. }
  74. if model != "" {
  75. config.Model = model
  76. }
  77. })
  78. if config.Model == "" {
  79. config.DefaultMode = "gpt-3.5-turbo"
  80. }
  81. if config.DefaultMode == "" {
  82. config.DefaultMode = "单聊"
  83. }
  84. if config.ApiKey == "" {
  85. logger.Danger("config err: api key required")
  86. }
  87. return config
  88. }