config.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. MaxRequest int `json:"max_request"`
  27. }
  28. var config *Configuration
  29. var once sync.Once
  30. // LoadConfig 加载配置
  31. func LoadConfig() *Configuration {
  32. once.Do(func() {
  33. // 从文件中读取
  34. config = &Configuration{}
  35. f, err := os.Open("config.json")
  36. if err != nil {
  37. logger.Danger(fmt.Errorf("open config err: %+v", err))
  38. return
  39. }
  40. defer f.Close()
  41. encoder := json.NewDecoder(f)
  42. err = encoder.Decode(config)
  43. if err != nil {
  44. logger.Warning(fmt.Errorf("decode config err: %v", err))
  45. return
  46. }
  47. // 如果环境变量有配置,读取环境变量
  48. apiKey := os.Getenv("APIKEY")
  49. baseURL := os.Getenv("BASE_URL")
  50. model := os.Getenv("MODEL")
  51. sessionTimeout := os.Getenv("SESSION_TIMEOUT")
  52. defaultMode := os.Getenv("DEFAULT_MODE")
  53. httpProxy := os.Getenv("HTTP_PROXY")
  54. maxRequest := os.Getenv("MAX_REQUEST")
  55. if apiKey != "" {
  56. config.ApiKey = apiKey
  57. }
  58. if baseURL != "" {
  59. config.BaseURL = baseURL
  60. }
  61. if sessionTimeout != "" {
  62. duration, err := strconv.ParseInt(sessionTimeout, 10, 64)
  63. if err != nil {
  64. logger.Danger(fmt.Sprintf("config session timeout err: %v ,get is %v", err, sessionTimeout))
  65. return
  66. }
  67. config.SessionTimeout = time.Duration(duration) * time.Second
  68. } else {
  69. config.SessionTimeout = time.Duration(config.SessionTimeout) * time.Second
  70. }
  71. if defaultMode != "" {
  72. config.DefaultMode = defaultMode
  73. }
  74. if httpProxy != "" {
  75. config.HttpProxy = httpProxy
  76. }
  77. if model != "" {
  78. config.Model = model
  79. }
  80. if maxRequest != "" {
  81. newMR, _ := strconv.Atoi(maxRequest)
  82. config.MaxRequest = newMR
  83. }
  84. })
  85. if config.Model == "" {
  86. config.DefaultMode = "gpt-3.5-turbo"
  87. }
  88. if config.DefaultMode == "" {
  89. config.DefaultMode = "单聊"
  90. }
  91. if config.ApiKey == "" {
  92. logger.Danger("config err: api key required")
  93. }
  94. return config
  95. }