config.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package config
  2. import (
  3. "bufio"
  4. "io"
  5. "os"
  6. "reflect"
  7. "strconv"
  8. "strings"
  9. "github.com/runningwater/go-redis/lib/logger"
  10. )
  11. // ServerProperties defines global config properties
  12. type ServerProperties struct {
  13. Bind string `cfg:"bind"`
  14. Port int `cfg:"port"`
  15. AppendOnly bool `cfg:"appendOnly"`
  16. AppendFilename string `cfg:"appendFilename"`
  17. MaxClients int `cfg:"maxclients"`
  18. RequirePass string `cfg:"requirepass"`
  19. Databases int `cfg:"databases"`
  20. Peers []string `cfg:"peers"`
  21. Self string `cfg:"self"`
  22. }
  23. // Properties holds global config properties
  24. var Properties *ServerProperties
  25. func init() {
  26. // default config
  27. Properties = &ServerProperties{
  28. Bind: "127.0.0.1",
  29. Port: 6379,
  30. AppendOnly: false,
  31. }
  32. }
  33. func parse(src io.Reader) *ServerProperties {
  34. config := &ServerProperties{}
  35. // read config file
  36. rawMap := make(map[string]string)
  37. scanner := bufio.NewScanner(src)
  38. for scanner.Scan() {
  39. line := scanner.Text()
  40. if len(line) > 0 && line[0] == '#' {
  41. continue
  42. }
  43. pivot := strings.IndexAny(line, " ")
  44. if pivot > 0 && pivot < len(line)-1 { // separator found
  45. key := line[0:pivot]
  46. value := strings.Trim(line[pivot+1:], " ")
  47. rawMap[strings.ToLower(key)] = value
  48. }
  49. }
  50. if err := scanner.Err(); err != nil {
  51. logger.Fatal(err)
  52. }
  53. // parse format
  54. t := reflect.TypeOf(config)
  55. v := reflect.ValueOf(config)
  56. n := t.Elem().NumField()
  57. for i := 0; i < n; i++ {
  58. field := t.Elem().Field(i)
  59. fieldVal := v.Elem().Field(i)
  60. key, ok := field.Tag.Lookup("cfg")
  61. if !ok {
  62. key = field.Name
  63. }
  64. value, ok := rawMap[strings.ToLower(key)]
  65. if ok {
  66. // fill config
  67. switch field.Type.Kind() {
  68. case reflect.String:
  69. fieldVal.SetString(value)
  70. case reflect.Int:
  71. intValue, err := strconv.ParseInt(value, 10, 64)
  72. if err == nil {
  73. fieldVal.SetInt(intValue)
  74. }
  75. case reflect.Bool:
  76. boolValue := "yes" == value
  77. fieldVal.SetBool(boolValue)
  78. case reflect.Slice:
  79. if field.Type.Elem().Kind() == reflect.String {
  80. slice := strings.Split(value, ",")
  81. fieldVal.Set(reflect.ValueOf(slice))
  82. }
  83. }
  84. }
  85. }
  86. return config
  87. }
  88. // SetupConfig read config file and store properties into Properties
  89. func SetupConfig(configFilename string) {
  90. file, err := os.Open(configFilename)
  91. if err != nil {
  92. panic(err)
  93. }
  94. defer file.Close()
  95. Properties = parse(file)
  96. }