@@ -5,20 +5,24 @@ import (
55 "github.com/apolloconfig/agollo/v4"
66 "github.com/apolloconfig/agollo/v4/component/log"
77 "github.com/apolloconfig/agollo/v4/env/config"
8+ "github.com/apolloconfig/agollo/v4/storage"
89 "github.com/pkg/errors"
910)
1011
1112var (
1213 ErrEmptyKey = errors .New ("property key is empty" )
1314 ErrMissConfig = errors .New ("miss config" )
15+ ErrConfigNil = errors .New ("cant find a config by the special namespace" )
1416)
1517
18+ const defaultNamespace = "application"
19+
1620type Option func (o * options )
1721
1822type options struct {
19- handlers []datasource.PropertyHandler
20- logger log.LoggerInterface
21- client * agollo. Client
23+ handlers []datasource.PropertyHandler
24+ logger log.LoggerInterface
25+ namespace string
2226}
2327
2428// WithPropertyHandlers set property handlers
@@ -35,11 +39,25 @@ func WithLogger(logger log.LoggerInterface) Option {
3539 }
3640}
3741
42+ // WithNamespace set apollo namespace to supports fetching rules from specified namespace.
43+ func WithNamespace (namespace string ) Option {
44+ return func (o * options ) {
45+ o .namespace = namespace
46+ }
47+ }
48+
3849// apolloDatasource implements datasource.Datasource
3950type apolloDatasource struct {
4051 datasource.Base
41- client * agollo. Client
52+ client apolloClient
4253 propertyKey string
54+ namespace string
55+ }
56+
57+ // apolloClient a simple apollo client to support sentinel datasource
58+ type apolloClient interface {
59+ GetConfig (namespace string ) * storage.Config
60+ AddChangeListener (listener storage.ChangeListener )
4361}
4462
4563// NewDatasource create apollo datasource
@@ -56,6 +74,9 @@ func NewDatasource(conf *config.AppConfig, propertyKey string, opts ...Option) (
5674 for _ , opt := range opts {
5775 opt (option )
5876 }
77+ if option .namespace == "" {
78+ option .namespace = defaultNamespace
79+ }
5980 agollo .SetLogger (option .logger )
6081 apolloClient , err := agollo .StartWithConfig (func () (* config.AppConfig , error ) {
6182 return conf , nil
@@ -66,6 +87,7 @@ func NewDatasource(conf *config.AppConfig, propertyKey string, opts ...Option) (
6687 ds := & apolloDatasource {
6788 client : apolloClient ,
6889 propertyKey : propertyKey ,
90+ namespace : option .namespace ,
6991 }
7092 for _ , handler := range option .handlers {
7193 ds .AddPropertyHandler (handler )
@@ -74,7 +96,11 @@ func NewDatasource(conf *config.AppConfig, propertyKey string, opts ...Option) (
7496}
7597
7698func (a * apolloDatasource ) ReadSource () ([]byte , error ) {
77- value := a .client .GetValue (a .propertyKey )
99+ cfg := a .client .GetConfig (a .namespace )
100+ if cfg == nil {
101+ return nil , ErrConfigNil
102+ }
103+ value := cfg .GetValue (a .propertyKey )
78104 return []byte (value ), nil
79105}
80106
0 commit comments