example_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package paladin_test
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/library/conf/paladin"
  6. "github.com/naoina/toml"
  7. )
  8. type exampleConf struct {
  9. Bool bool
  10. Int int64
  11. Float float64
  12. String string
  13. Strings []string
  14. }
  15. func (e *exampleConf) Set(text string) error {
  16. var ec exampleConf
  17. if err := toml.Unmarshal([]byte(text), &ec); err != nil {
  18. return err
  19. }
  20. *e = ec
  21. return nil
  22. }
  23. // ExampleClient is a example client usage.
  24. // exmaple.toml:
  25. /*
  26. bool = true
  27. int = 100
  28. float = 100.1
  29. string = "text"
  30. strings = ["a", "b", "c"]
  31. */
  32. func ExampleClient() {
  33. if err := paladin.Init(); err != nil {
  34. panic(err)
  35. }
  36. var ec exampleConf
  37. // var setter
  38. if err := paladin.Watch("example.toml", &ec); err != nil {
  39. panic(err)
  40. }
  41. if err := paladin.Get("example.toml").UnmarshalTOML(&ec); err != nil {
  42. panic(err)
  43. }
  44. // use exampleConf
  45. // watch event key
  46. go func() {
  47. for event := range paladin.WatchEvent(context.TODO(), "key") {
  48. fmt.Println(event)
  49. }
  50. }()
  51. }
  52. // ExampleMap is a example map usage.
  53. // exmaple.toml:
  54. /*
  55. bool = true
  56. int = 100
  57. float = 100.1
  58. string = "text"
  59. strings = ["a", "b", "c"]
  60. [object]
  61. string = "text"
  62. bool = true
  63. int = 100
  64. float = 100.1
  65. strings = ["a", "b", "c"]
  66. */
  67. func ExampleMap() {
  68. var (
  69. m paladin.TOML
  70. strs []string
  71. )
  72. // paladin toml
  73. if err := paladin.Watch("example.toml", &m); err != nil {
  74. panic(err)
  75. }
  76. // value string
  77. s, err := m.Get("string").String()
  78. if err != nil {
  79. s = "default"
  80. }
  81. fmt.Println(s)
  82. // value bool
  83. b, err := m.Get("bool").Bool()
  84. if err != nil {
  85. b = false
  86. }
  87. fmt.Println(b)
  88. // value int
  89. i, err := m.Get("int").Int64()
  90. if err != nil {
  91. i = 100
  92. }
  93. fmt.Println(i)
  94. // value float
  95. f, err := m.Get("float").Float64()
  96. if err != nil {
  97. f = 100.1
  98. }
  99. fmt.Println(f)
  100. // value slice
  101. if err = m.Get("strings").Slice(&strs); err == nil {
  102. fmt.Println(strs)
  103. }
  104. }