source.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package config
  2. import (
  3. "fmt"
  4. "github.com/go-kratos/kratos/v2/config"
  5. "github.com/go-kratos/kratos/v2/config/file"
  6. clientv3 "go.etcd.io/etcd/client/v3"
  7. )
  8. type Source interface {
  9. NewSource() (config.Source, error)
  10. Validate() bool
  11. String() string
  12. }
  13. type Format string
  14. const (
  15. Yaml Format = "yaml"
  16. )
  17. var formatMap = map[Format]string{
  18. Yaml: "yaml",
  19. }
  20. func (f Format) String() string {
  21. return string(f)
  22. }
  23. func (f Format) Validate() bool {
  24. _, ok := formatMap[f]
  25. return ok
  26. }
  27. // =======================================
  28. type EtcdSource struct {
  29. Format Format
  30. Client *clientv3.Client
  31. Namespace string
  32. Name string
  33. }
  34. func (s *EtcdSource) NewSource() (config.Source, error) {
  35. source, err := New(s.Client, WithPath(fmt.Sprintf("/%s/config/%s", s.Namespace, s.Name)))
  36. if err != nil {
  37. return nil, err
  38. }
  39. return source, nil
  40. }
  41. func (s *EtcdSource) Validate() bool {
  42. if !s.Format.Validate() {
  43. return false
  44. }
  45. if s.Client == nil {
  46. return false
  47. }
  48. if s.Namespace == "" {
  49. return false
  50. }
  51. if s.Name == "" {
  52. return false
  53. }
  54. return true
  55. }
  56. func (s *EtcdSource) String() string {
  57. return fmt.Sprintf("etcd source format:%v, namespace:%v, name:%v", s.Format, s.Namespace, s.Name)
  58. }
  59. // =======================================
  60. type FileSource struct {
  61. Format Format
  62. Path string
  63. }
  64. func (s *FileSource) NewSource() (config.Source, error) {
  65. source := file.NewSource(s.Path)
  66. return source, nil
  67. }
  68. func (s *FileSource) Validate() bool {
  69. if !s.Format.Validate() {
  70. return false
  71. }
  72. if s.Path == "" {
  73. return false
  74. }
  75. return true
  76. }
  77. func (s *FileSource) String() string {
  78. return fmt.Sprintf("file source format:%v, path:%v", s.Format, s.Path)
  79. }