You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.1 KiB

11 years ago
10 years ago
11 years ago
10 years ago
  1. package config
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. type Config interface {
  7. Get(key string) interface{}
  8. GetBool(key string) bool
  9. GetFloat64(key string) float64
  10. GetInt(key string) int
  11. GetString(key string) string
  12. GetStringMap(key string) map[string]interface{}
  13. GetStringMapString(key string) map[string]string
  14. GetStringSlice(key string) []string
  15. GetTime(key string) time.Time
  16. IsSet(key string) bool
  17. Set(key string, value interface{})
  18. }
  19. type MapConfig map[string]interface{}
  20. func (cfg MapConfig) Get(key string) interface{} { return cfg[key] }
  21. func (cfg MapConfig) GetBool(key string) bool { return cfg[key].(bool) }
  22. func (cfg MapConfig) GetFloat64(key string) float64 { return cfg[key].(float64) }
  23. func (cfg MapConfig) GetInt(key string) int { return cfg[key].(int) }
  24. func (cfg MapConfig) GetString(key string) string { return cfg[key].(string) }
  25. func (cfg MapConfig) GetStringMap(key string) map[string]interface{} {
  26. return cfg[key].(map[string]interface{})
  27. }
  28. func (cfg MapConfig) GetStringMapString(key string) map[string]string {
  29. return cfg[key].(map[string]string)
  30. }
  31. func (cfg MapConfig) GetStringSlice(key string) []string { return cfg[key].([]string) }
  32. func (cfg MapConfig) GetTime(key string) time.Time { return cfg[key].(time.Time) }
  33. func (cfg MapConfig) IsSet(key string) bool { _, ok := cfg[key]; return ok }
  34. func (cfg MapConfig) Set(key string, value interface{}) { cfg[key] = value }
  35. func (cfg MapConfig) SetDefault(key string, value interface{}) {
  36. if cfg.IsSet(key) {
  37. return
  38. }
  39. cfg[key] = value
  40. }
  41. //--------------------------------------------------------------------------------
  42. // A little convenient hack to notify listeners upon config changes.
  43. type Configurable func(Config)
  44. var mtx sync.Mutex
  45. var globalConfig Config
  46. var confs []Configurable
  47. func OnConfig(conf func(Config)) {
  48. mtx.Lock()
  49. defer mtx.Unlock()
  50. confs = append(confs, conf)
  51. if globalConfig != nil {
  52. conf(globalConfig)
  53. }
  54. }
  55. func ApplyConfig(config Config) {
  56. mtx.Lock()
  57. globalConfig = config
  58. confsCopy := make([]Configurable, len(confs))
  59. copy(confsCopy, confs)
  60. mtx.Unlock()
  61. for _, conf := range confsCopy {
  62. conf(config)
  63. }
  64. }