123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package config
- import (
- "encoding/json"
- "fmt"
- "os"
- "strconv"
- "sync"
- "time"
- "github.com/eryajf/chatgpt-dingtalk/public/logger"
- )
- type Configuration struct {
-
- ApiKey string `json:"api_key"`
-
- Model string `json:"model"`
-
- SessionTimeout time.Duration `json:"session_timeout"`
-
- DefaultMode string `json:"default_mode"`
-
- HttpProxy string `json:"http_proxy"`
- }
- var config *Configuration
- var once sync.Once
- func LoadConfig() *Configuration {
- once.Do(func() {
-
- config = &Configuration{}
- f, err := os.Open("config.json")
- if err != nil {
- logger.Danger(fmt.Errorf("open config err: %+v", err))
- return
- }
- defer f.Close()
- encoder := json.NewDecoder(f)
- err = encoder.Decode(config)
- if err != nil {
- logger.Warning(fmt.Errorf("decode config err: %v", err))
- return
- }
-
- ApiKey := os.Getenv("APIKEY")
- model := os.Getenv("MODEL")
- SessionTimeout := os.Getenv("SESSION_TIMEOUT")
- defaultMode := os.Getenv("DEFAULT_MODE")
- httpProxy := os.Getenv("HTTP_PROXY")
- if ApiKey != "" {
- config.ApiKey = ApiKey
- }
- if SessionTimeout != "" {
- duration, err := strconv.ParseInt(SessionTimeout, 10, 64)
- if err != nil {
- logger.Danger(fmt.Sprintf("config session timeout err: %v ,get is %v", err, SessionTimeout))
- return
- }
- config.SessionTimeout = time.Duration(duration) * time.Second
- } else {
- config.SessionTimeout = time.Duration(config.SessionTimeout) * time.Second
- }
- if defaultMode != "" {
- config.DefaultMode = defaultMode
- }
- if httpProxy != "" {
- config.HttpProxy = httpProxy
- }
- if model != "" {
- config.Model = model
- }
- })
- if config.DefaultMode == "" {
- config.DefaultMode = "单聊"
- }
- if config.ApiKey == "" {
- logger.Danger("config err: api key required")
- }
- return config
- }
|