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

62 lines
1.1 KiB

  1. package grconfig
  2. import (
  3. "bytes"
  4. "errors"
  5. "gopkg.in/yaml.v2"
  6. "log"
  7. "strings"
  8. )
  9. type ConfigerChannelYAML struct {
  10. tmp interface{}
  11. filename string
  12. adapter string
  13. }
  14. func (conf *ConfigerChannelYAML) String(item string) string {
  15. chunks := strings.SplitN(item, ".", 2)
  16. var target interface{}
  17. if len(chunks) > 1 {
  18. target = recursiveParse(chunks[1], conf.tmp)
  19. } else {
  20. target = conf.tmp
  21. }
  22. if str, ok := target.(string); ok {
  23. return str
  24. } else {
  25. if out, err := yaml.Marshal(target); err == nil {
  26. return bytes.NewBuffer(out).String()
  27. }
  28. }
  29. return ""
  30. }
  31. func (conf *ConfigerChannelYAML) Item(item string, t interface{}) (err error) {
  32. chunks := strings.SplitN(item, ".", 2)
  33. if len(chunks) == 1 {
  34. chunks = append(chunks, "")
  35. }
  36. target := recursiveParse(chunks[1], conf.tmp)
  37. if target == nil {
  38. err = errors.New("item doesn't exists")
  39. return
  40. }
  41. out, _ := yaml.Marshal(target)
  42. err = yaml.Unmarshal(out, t)
  43. return
  44. }
  45. func parseYAML(buf bytes.Buffer) interface{} {
  46. var v interface{}
  47. if err := yaml.Unmarshal(buf.Bytes(), &v); err != nil {
  48. log.Println(err)
  49. panic(err)
  50. }
  51. return v
  52. }