source.go 1.7 KB

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