config.go 1.9 KB

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