简单地读取不同环境的配置, 目前仅限于YAML
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.

106 lines
1.9 KiB

  1. package grconfig
  2. import (
  3. "bytes"
  4. "os"
  5. "path"
  6. "reflect"
  7. "strconv"
  8. "strings"
  9. )
  10. type ConfigerChannelInterface interface {
  11. Item(item string, t interface{}) (err error)
  12. String(item string) string
  13. }
  14. type Configer struct {
  15. channels map[string]ConfigerChannelInterface
  16. root string
  17. }
  18. func New(root string) *Configer {
  19. return &Configer{root: root, channels: map[string]ConfigerChannelInterface{}}
  20. }
  21. func (conf *Configer) getData(item string) (ch ConfigerChannelInterface, err error) {
  22. var ok bool
  23. env := os.Getenv("CENTER_RUNMODE")
  24. chunks := strings.SplitN(item, ".", 2)
  25. if len(chunks) < 1 {
  26. panic("Item string error chunk len must more than 1")
  27. }
  28. if strings.TrimSpace(env) == "" {
  29. env = ""
  30. }
  31. if ch, ok = conf.channels[chunks[0]]; !ok {
  32. var fd *os.File
  33. var buf bytes.Buffer
  34. // @TODO 检查配置
  35. fpath := path.Join(conf.root, env, chunks[0]+"."+"yaml")
  36. if fd, err = os.Open(fpath); err != nil {
  37. return nil, err
  38. }
  39. if _, err = buf.ReadFrom(fd); err != nil {
  40. return nil, err
  41. }
  42. // @TODO
  43. ch = &ConfigerChannelYAML{
  44. tmp: parseYAML(buf),
  45. filename: chunks[0],
  46. }
  47. conf.channels[chunks[0]] = ch
  48. }
  49. return
  50. }
  51. func (conf *Configer) Item(item string, t interface{}) (err error) {
  52. ch, err1 := conf.getData(item)
  53. if err1 != nil {
  54. return err1
  55. }
  56. return ch.Item(item, t)
  57. }
  58. func (conf *Configer) String(item string) string {
  59. ch, err1 := conf.getData(item)
  60. if err1 != nil {
  61. return ""
  62. }
  63. return ch.String(item)
  64. }
  65. func recursiveParse(item string, v interface{}) interface{} {
  66. if item == "" {
  67. return v
  68. }
  69. chunks := strings.SplitN(item, ".", 2)
  70. if n, err := strconv.Atoi(chunks[0]); err == nil {
  71. if tmp, ok := v.([]interface{}); reflect.TypeOf(v).Kind() == reflect.Slice && ok {
  72. v = tmp[n]
  73. }
  74. } else {
  75. if tmp, ok := v.(map[interface{}]interface{}); reflect.TypeOf(v).Kind() == reflect.Map && ok {
  76. v = tmp[chunks[0]]
  77. }
  78. }
  79. if len(chunks) <= 1 {
  80. return v
  81. }
  82. return recursiveParse(chunks[1], v)
  83. }