config.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. // 会话超时时间
  16. SessionTimeout time.Duration `json:"session_timeout"`
  17. // 默认对话模式
  18. DefaultMode string `json:"default_mode"`
  19. }
  20. var config *Configuration
  21. var once sync.Once
  22. // LoadConfig 加载配置
  23. func LoadConfig() *Configuration {
  24. once.Do(func() {
  25. // 从文件中读取
  26. config = &Configuration{}
  27. f, err := os.Open("config.json")
  28. if err != nil {
  29. logger.Danger(fmt.Errorf("open config err: %+v", err))
  30. return
  31. }
  32. defer f.Close()
  33. encoder := json.NewDecoder(f)
  34. err = encoder.Decode(config)
  35. if err != nil {
  36. logger.Warning(fmt.Errorf("decode config err: %v", err))
  37. return
  38. }
  39. // 如果环境变量有配置,读取环境变量
  40. ApiKey := os.Getenv("APIKEY")
  41. SessionTimeout := os.Getenv("SESSION_TIMEOUT")
  42. defaultMode := os.Getenv("DEFAULT_MODE")
  43. // Model := os.Getenv("MODEL")
  44. // MaxTokens := os.Getenv("MAX_TOKENS")
  45. // Temperature := os.Getenv("TEMPREATURE")
  46. // SessionClearToken := os.Getenv("SESSION_CLEAR_TOKEN")
  47. if ApiKey != "" {
  48. config.ApiKey = ApiKey
  49. }
  50. if SessionTimeout != "" {
  51. duration, err := strconv.ParseInt(SessionTimeout, 10, 64)
  52. if err != nil {
  53. logger.Danger(fmt.Sprintf("config session timeout err: %v ,get is %v", err, SessionTimeout))
  54. return
  55. }
  56. config.SessionTimeout = time.Duration(duration) * time.Second
  57. } else {
  58. config.SessionTimeout = time.Duration(config.SessionTimeout) * time.Second
  59. }
  60. if defaultMode != "" {
  61. config.DefaultMode = defaultMode
  62. }
  63. })
  64. if config.DefaultMode == "" {
  65. config.DefaultMode = "单聊"
  66. }
  67. if config.ApiKey == "" {
  68. logger.Danger("config err: api key required")
  69. }
  70. return config
  71. }