config.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package config
  2. import (
  3. "encoding/json"
  4. "log"
  5. "os"
  6. "sync"
  7. "time"
  8. )
  9. // Configuration 项目配置
  10. type Configuration struct {
  11. // gtp apikey
  12. ApiKey string `json:"api_key"`
  13. // 会话超时时间
  14. SessionTimeout time.Duration `json:"session_timeout"`
  15. }
  16. var config *Configuration
  17. var once sync.Once
  18. // LoadConfig 加载配置
  19. func LoadConfig() *Configuration {
  20. once.Do(func() {
  21. // 从文件中读取
  22. config = &Configuration{
  23. SessionTimeout: 1,
  24. }
  25. f, err := os.Open("config.json")
  26. if err != nil {
  27. log.Fatalf("open config err: %v", err)
  28. return
  29. }
  30. defer f.Close()
  31. encoder := json.NewDecoder(f)
  32. err = encoder.Decode(config)
  33. if err != nil {
  34. log.Fatalf("decode config err: %v", err)
  35. return
  36. }
  37. // 如果环境变量有配置,读取环境变量
  38. ApiKey := os.Getenv("ApiKey")
  39. SessionTimeout := os.Getenv("SessionTimeout")
  40. if ApiKey != "" {
  41. config.ApiKey = ApiKey
  42. }
  43. if SessionTimeout != "" {
  44. duration, err := time.ParseDuration(SessionTimeout)
  45. if err != nil {
  46. log.Fatalf("config decode session timeout err: %v ,get is %v", err, SessionTimeout)
  47. return
  48. }
  49. config.SessionTimeout = duration
  50. }
  51. })
  52. return config
  53. }