Merge branch 'develop'
diff --git a/README.md b/README.md
index d4f6cab..d1354fd 100644
--- a/README.md
+++ b/README.md
@@ -236,6 +236,16 @@
<img width="222px" src="https://i.gsxcdn.com/0cms/d/file/content/2020/02/5e572137d7d94.png">
</a>
</td>
+ <td align="center" valign="middle">
+ <a href="http://www.51h5.com" target="_blank">
+ <img width="222px" src="https://fs-ews.51h5.com/common/hw_220_black.png">
+ </a>
+ </td>
+ <td align="center" valign="middle">
+ <a href="https://www.zto.com" target="_blank">
+ <img width="222px" src="https://fscdn.zto.com/fs8/M02/B2/E4/wKhBD1-8o52Ae3GnAAASU3r62ME040.png">
+ </a>
+ </td>
</tr>
<tr></tr>
</tbody>
diff --git a/README_CN.md b/README_CN.md
index fc9eec8..4645fb2 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -234,6 +234,16 @@
<img width="222px" src="https://i.gsxcdn.com/0cms/d/file/content/2020/02/5e572137d7d94.png">
</a>
</td>
+ <td align="center" valign="middle">
+ <a href="http://www.51h5.com" target="_blank">
+ <img width="222px" src="https://fs-ews.51h5.com/common/hw_220_black.png">
+ </a>
+ </td>
+ <td align="center" valign="middle">
+ <a href="https://www.zto.com" target="_blank">
+ <img width="222px" src="https://fscdn.zto.com/fs8/M02/B2/E4/wKhBD1-8o52Ae3GnAAASU3r62ME040.png">
+ </a>
+ </td>
</tr>
<tr></tr>
</tbody>
diff --git a/cluster/cluster_impl/base_cluster_invoker.go b/cluster/cluster_impl/base_cluster_invoker.go
index 0ac851f..ed30559 100644
--- a/cluster/cluster_impl/base_cluster_invoker.go
+++ b/cluster/cluster_impl/base_cluster_invoker.go
@@ -51,7 +51,7 @@
}
}
-func (invoker *baseClusterInvoker) GetUrl() common.URL {
+func (invoker *baseClusterInvoker) GetUrl() *common.URL {
return invoker.directory.GetUrl()
}
diff --git a/cluster/cluster_impl/failover_cluster_test.go b/cluster/cluster_impl/failover_cluster_test.go
index d3ac2c8..3ea6232 100644
--- a/cluster/cluster_impl/failover_cluster_test.go
+++ b/cluster/cluster_impl/failover_cluster_test.go
@@ -45,7 +45,7 @@
// nolint
type MockInvoker struct {
- url common.URL
+ url *common.URL
available bool
destroyed bool
@@ -53,7 +53,7 @@
}
// nolint
-func NewMockInvoker(url common.URL, successCount int) *MockInvoker {
+func NewMockInvoker(url *common.URL, successCount int) *MockInvoker {
return &MockInvoker{
url: url,
available: true,
@@ -63,7 +63,7 @@
}
// nolint
-func (bi *MockInvoker) GetUrl() common.URL {
+func (bi *MockInvoker) GetUrl() *common.URL {
return bi.url
}
diff --git a/cluster/directory/base_directory.go b/cluster/directory/base_directory.go
index 20db1f2..d1025a1 100644
--- a/cluster/directory/base_directory.go
+++ b/cluster/directory/base_directory.go
@@ -65,8 +65,8 @@
}
// GetUrl Get URL
-func (dir *BaseDirectory) GetUrl() common.URL {
- return *dir.url
+func (dir *BaseDirectory) GetUrl() *common.URL {
+ return dir.url
}
// GetDirectoryUrl Get URL instance
diff --git a/cluster/directory/base_directory_test.go b/cluster/directory/base_directory_test.go
index e51e533..16e3c5a 100644
--- a/cluster/directory/base_directory_test.go
+++ b/cluster/directory/base_directory_test.go
@@ -40,19 +40,16 @@
)
func TestNewBaseDirectory(t *testing.T) {
- directory := NewBaseDirectory(&url)
- assert.NotNil(t, directory)
- assert.Equal(t, url, directory.GetUrl())
- assert.Equal(t, &url, directory.GetDirectoryUrl())
+ dir := NewBaseDirectory(url)
+ assert.Equal(t, url, dir.GetUrl())
+ assert.Equal(t, url, dir.GetDirectoryUrl())
}
func TestBuildRouterChain(t *testing.T) {
regURL := url
regURL.AddParam(constant.INTERFACE_KEY, "mock-app")
- directory := NewBaseDirectory(®URL)
-
- assert.NotNil(t, directory)
+ directory := NewBaseDirectory(regURL)
localIP := common.GetLocalIp()
rule := base64.URLEncoding.EncodeToString([]byte("true => " + " host = " + localIP))
@@ -66,18 +63,18 @@
assert.NotNil(t, chain)
}
-func getRouteURL(rule string, u common.URL) *common.URL {
+func getRouteURL(rule string, u *common.URL) *common.URL {
ru := u
ru.AddParam("rule", rule)
ru.AddParam("force", "true")
ru.AddParam(constant.ROUTER_KEY, "router")
- return &ru
+ return ru
}
func TestIsProperRouter(t *testing.T) {
regURL := url
regURL.AddParam(constant.APPLICATION_KEY, "mock-app")
- d := NewBaseDirectory(®URL)
+ d := NewBaseDirectory(regURL)
localIP := common.GetLocalIp()
rule := base64.URLEncoding.EncodeToString([]byte("true => " + " host = " + localIP))
routeURL := getRouteURL(rule, anyURL)
@@ -87,7 +84,7 @@
regURL.AddParam(constant.APPLICATION_KEY, "")
regURL.AddParam(constant.INTERFACE_KEY, "com.foo.BarService")
- d = NewBaseDirectory(®URL)
+ d = NewBaseDirectory(regURL)
routeURL = getRouteURL(rule, anyURL)
routeURL.AddParam(constant.INTERFACE_KEY, "com.foo.BarService")
rst = d.isProperRouter(routeURL)
@@ -95,14 +92,14 @@
regURL.AddParam(constant.APPLICATION_KEY, "")
regURL.AddParam(constant.INTERFACE_KEY, "")
- d = NewBaseDirectory(®URL)
+ d = NewBaseDirectory(regURL)
routeURL = getRouteURL(rule, anyURL)
rst = d.isProperRouter(routeURL)
assert.True(t, rst)
regURL.SetParam(constant.APPLICATION_KEY, "")
regURL.SetParam(constant.INTERFACE_KEY, "")
- d = NewBaseDirectory(®URL)
+ d = NewBaseDirectory(regURL)
routeURL = getRouteURL(rule, anyURL)
routeURL.AddParam(constant.APPLICATION_KEY, "mock-service")
rst = d.isProperRouter(routeURL)
@@ -110,7 +107,7 @@
regURL.SetParam(constant.APPLICATION_KEY, "")
regURL.SetParam(constant.INTERFACE_KEY, "")
- d = NewBaseDirectory(®URL)
+ d = NewBaseDirectory(regURL)
routeURL = getRouteURL(rule, anyURL)
routeURL.AddParam(constant.INTERFACE_KEY, "mock-service")
rst = d.isProperRouter(routeURL)
diff --git a/cluster/directory/static_directory.go b/cluster/directory/static_directory.go
index 6d75dff..d9695d4 100644
--- a/cluster/directory/static_directory.go
+++ b/cluster/directory/static_directory.go
@@ -34,13 +34,13 @@
// NewStaticDirectory Create a new staticDirectory with invokers
func NewStaticDirectory(invokers []protocol.Invoker) *staticDirectory {
- var url common.URL
+ var url *common.URL
if len(invokers) > 0 {
url = invokers[0].GetUrl()
}
dir := &staticDirectory{
- BaseDirectory: NewBaseDirectory(&url),
+ BaseDirectory: NewBaseDirectory(url),
invokers: invokers,
}
@@ -72,7 +72,7 @@
return invokers
}
dirUrl := dir.GetUrl()
- return routerChain.Route(&dirUrl, invocation)
+ return routerChain.Route(dirUrl, invocation)
}
// Destroy Destroy
@@ -91,7 +91,7 @@
return perrors.Errorf("invokers == null")
}
url := invokers[0].GetUrl()
- routerChain, e := chain.NewRouterChain(&url)
+ routerChain, e := chain.NewRouterChain(url)
if e != nil {
return e
}
diff --git a/cluster/loadbalance/consistent_hash_test.go b/cluster/loadbalance/consistent_hash_test.go
index 9f22d39..0fbb740 100644
--- a/cluster/loadbalance/consistent_hash_test.go
+++ b/cluster/loadbalance/consistent_hash_test.go
@@ -84,9 +84,9 @@
type consistentHashLoadBalanceSuite struct {
suite.Suite
- url1 common.URL
- url2 common.URL
- url3 common.URL
+ url1 *common.URL
+ url2 *common.URL
+ url3 *common.URL
invokers []protocol.Invoker
invoker1 protocol.Invoker
invoker2 protocol.Invoker
diff --git a/cluster/router/chain/chain.go b/cluster/router/chain/chain.go
index 252093a..612c12d 100644
--- a/cluster/router/chain/chain.go
+++ b/cluster/router/chain/chain.go
@@ -55,7 +55,7 @@
mutex sync.RWMutex
- url common.URL
+ url *common.URL
// The times of address notification since last update for address cache
count int64
@@ -215,7 +215,7 @@
}
// URL Return URL in RouterChain
-func (c *RouterChain) URL() common.URL {
+func (c *RouterChain) URL() *common.URL {
return c.url
}
@@ -248,7 +248,7 @@
notify: make(chan struct{}),
}
if url != nil {
- chain.url = *url
+ chain.url = url
}
go chain.loop()
diff --git a/cluster/router/chain/chain_test.go b/cluster/router/chain/chain_test.go
index 5a9f2d1..b21990b 100644
--- a/cluster/router/chain/chain_test.go
+++ b/cluster/router/chain/chain_test.go
@@ -65,7 +65,6 @@
assert.NoError(t, err)
err = z.Create(path)
assert.NoError(t, err)
-
testyml := `scope: application
key: mock-app
enabled: true
@@ -81,7 +80,7 @@
defer z.Close()
zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port))
- configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl)
+ configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(zkUrl)
config.GetEnvInstance().SetDynamicConfiguration(configuration)
assert.Nil(t, err)
@@ -133,7 +132,7 @@
defer z.Close()
zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port))
- configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl)
+ configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(zkUrl)
config.GetEnvInstance().SetDynamicConfiguration(configuration)
chain, err := NewRouterChain(getConditionRouteUrl(applicationKey))
@@ -159,7 +158,7 @@
defer z.Close()
zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port))
- configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl)
+ configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(zkUrl)
config.GetEnvInstance().SetDynamicConfiguration(configuration)
chain, err := NewRouterChain(getConditionRouteUrl(applicationKey))
@@ -169,7 +168,7 @@
url := getConditionRouteUrl(applicationKey)
assert.NotNil(t, url)
- invokers := []protocol.Invoker{}
+ var invokers []protocol.Invoker
dubboURL, _ := common.NewURL(fmt.Sprintf(dubboForamt, test1234IP, port20000))
invokers = append(invokers, protocol.NewBaseInvoker(dubboURL))
chain.SetInvokers(invokers)
@@ -177,7 +176,7 @@
targetURL, _ := common.NewURL(fmt.Sprintf(consumerFormat, test1111IP))
inv := &invocation.RPCInvocation{}
- finalInvokers := chain.Route(&targetURL, inv)
+ finalInvokers := chain.Route(targetURL, inv)
assert.Equal(t, 1, len(finalInvokers))
}
@@ -203,14 +202,14 @@
defer z.Close()
zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port))
- configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl)
+ configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(zkUrl)
config.GetEnvInstance().SetDynamicConfiguration(configuration)
chain, err := NewRouterChain(getConditionRouteUrl(applicationKey))
assert.Nil(t, err)
assert.Equal(t, 2, len(chain.routers))
- invokers := []protocol.Invoker{}
+ var invokers []protocol.Invoker
dubboURL, _ := common.NewURL(fmt.Sprintf(dubboForamt, test1234IP, port20000))
invokers = append(invokers, protocol.NewBaseInvoker(dubboURL))
chain.SetInvokers(invokers)
@@ -218,7 +217,7 @@
targetURL, _ := common.NewURL(fmt.Sprintf(consumerFormat, test1111IP))
inv := &invocation.RPCInvocation{}
- finalInvokers := chain.Route(&targetURL, inv)
+ finalInvokers := chain.Route(targetURL, inv)
assert.Equal(t, 0, len(finalInvokers))
}
@@ -229,7 +228,7 @@
defer z.Close()
zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port))
- configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(&zkUrl)
+ configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(zkUrl)
config.GetEnvInstance().SetDynamicConfiguration(configuration)
chain, err := NewRouterChain(getConditionNoRouteUrl(applicationKey))
@@ -239,7 +238,7 @@
url := getConditionRouteUrl(applicationKey)
assert.NotNil(t, url)
- invokers := []protocol.Invoker{}
+ var invokers []protocol.Invoker
dubboURL, _ := common.NewURL(fmt.Sprintf(dubboForamt, test1234IP, port20000))
invokers = append(invokers, protocol.NewBaseInvoker(dubboURL))
chain.SetInvokers(invokers)
@@ -247,7 +246,7 @@
targetURL, _ := common.NewURL(fmt.Sprintf(consumerFormat, test1111IP))
inv := &invocation.RPCInvocation{}
- finalInvokers := chain.Route(&targetURL, inv)
+ finalInvokers := chain.Route(targetURL, inv)
assert.Equal(t, 0, len(finalInvokers))
}
@@ -258,7 +257,7 @@
url.AddParam(forceField, forceValue)
rule := base64.URLEncoding.EncodeToString([]byte("host = 1.1.1.1 => host != 1.2.3.4"))
url.AddParam(constant.RULE_KEY, rule)
- return &url
+ return url
}
func getConditionRouteUrl(applicationKey string) *common.URL {
@@ -267,12 +266,12 @@
url.AddParam(forceField, forceValue)
rule := base64.URLEncoding.EncodeToString([]byte("host = 1.1.1.1 => host = 1.2.3.4"))
url.AddParam(constant.RULE_KEY, rule)
- return &url
+ return url
}
func getRouteUrl(applicationKey string) *common.URL {
url, _ := common.NewURL(fmt.Sprintf(anyUrlFormat, test0000IP))
url.AddParam(applicationField, applicationKey)
url.AddParam(forceField, forceValue)
- return &url
+ return url
}
diff --git a/cluster/router/condition/app_router_test.go b/cluster/router/condition/app_router_test.go
index cce96b1..879abc5 100644
--- a/cluster/router/condition/app_router_test.go
+++ b/cluster/router/condition/app_router_test.go
@@ -71,7 +71,7 @@
defer z.Close()
zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, routerLocalIP, ts.Servers[0].Port))
- configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(&zkUrl)
+ configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(zkUrl)
config.GetEnvInstance().SetDynamicConfiguration(configuration)
assert.Nil(t, err)
@@ -119,7 +119,7 @@
defer z.Close()
zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, routerLocalIP, ts.Servers[0].Port))
- configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(&zkUrl)
+ configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(zkUrl)
config.GetEnvInstance().SetDynamicConfiguration(configuration)
assert.Nil(t, err)
@@ -158,7 +158,7 @@
defer z.Close()
zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, routerLocalIP, ts.Servers[0].Port))
- configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(&zkUrl)
+ configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(zkUrl)
config.GetEnvInstance().SetDynamicConfiguration(configuration)
assert.Nil(t, err)
@@ -194,5 +194,5 @@
url, _ := common.NewURL(fmt.Sprintf(conditionFormat, constant.ANYHOST_VALUE))
url.AddParam("application", applicationKey)
url.AddParam("force", "true")
- return &url
+ return url
}
diff --git a/cluster/router/condition/factory_test.go b/cluster/router/condition/factory_test.go
index 8fdfae7..c916588 100644
--- a/cluster/router/condition/factory_test.go
+++ b/cluster/router/condition/factory_test.go
@@ -52,13 +52,13 @@
)
type MockInvoker struct {
- url common.URL
+ url *common.URL
available bool
destroyed bool
successCount int
}
-func NewMockInvoker(url common.URL, successCount int) *MockInvoker {
+func NewMockInvoker(url *common.URL, successCount int) *MockInvoker {
return &MockInvoker{
url: url,
available: true,
@@ -67,7 +67,7 @@
}
}
-func (bi *MockInvoker) GetUrl() common.URL {
+func (bi *MockInvoker) GetUrl() *common.URL {
return bi.url
}
@@ -75,20 +75,20 @@
url, _ := common.NewURL(fmt.Sprintf(factoryUrlFormat, constant.ANYHOST_VALUE))
url.AddParam("rule", rule)
url.AddParam("force", "true")
- return &url
+ return url
}
func getRouteUrlWithForce(rule, force string) *common.URL {
url, _ := common.NewURL(fmt.Sprintf(factoryUrlFormat, constant.ANYHOST_VALUE))
url.AddParam("rule", rule)
url.AddParam("force", force)
- return &url
+ return url
}
func getRouteUrlWithNoForce(rule string) *common.URL {
url, _ := common.NewURL(fmt.Sprintf(factoryUrlFormat, constant.ANYHOST_VALUE))
url.AddParam("rule", rule)
- return &url
+ return url
}
func (bi *MockInvoker) IsAvailable() bool {
@@ -134,31 +134,31 @@
rule := base64.URLEncoding.EncodeToString([]byte("=> host = 1.2.3.4"))
router, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule))
cUrl, _ := common.NewURL(fmt.Sprintf(factoryDubboFormat, factory1111Ip))
- matchWhen := router.(*ConditionRouter).MatchWhen(&cUrl, inv)
+ matchWhen := router.(*ConditionRouter).MatchWhen(cUrl, inv)
assert.Equal(t, true, matchWhen)
rule1 := base64.URLEncoding.EncodeToString([]byte("host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"))
router1, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule1))
- matchWhen1 := router1.(*ConditionRouter).MatchWhen(&cUrl, inv)
+ matchWhen1 := router1.(*ConditionRouter).MatchWhen(cUrl, inv)
assert.Equal(t, true, matchWhen1)
rule2 := base64.URLEncoding.EncodeToString([]byte("host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4"))
router2, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule2))
- matchWhen2 := router2.(*ConditionRouter).MatchWhen(&cUrl, inv)
+ matchWhen2 := router2.(*ConditionRouter).MatchWhen(cUrl, inv)
assert.Equal(t, false, matchWhen2)
rule3 := base64.URLEncoding.EncodeToString([]byte("host !=4.4.4.4 & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"))
router3, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule3))
- matchWhen3 := router3.(*ConditionRouter).MatchWhen(&cUrl, inv)
+ matchWhen3 := router3.(*ConditionRouter).MatchWhen(cUrl, inv)
assert.Equal(t, true, matchWhen3)
rule4 := base64.URLEncoding.EncodeToString([]byte("host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"))
router4, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule4))
- matchWhen4 := router4.(*ConditionRouter).MatchWhen(&cUrl, inv)
+ matchWhen4 := router4.(*ConditionRouter).MatchWhen(cUrl, inv)
assert.Equal(t, true, matchWhen4)
rule5 := base64.URLEncoding.EncodeToString([]byte("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.1 => host = 1.2.3.4"))
router5, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule5))
- matchWhen5 := router5.(*ConditionRouter).MatchWhen(&cUrl, inv)
+ matchWhen5 := router5.(*ConditionRouter).MatchWhen(cUrl, inv)
assert.Equal(t, false, matchWhen5)
rule6 := base64.URLEncoding.EncodeToString([]byte("host = 2.2.2.2,1.1.1.*,3.3.3.3 & host != 1.1.1.2 => host = 1.2.3.4"))
router6, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule6))
- matchWhen6 := router6.(*ConditionRouter).MatchWhen(&cUrl, inv)
+ matchWhen6 := router6.(*ConditionRouter).MatchWhen(cUrl, inv)
assert.Equal(t, true, matchWhen6)
}
@@ -182,12 +182,12 @@
router5, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule5))
router6, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule6))
cUrl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP))
- ret1 := router1.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &cUrl, &invocation.RPCInvocation{})
- ret2 := router2.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &cUrl, &invocation.RPCInvocation{})
- ret3 := router3.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &cUrl, &invocation.RPCInvocation{})
- ret4 := router4.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &cUrl, &invocation.RPCInvocation{})
- ret5 := router5.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &cUrl, &invocation.RPCInvocation{})
- ret6 := router6.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &cUrl, &invocation.RPCInvocation{})
+ ret1 := router1.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), cUrl, &invocation.RPCInvocation{})
+ ret2 := router2.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), cUrl, &invocation.RPCInvocation{})
+ ret3 := router3.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), cUrl, &invocation.RPCInvocation{})
+ ret4 := router4.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), cUrl, &invocation.RPCInvocation{})
+ ret5 := router5.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), cUrl, &invocation.RPCInvocation{})
+ ret6 := router6.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), cUrl, &invocation.RPCInvocation{})
assert.Equal(t, 1, len(ret1.ToArray()))
assert.Equal(t, 0, len(ret2.ToArray()))
assert.Equal(t, 0, len(ret3.ToArray()))
@@ -202,20 +202,20 @@
rule := base64.URLEncoding.EncodeToString([]byte("host !=4.4.4.* & host = 2.2.2.2,1.1.1.1,3.3.3.3 => host = 1.2.3.4"))
r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule))
url, _ := common.NewURL("consumer://1.1.1.1/com.foo.BarService?methods=setFoo,getFoo,findFoo")
- matchWhen := r.(*ConditionRouter).MatchWhen(&url, inv)
+ matchWhen := r.(*ConditionRouter).MatchWhen(url, inv)
assert.Equal(t, true, matchWhen)
url1, _ := common.NewURL(fmt.Sprintf(factoryConsumerMethodFormat, factory1111Ip))
- matchWhen = r.(*ConditionRouter).MatchWhen(&url1, inv)
+ matchWhen = r.(*ConditionRouter).MatchWhen(url1, inv)
assert.Equal(t, true, matchWhen)
url2, _ := common.NewURL(fmt.Sprintf(factoryConsumerMethodFormat, factory1111Ip))
rule2 := base64.URLEncoding.EncodeToString([]byte("methods=getFoo & host!=1.1.1.1 => host = 1.2.3.4"))
router2, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule2))
- matchWhen = router2.(*ConditionRouter).MatchWhen(&url2, inv)
+ matchWhen = router2.(*ConditionRouter).MatchWhen(url2, inv)
assert.Equal(t, false, matchWhen)
url3, _ := common.NewURL(fmt.Sprintf(factoryConsumerMethodFormat, factory1111Ip))
rule3 := base64.URLEncoding.EncodeToString([]byte("methods=getFoo & host=1.1.1.1 => host = 1.2.3.4"))
router3, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule3))
- matchWhen = router3.(*ConditionRouter).MatchWhen(&url3, inv)
+ matchWhen = router3.(*ConditionRouter).MatchWhen(url3, inv)
assert.Equal(t, true, matchWhen)
}
@@ -228,7 +228,7 @@
rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => false"))
curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP))
r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule))
- ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv)
+ ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv)
assert.Equal(t, 0, len(ret.ToArray()))
}
@@ -240,7 +240,7 @@
rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => "))
curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP))
r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule))
- ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv)
+ ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv)
assert.Equal(t, 0, len(ret.ToArray()))
}
@@ -256,7 +256,7 @@
rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = " + localIP))
curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP))
r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule))
- ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv)
+ ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv)
assert.Equal(t, len(invokers), len(ret.ToArray()))
}
@@ -273,7 +273,7 @@
rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = " + localIP))
curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP))
r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule))
- ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv)
+ ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv)
assert.Equal(t, 2, len(ret.ToArray()))
assert.Equal(t, invoker2, invokers[ret.ToArray()[0]])
assert.Equal(t, invoker3, invokers[ret.ToArray()[1]])
@@ -292,7 +292,7 @@
rule := base64.URLEncoding.EncodeToString([]byte(" => " + " host = " + localIP))
curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP))
r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule))
- ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv)
+ ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv)
assert.Equal(t, 2, len(ret.ToArray()))
assert.Equal(t, invoker2, invokers[ret.ToArray()[0]])
assert.Equal(t, invoker3, invokers[ret.ToArray()[1]])
@@ -311,7 +311,7 @@
rule := base64.URLEncoding.EncodeToString([]byte("true => " + " host = " + localIP))
curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP))
r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule))
- ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv)
+ ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv)
assert.Equal(t, 2, len(ret.ToArray()))
assert.Equal(t, invoker2, invokers[ret.ToArray()[0]])
assert.Equal(t, invoker3, invokers[ret.ToArray()[1]])
@@ -330,7 +330,7 @@
rule := base64.URLEncoding.EncodeToString([]byte("host = " + localIP + " => " + " host = $host"))
curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP))
r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule))
- ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv)
+ ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv)
assert.Equal(t, 2, len(ret.ToArray()))
assert.Equal(t, invoker2, invokers[ret.ToArray()[0]])
assert.Equal(t, invoker3, invokers[ret.ToArray()[1]])
@@ -349,7 +349,7 @@
rule := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(factoryHostIp1234Format, localIP)))
curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP))
r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrlWithNoForce(rule))
- ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv)
+ ret := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv)
assert.Equal(t, len(invokers), len(ret.ToArray()))
}
@@ -366,7 +366,7 @@
rule := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(factoryHostIp1234Format, localIP)))
curl, _ := common.NewURL(fmt.Sprintf(factoryConsumerFormat, localIP))
r, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrlWithForce(rule, "true"))
- fileredInvokers := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), &curl, inv)
+ fileredInvokers := r.Route(utils.ToBitmap(invokers), setUpAddrCache(invokers), curl, inv)
assert.Equal(t, 0, len(fileredInvokers.ToArray()))
}
diff --git a/cluster/router/condition/file.go b/cluster/router/condition/file.go
index 996db74..a97d9cb 100644
--- a/cluster/router/condition/file.go
+++ b/cluster/router/condition/file.go
@@ -39,7 +39,7 @@
type FileConditionRouter struct {
listenableRouter
parseOnce sync.Once
- url common.URL
+ url *common.URL
}
// NewFileConditionRouter Create file condition router instance with content ( from config file)
@@ -60,11 +60,11 @@
}
// URL Return URL in file condition router n
-func (f *FileConditionRouter) URL() common.URL {
+func (f *FileConditionRouter) URL() *common.URL {
f.parseOnce.Do(func() {
routerRule := f.routerRule
rule := parseCondition(routerRule.Conditions)
- f.url = *common.NewURLWithOptions(
+ f.url = common.NewURLWithOptions(
common.WithProtocol(constant.CONDITION_ROUTE_PROTOCOL),
common.WithIp(constant.ANYHOST_VALUE),
common.WithParams(url.Values{}),
diff --git a/cluster/router/condition/listenable_router.go b/cluster/router/condition/listenable_router.go
index 19e3a00..0b47310 100644
--- a/cluster/router/condition/listenable_router.go
+++ b/cluster/router/condition/listenable_router.go
@@ -148,6 +148,6 @@
}
// URL Return URL in listenable router
-func (l *listenableRouter) URL() common.URL {
- return *l.url
+func (l *listenableRouter) URL() *common.URL {
+ return l.url
}
diff --git a/cluster/router/condition/router.go b/cluster/router/condition/router.go
index 48f2aae..2fc3307 100644
--- a/cluster/router/condition/router.go
+++ b/cluster/router/condition/router.go
@@ -138,8 +138,8 @@
}
// URL Return URL in condition router
-func (c *ConditionRouter) URL() common.URL {
- return *c.url
+func (c *ConditionRouter) URL() *common.URL {
+ return c.url
}
// Enabled Return is condition router is enabled
@@ -173,7 +173,7 @@
index := iter.Next()
invoker := cache.GetInvokers()[index]
invokerUrl := invoker.GetUrl()
- isMatchThen := c.MatchThen(&invokerUrl, url)
+ isMatchThen := c.MatchThen(invokerUrl, url)
if isMatchThen {
result.Add(index)
}
diff --git a/cluster/router/condition/router_rule_test.go b/cluster/router/condition/router_rule_test.go
index 369b14f..192e528 100644
--- a/cluster/router/condition/router_rule_test.go
+++ b/cluster/router/condition/router_rule_test.go
@@ -80,5 +80,5 @@
func TestIsMatchGlobPattern(t *testing.T) {
url, _ := common.NewURL("dubbo://localhost:8080/Foo?key=v*e")
- assert.Equal(t, true, isMatchGlobalPattern("$key", "value", &url))
+ assert.Equal(t, true, isMatchGlobalPattern("$key", "value", url))
}
diff --git a/cluster/router/condition/router_test.go b/cluster/router/condition/router_test.go
index c27a1d9..3d33ca2 100644
--- a/cluster/router/condition/router_test.go
+++ b/cluster/router/condition/router_test.go
@@ -59,7 +59,7 @@
func TestNewConditionRouter(t *testing.T) {
url, _ := common.NewURL(`condition://0.0.0.0:?application=mock-app&category=routers&force=true&priority=1&router=condition&rule=YSAmIGMgPT4gYiAmIGQ%3D`)
- router, err := NewConditionRouter(&url)
+ router, err := NewConditionRouter(url)
assert.Nil(t, err)
assert.Equal(t, true, router.Enabled())
assert.Equal(t, true, router.Force)
@@ -73,16 +73,16 @@
assert.Error(t, err)
url, _ = common.NewURL(`condition://0.0.0.0:?application=mock-app&category=routers&force=true&priority=1&router=condition&rule=YSAmT4gYiAmIGQ%3D`)
- router, err = NewConditionRouter(&url)
+ router, err = NewConditionRouter(url)
assert.Error(t, err)
url, _ = common.NewURL(`condition://0.0.0.0:?application=mock-app&category=routers&force=true&router=condition&rule=YSAmIGMgPT4gYiAmIGQ%3D`)
- router, err = NewConditionRouter(&url)
+ router, err = NewConditionRouter(url)
assert.Nil(t, err)
assert.Equal(t, int64(150), router.Priority())
url, _ = common.NewURL(`condition://0.0.0.0:?category=routers&force=true&interface=mock-service&router=condition&rule=YSAmIGMgPT4gYiAmIGQ%3D`)
- router, err = NewConditionRouter(&url)
+ router, err = NewConditionRouter(url)
assert.Nil(t, err)
assert.Equal(t, int64(140), router.Priority())
}
diff --git a/cluster/router/healthcheck/default_health_check_test.go b/cluster/router/healthcheck/default_health_check_test.go
index 5d35ae8..39827c5 100644
--- a/cluster/router/healthcheck/default_health_check_test.go
+++ b/cluster/router/healthcheck/default_health_check_test.go
@@ -43,7 +43,7 @@
func TestDefaultHealthCheckerIsHealthy(t *testing.T) {
defer protocol.CleanAllStatus()
url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP))
- hc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker)
+ hc := NewDefaultHealthChecker(url).(*DefaultHealthChecker)
invoker := NewMockInvoker(url)
healthy := hc.IsHealthy(invoker)
assert.True(t, healthy)
@@ -54,7 +54,7 @@
for i := 0; i < 11; i++ {
request(url, healthCheckMethodTest, 0, true, false)
}
- hc = NewDefaultHealthChecker(&url).(*DefaultHealthChecker)
+ hc = NewDefaultHealthChecker(url).(*DefaultHealthChecker)
healthy = hc.IsHealthy(invoker)
// the outgoing request is more than OUTSTANDING_REQUEST_COUNT_LIMIT, go to unhealthy
assert.False(t, hc.IsHealthy(invoker))
@@ -65,7 +65,7 @@
}
url.SetParam(constant.SUCCESSIVE_FAILED_REQUEST_THRESHOLD_KEY, "10")
url.SetParam(constant.OUTSTANDING_REQUEST_COUNT_LIMIT_KEY, "1000")
- hc = NewDefaultHealthChecker(&url).(*DefaultHealthChecker)
+ hc = NewDefaultHealthChecker(url).(*DefaultHealthChecker)
healthy = hc.IsHealthy(invoker)
assert.False(t, hc.IsHealthy(invoker))
@@ -78,7 +78,7 @@
func TestDefaultHealthCheckerGetCircuitBreakerSleepWindowTime(t *testing.T) {
defer protocol.CleanAllStatus()
url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP))
- defaultHc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker)
+ defaultHc := NewDefaultHealthChecker(url).(*DefaultHealthChecker)
// Increase the number of failed requests
for i := 0; i < 100; i++ {
request(url, healthCheckMethodTest, 1, false, false)
@@ -88,7 +88,7 @@
// Adjust the threshold size to 1000
url.SetParam(constant.SUCCESSIVE_FAILED_REQUEST_THRESHOLD_KEY, "1000")
- sleepWindowTime = NewDefaultHealthChecker(&url).(*DefaultHealthChecker).getCircuitBreakerSleepWindowTime(protocol.GetURLStatus(url))
+ sleepWindowTime = NewDefaultHealthChecker(url).(*DefaultHealthChecker).getCircuitBreakerSleepWindowTime(protocol.GetURLStatus(url))
assert.True(t, sleepWindowTime == 0)
url1, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1011IP))
@@ -107,7 +107,7 @@
func TestDefaultHealthCheckerGetCircuitBreakerTimeout(t *testing.T) {
defer protocol.CleanAllStatus()
url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP))
- defaultHc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker)
+ defaultHc := NewDefaultHealthChecker(url).(*DefaultHealthChecker)
timeout := defaultHc.getCircuitBreakerTimeout(protocol.GetURLStatus(url))
assert.True(t, timeout == 0)
url1, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1011IP))
@@ -126,7 +126,7 @@
func TestDefaultHealthCheckerIsCircuitBreakerTripped(t *testing.T) {
defer protocol.CleanAllStatus()
url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP))
- defaultHc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker)
+ defaultHc := NewDefaultHealthChecker(url).(*DefaultHealthChecker)
status := protocol.GetURLStatus(url)
tripped := defaultHc.isCircuitBreakerTripped(status)
assert.False(t, tripped)
@@ -142,7 +142,7 @@
func TestNewDefaultHealthChecker(t *testing.T) {
defer protocol.CleanAllStatus()
url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP))
- defaultHc := NewDefaultHealthChecker(&url).(*DefaultHealthChecker)
+ defaultHc := NewDefaultHealthChecker(url).(*DefaultHealthChecker)
assert.NotNil(t, defaultHc)
assert.Equal(t, defaultHc.outStandingRequestConutLimit, int32(math.MaxInt32))
assert.Equal(t, defaultHc.requestSuccessiveFailureThreshold, int32(constant.DEFAULT_SUCCESSIVE_FAILED_REQUEST_MAX_DIFF))
@@ -150,13 +150,13 @@
url1, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP))
url1.SetParam(constant.OUTSTANDING_REQUEST_COUNT_LIMIT_KEY, "10")
url1.SetParam(constant.SUCCESSIVE_FAILED_REQUEST_THRESHOLD_KEY, "10")
- nondefaultHc := NewDefaultHealthChecker(&url1).(*DefaultHealthChecker)
+ nondefaultHc := NewDefaultHealthChecker(url1).(*DefaultHealthChecker)
assert.NotNil(t, nondefaultHc)
assert.Equal(t, nondefaultHc.outStandingRequestConutLimit, int32(10))
assert.Equal(t, nondefaultHc.requestSuccessiveFailureThreshold, int32(10))
}
-func request(url common.URL, method string, elapsed int64, active, succeeded bool) {
+func request(url *common.URL, method string, elapsed int64, active, succeeded bool) {
protocol.BeginCount(url, method)
if !active {
protocol.EndCount(url, method, elapsed, succeeded)
diff --git a/cluster/router/healthcheck/factory_test.go b/cluster/router/healthcheck/factory_test.go
index e80fd4c..1e73683 100644
--- a/cluster/router/healthcheck/factory_test.go
+++ b/cluster/router/healthcheck/factory_test.go
@@ -33,18 +33,18 @@
// nolint
type MockInvoker struct {
- url common.URL
+ url *common.URL
}
// nolint
-func NewMockInvoker(url common.URL) *MockInvoker {
+func NewMockInvoker(url *common.URL) *MockInvoker {
return &MockInvoker{
url: url,
}
}
// nolint
-func (bi *MockInvoker) GetUrl() common.URL {
+func (bi *MockInvoker) GetUrl() *common.URL {
return bi.url
}
diff --git a/cluster/router/healthcheck/health_check_route.go b/cluster/router/healthcheck/health_check_route.go
index 75ad189..1a878af 100644
--- a/cluster/router/healthcheck/health_check_route.go
+++ b/cluster/router/healthcheck/health_check_route.go
@@ -106,8 +106,8 @@
}
// URL Return URL in router
-func (r *HealthCheckRouter) URL() common.URL {
- return *r.url
+func (r *HealthCheckRouter) URL() *common.URL {
+ return r.url
}
// HealthyChecker returns the HealthChecker bound to this HealthCheckRouter
diff --git a/cluster/router/healthcheck/health_check_route_test.go b/cluster/router/healthcheck/health_check_route_test.go
index c321b56..0730f10 100644
--- a/cluster/router/healthcheck/health_check_route_test.go
+++ b/cluster/router/healthcheck/health_check_route_test.go
@@ -54,7 +54,7 @@
url1, _ := common.NewURL(fmt.Sprintf(healthCheckRouteUrlFormat, healthCheckRoute1010IP))
url2, _ := common.NewURL(fmt.Sprintf(healthCheckRouteUrlFormat, healthCheckRoute1011IP))
url3, _ := common.NewURL(fmt.Sprintf(healthCheckRouteUrlFormat, healthCheckRoute1012IP))
- hcr, _ := NewHealthCheckRouter(&consumerURL)
+ hcr, _ := NewHealthCheckRouter(consumerURL)
var invokers []protocol.Invoker
invoker1 := NewMockInvoker(url1)
@@ -62,14 +62,14 @@
invoker3 := NewMockInvoker(url3)
invokers = append(invokers, invoker1, invoker2, invoker3)
inv := invocation.NewRPCInvocation(healthCheckRouteMethodNameTest, nil, nil)
- res := hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv)
+ res := hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv)
// now all invokers are healthy
assert.True(t, len(res.ToArray()) == len(invokers))
for i := 0; i < 10; i++ {
request(url1, healthCheckRouteMethodNameTest, 0, false, false)
}
- res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv)
+ res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv)
// invokers1 is unhealthy now
assert.True(t, len(res.ToArray()) == 2 && !res.Contains(0))
@@ -78,7 +78,7 @@
request(url2, healthCheckRouteMethodNameTest, 0, false, false)
}
- res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv)
+ res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv)
// only invokers3 is healthy now
assert.True(t, len(res.ToArray()) == 1 && !res.Contains(0) && !res.Contains(1))
@@ -88,24 +88,24 @@
request(url3, healthCheckRouteMethodNameTest, 0, false, false)
}
- res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv)
+ res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv)
// now all invokers are unhealthy, so downgraded to all
assert.True(t, len(res.ToArray()) == 3)
// reset the invoker1 successive failed count, so invoker1 go to healthy
request(url1, healthCheckRouteMethodNameTest, 0, false, true)
- res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv)
+ res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv)
assert.True(t, res.Contains(0))
for i := 0; i < 6; i++ {
request(url1, healthCheckRouteMethodNameTest, 0, false, false)
}
// now all invokers are unhealthy, so downgraded to all again
- res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv)
+ res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv)
assert.True(t, len(res.ToArray()) == 3)
time.Sleep(time.Second * 2)
// invoker1 go to healthy again after 2s
- res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), &consumerURL, inv)
+ res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv)
assert.True(t, res.Contains(0))
}
@@ -113,12 +113,12 @@
func TestNewHealthCheckRouter(t *testing.T) {
defer protocol.CleanAllStatus()
url, _ := common.NewURL(fmt.Sprintf(healthCheckDubboUrlFormat, healthCheckDubbo1010IP))
- hcr, _ := NewHealthCheckRouter(&url)
+ hcr, _ := NewHealthCheckRouter(url)
h := hcr.(*HealthCheckRouter)
assert.Nil(t, h.checker)
url.SetParam(HEALTH_ROUTE_ENABLED_KEY, "true")
- hcr, _ = NewHealthCheckRouter(&url)
+ hcr, _ = NewHealthCheckRouter(url)
h = hcr.(*HealthCheckRouter)
assert.NotNil(t, h.checker)
@@ -130,7 +130,7 @@
url.SetParam(constant.CIRCUIT_TRIPPED_TIMEOUT_FACTOR_KEY, "500")
url.SetParam(constant.SUCCESSIVE_FAILED_REQUEST_THRESHOLD_KEY, "10")
url.SetParam(constant.OUTSTANDING_REQUEST_COUNT_LIMIT_KEY, "1000")
- hcr, _ = NewHealthCheckRouter(&url)
+ hcr, _ = NewHealthCheckRouter(url)
h = hcr.(*HealthCheckRouter)
dhc = h.checker.(*DefaultHealthChecker)
assert.Equal(t, dhc.outStandingRequestConutLimit, int32(1000))
diff --git a/cluster/router/router.go b/cluster/router/router.go
index ddca42a..8a19dcf 100644
--- a/cluster/router/router.go
+++ b/cluster/router/router.go
@@ -45,7 +45,7 @@
Route(*roaring.Bitmap, Cache, *common.URL, protocol.Invocation) *roaring.Bitmap
// URL Return URL in router
- URL() common.URL
+ URL() *common.URL
}
// Router
diff --git a/cluster/router/tag/factory_test.go b/cluster/router/tag/factory_test.go
index ee19582..b350bb2 100644
--- a/cluster/router/tag/factory_test.go
+++ b/cluster/router/tag/factory_test.go
@@ -39,7 +39,7 @@
u1, err := common.NewURL(fmt.Sprintf(factoryFormat, factoryLocalIP))
assert.Nil(t, err)
factory := NewTagRouterFactory()
- tagRouter, e := factory.NewPriorityRouter(&u1)
+ tagRouter, e := factory.NewPriorityRouter(u1)
assert.Nil(t, e)
assert.NotNil(t, tagRouter)
}
diff --git a/cluster/router/tag/file.go b/cluster/router/tag/file.go
index 0ee4311..94daf15 100644
--- a/cluster/router/tag/file.go
+++ b/cluster/router/tag/file.go
@@ -52,13 +52,12 @@
return nil, perrors.Errorf("yaml.Unmarshal() failed , error:%v", perrors.WithStack(err))
}
fileRouter.routerRule = rule
- url := fileRouter.URL()
- fileRouter.router, err = NewTagRouter(&url)
+ fileRouter.router, err = NewTagRouter(fileRouter.URL())
return fileRouter, err
}
// URL Return URL in file tag router n
-func (f *FileTagRouter) URL() common.URL {
+func (f *FileTagRouter) URL() *common.URL {
f.parseOnce.Do(func() {
routerRule := f.routerRule
f.url = common.NewURLWithOptions(
@@ -68,7 +67,7 @@
common.WithParamsValue(constant.RouterPriority, strconv.Itoa(routerRule.Priority)),
common.WithParamsValue(constant.ROUTER_KEY, constant.TAG_ROUTE_PROTOCOL))
})
- return *f.url
+ return f.url
}
// Priority Return Priority in listenable router
diff --git a/cluster/router/tag/tag_router.go b/cluster/router/tag/tag_router.go
index 9f92e83..c7f5304 100644
--- a/cluster/router/tag/tag_router.go
+++ b/cluster/router/tag/tag_router.go
@@ -194,8 +194,8 @@
}
// URL gets the url of tagRouter
-func (c *tagRouter) URL() common.URL {
- return *c.url
+func (c *tagRouter) URL() *common.URL {
+ return c.url
}
// Priority gets the priority of tagRouter
diff --git a/cluster/router/tag/tag_router_test.go b/cluster/router/tag/tag_router_test.go
index 92611ac..3f7b979 100644
--- a/cluster/router/tag/tag_router_test.go
+++ b/cluster/router/tag/tag_router_test.go
@@ -79,13 +79,13 @@
// MockInvoker is only mock the Invoker to support test tagRouter
type MockInvoker struct {
- url common.URL
+ url *common.URL
available bool
destroyed bool
successCount int
}
-func NewMockInvoker(url common.URL) *MockInvoker {
+func NewMockInvoker(url *common.URL) *MockInvoker {
return &MockInvoker{
url: url,
available: true,
@@ -94,7 +94,7 @@
}
}
-func (bi *MockInvoker) GetUrl() common.URL {
+func (bi *MockInvoker) GetUrl() *common.URL {
return bi.url
}
@@ -121,7 +121,7 @@
func TestTagRouterPriority(t *testing.T) {
u1, err := common.NewURL(tagRouterTestUserConsumerTag)
assert.Nil(t, err)
- tagRouter, e := NewTagRouter(&u1)
+ tagRouter, e := NewTagRouter(u1)
assert.Nil(t, e)
p := tagRouter.Priority()
assert.Equal(t, int64(0), p)
@@ -130,7 +130,7 @@
func TestTagRouterRouteForce(t *testing.T) {
u1, e1 := common.NewURL(tagRouterTestUserConsumerTag)
assert.Nil(t, e1)
- tagRouter, e := NewTagRouter(&u1)
+ tagRouter, e := NewTagRouter(u1)
assert.Nil(t, e)
u2, e2 := common.NewURL(tagRouterTestHangZhouUrl)
@@ -146,23 +146,23 @@
invokers = append(invokers, inv2, inv3, inv4)
inv := &invocation.RPCInvocation{}
inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestHangZhou)
- invRst1 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), &u1, inv)
+ invRst1 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), u1, inv)
assert.Equal(t, 1, len(invRst1.ToArray()))
assert.Equal(t, tagRouterTestHangZhou, invokers[invRst1.ToArray()[0]].GetUrl().GetParam(tagRouterTestDubboTag, ""))
inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestGuangZhou)
- invRst2 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), &u1, inv)
+ invRst2 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), u1, inv)
assert.Equal(t, 0, len(invRst2.ToArray()))
inv.SetAttachments(tagRouterTestDubboForceTag, tagRouterTestFalse)
inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestGuangZhou)
- invRst3 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), &u1, inv)
+ invRst3 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), u1, inv)
assert.Equal(t, 3, len(invRst3.ToArray()))
}
func TestTagRouterRouteNoForce(t *testing.T) {
u1, e1 := common.NewURL(tagRouterTestUserConsumer)
assert.Nil(t, e1)
- tagRouter, e := NewTagRouter(&u1)
+ tagRouter, e := NewTagRouter(u1)
assert.Nil(t, e)
u2, e2 := common.NewURL(tagRouterTestHangZhouUrl)
@@ -178,16 +178,16 @@
invokers = append(invokers, inv2, inv3, inv4)
inv := &invocation.RPCInvocation{}
inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestHangZhou)
- invRst := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), &u1, inv)
+ invRst := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), u1, inv)
assert.Equal(t, 1, len(invRst.ToArray()))
assert.Equal(t, tagRouterTestHangZhou, invokers[invRst.ToArray()[0]].GetUrl().GetParam(tagRouterTestDubboTag, ""))
inv.SetAttachments(tagRouterTestDubboTag, tagRouterTestGuangZhou)
inv.SetAttachments(tagRouterTestDubboForceTag, tagRouterTestTrue)
- invRst1 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), &u1, inv)
+ invRst1 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), u1, inv)
assert.Equal(t, 0, len(invRst1.ToArray()))
inv.SetAttachments(tagRouterTestDubboForceTag, tagRouterTestFalse)
- invRst2 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), &u1, inv)
+ invRst2 := tagRouter.Route(utils.ToBitmap(invokers), setUpAddrCache(tagRouter, invokers), u1, inv)
assert.Equal(t, 3, len(invRst2.ToArray()))
}
@@ -225,13 +225,13 @@
invokers = append(invokers, inv2, inv3, inv4, inv5)
url, _ := common.NewURL(tagRouterTestBeijingUrl)
- tagRouter, _ := NewTagRouter(&url)
+ tagRouter, _ := NewTagRouter(url)
rb := roaring.NewBitmap()
rb.AddRange(0, uint64(len(invokers)))
cache := setUpAddrCache(tagRouter, invokers)
inv := &invocation.RPCInvocation{}
- res := tagRouter.Route(rb, cache, &url, inv)
+ res := tagRouter.Route(rb, cache, url, inv)
// inv4 and inv5
assert.Equal(t, []uint32{2, 3}, res.ToArray())
}
@@ -292,7 +292,7 @@
suite.NoError(err)
zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, routerLocalIP, suite.testCluster.Servers[0].Port))
- configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(&zkUrl)
+ configuration, err := extension.GetConfigCenterFactory(routerZk).GetDynamicConfiguration(zkUrl)
config.GetEnvInstance().SetDynamicConfiguration(configuration)
suite.Nil(err)
@@ -301,11 +301,11 @@
url, e1 := common.NewURL(tagRouterTestUserConsumerTag)
suite.Nil(e1)
- tagRouter, err := NewTagRouter(&url)
+ tagRouter, err := NewTagRouter(url)
suite.Nil(err)
suite.NotNil(tagRouter)
suite.route = tagRouter
- suite.url = &url
+ suite.url = url
}
func (suite *DynamicTagRouter) TearDownTest() {
@@ -365,7 +365,7 @@
func TestProcess(t *testing.T) {
u1, err := common.NewURL(tagRouterTestUserConsumerTag)
assert.Nil(t, err)
- tagRouter, e := NewTagRouter(&u1)
+ tagRouter, e := NewTagRouter(u1)
assert.Nil(t, e)
assert.NotNil(t, tagRouter)
diff --git a/common/node.go b/common/node.go
index 4febd78..b9c1f39 100644
--- a/common/node.go
+++ b/common/node.go
@@ -19,7 +19,7 @@
// Node use for process dubbo node
type Node interface {
- GetUrl() URL
+ GetUrl() *URL
IsAvailable() bool
Destroy()
}
diff --git a/common/proxy/proxy_factory.go b/common/proxy/proxy_factory.go
index 117428c..2e66c34 100644
--- a/common/proxy/proxy_factory.go
+++ b/common/proxy/proxy_factory.go
@@ -26,7 +26,7 @@
type ProxyFactory interface {
GetProxy(invoker protocol.Invoker, url *common.URL) *Proxy
GetAsyncProxy(invoker protocol.Invoker, callBack interface{}, url *common.URL) *Proxy
- GetInvoker(url common.URL) protocol.Invoker
+ GetInvoker(url *common.URL) protocol.Invoker
}
// Option will define a function of handling ProxyFactory
diff --git a/common/proxy/proxy_factory/default.go b/common/proxy/proxy_factory/default.go
index 752f3ea..067c077 100644
--- a/common/proxy/proxy_factory/default.go
+++ b/common/proxy/proxy_factory/default.go
@@ -72,7 +72,7 @@
}
// GetInvoker gets a invoker
-func (factory *DefaultProxyFactory) GetInvoker(url common.URL) protocol.Invoker {
+func (factory *DefaultProxyFactory) GetInvoker(url *common.URL) protocol.Invoker {
return &ProxyInvoker{
BaseInvoker: *protocol.NewBaseInvoker(url),
}
@@ -88,9 +88,8 @@
result := &protocol.RPCResult{}
result.SetAttachments(invocation.Attachments())
- url := pi.GetUrl()
//get providerUrl. The origin url may be is registry URL.
- url = *getProviderURL(&url)
+ url := getProviderURL(pi.GetUrl())
methodName := invocation.MethodName()
proto := url.Protocol
diff --git a/common/proxy/proxy_factory/default_test.go b/common/proxy/proxy_factory/default_test.go
index 99d5c02..4002ab9 100644
--- a/common/proxy/proxy_factory/default_test.go
+++ b/common/proxy/proxy_factory/default_test.go
@@ -34,7 +34,7 @@
func TestGetProxy(t *testing.T) {
proxyFactory := NewDefaultProxyFactory()
url := common.NewURLWithOptions()
- proxy := proxyFactory.GetProxy(protocol.NewBaseInvoker(*url), url)
+ proxy := proxyFactory.GetProxy(protocol.NewBaseInvoker(url), url)
assert.NotNil(t, proxy)
}
@@ -49,13 +49,13 @@
proxyFactory := NewDefaultProxyFactory()
url := common.NewURLWithOptions()
async := &TestAsync{}
- proxy := proxyFactory.GetAsyncProxy(protocol.NewBaseInvoker(*url), async.CallBack, url)
+ proxy := proxyFactory.GetAsyncProxy(protocol.NewBaseInvoker(url), async.CallBack, url)
assert.NotNil(t, proxy)
}
func TestGetInvoker(t *testing.T) {
proxyFactory := NewDefaultProxyFactory()
url := common.NewURLWithOptions()
- invoker := proxyFactory.GetInvoker(*url)
+ invoker := proxyFactory.GetInvoker(url)
assert.True(t, invoker.IsAvailable())
}
diff --git a/common/proxy/proxy_test.go b/common/proxy/proxy_test.go
index 9f5eaad..c6f6596 100644
--- a/common/proxy/proxy_test.go
+++ b/common/proxy/proxy_test.go
@@ -58,7 +58,7 @@
func TestProxyImplement(t *testing.T) {
- invoker := protocol.NewBaseInvoker(common.URL{})
+ invoker := protocol.NewBaseInvoker(&common.URL{})
p := NewProxy(invoker, nil, map[string]string{constant.ASYNC_KEY: "false"})
s := &TestService{}
p.Implement(s)
@@ -126,7 +126,7 @@
func TestProxyImplementForContext(t *testing.T) {
invoker := &TestProxyInvoker{
- BaseInvoker: *protocol.NewBaseInvoker(common.URL{}),
+ BaseInvoker: *protocol.NewBaseInvoker(&common.URL{}),
}
p := NewProxy(invoker, nil, map[string]string{constant.ASYNC_KEY: "false"})
s := &TestService{}
diff --git a/common/url.go b/common/url.go
index 3a88001..d8f096b 100644
--- a/common/url.go
+++ b/common/url.go
@@ -21,6 +21,7 @@
"bytes"
"encoding/base64"
"fmt"
+ cm "github.com/Workiva/go-datastructures/common"
"math"
"net"
"net/url"
@@ -88,12 +89,25 @@
PrimitiveURL string
}
-// URL is not thread-safe.
+// noCopy may be embedded into structs which must not be copied
+// after the first use.
+//
+// See https://golang.org/issues/8005#issuecomment-190753527
+// for details.
+type noCopy struct{}
+
+// Lock is a no-op used by -copylocks checker from `go vet`.
+func (*noCopy) Lock() {}
+func (*noCopy) Unlock() {}
+
+// URL thread-safe. but this url should not be copied.
// we fail to define this struct to be immutable object.
// but, those method which will update the URL, including SetParam, SetParams
// are only allowed to be invoked in creating URL instance
// Please keep in mind that this struct is immutable after it has been created and initialized.
type URL struct {
+ noCopy noCopy
+
baseUrl
Path string // like /com.ikurento.dubbo.UserProvider3
Username string
@@ -105,80 +119,80 @@
// Option accepts url
// Option will define a function of handling URL
-type option func(*URL)
+type Option func(*URL)
// WithUsername sets username for url
-func WithUsername(username string) option {
+func WithUsername(username string) Option {
return func(url *URL) {
url.Username = username
}
}
// WithPassword sets password for url
-func WithPassword(pwd string) option {
+func WithPassword(pwd string) Option {
return func(url *URL) {
url.Password = pwd
}
}
// WithMethods sets methods for url
-func WithMethods(methods []string) option {
+func WithMethods(methods []string) Option {
return func(url *URL) {
url.Methods = methods
}
}
// WithParams sets params for url
-func WithParams(params url.Values) option {
+func WithParams(params url.Values) Option {
return func(url *URL) {
url.params = params
}
}
// WithParamsValue sets params field for url
-func WithParamsValue(key, val string) option {
+func WithParamsValue(key, val string) Option {
return func(url *URL) {
url.SetParam(key, val)
}
}
// WithProtocol sets protocol for url
-func WithProtocol(proto string) option {
+func WithProtocol(proto string) Option {
return func(url *URL) {
url.Protocol = proto
}
}
// WithIp sets ip for url
-func WithIp(ip string) option {
+func WithIp(ip string) Option {
return func(url *URL) {
url.Ip = ip
}
}
// WithPort sets port for url
-func WithPort(port string) option {
+func WithPort(port string) Option {
return func(url *URL) {
url.Port = port
}
}
// WithPath sets path for url
-func WithPath(path string) option {
+func WithPath(path string) Option {
return func(url *URL) {
url.Path = "/" + strings.TrimPrefix(path, "/")
}
}
// WithLocation sets location for url
-func WithLocation(location string) option {
+func WithLocation(location string) Option {
return func(url *URL) {
url.Location = location
}
}
// WithToken sets token for url
-func WithToken(token string) option {
+func WithToken(token string) Option {
return func(url *URL) {
if len(token) > 0 {
value := token
@@ -196,33 +210,26 @@
}
// NewURLWithOptions will create a new url with options
-func NewURLWithOptions(opts ...option) *URL {
- url := &URL{}
+func NewURLWithOptions(opts ...Option) *URL {
+ newUrl := &URL{}
for _, opt := range opts {
- opt(url)
+ opt(newUrl)
}
- url.Location = url.Ip + ":" + url.Port
- return url
+ newUrl.Location = newUrl.Ip + ":" + newUrl.Port
+ return newUrl
}
// NewURL will create a new url
// the urlString should not be empty
-func NewURL(urlString string, opts ...option) (URL, error) {
- var (
- err error
- rawUrlString string
- serviceUrl *url.URL
- s = URL{baseUrl: baseUrl{}}
- )
-
- // new a null instance
+func NewURL(urlString string, opts ...Option) (*URL, error) {
+ s := URL{baseUrl: baseUrl{}}
if urlString == "" {
- return s, nil
+ return &s, nil
}
- rawUrlString, err = url.QueryUnescape(urlString)
+ rawUrlString, err := url.QueryUnescape(urlString)
if err != nil {
- return s, perrors.Errorf("url.QueryUnescape(%s), error{%v}", urlString, err)
+ return &s, perrors.Errorf("url.QueryUnescape(%s), error{%v}", urlString, err)
}
// rawUrlString = "//" + rawUrlString
@@ -233,14 +240,15 @@
}
rawUrlString = t.Protocol + "://" + rawUrlString
}
- serviceUrl, err = url.Parse(rawUrlString)
- if err != nil {
- return s, perrors.Errorf("url.Parse(url string{%s}), error{%v}", rawUrlString, err)
+
+ serviceUrl, urlParseErr := url.Parse(rawUrlString)
+ if urlParseErr != nil {
+ return &s, perrors.Errorf("url.Parse(url string{%s}), error{%v}", rawUrlString, err)
}
s.params, err = url.ParseQuery(serviceUrl.RawQuery)
if err != nil {
- return s, perrors.Errorf("url.ParseQuery(raw url string{%s}), error{%v}", serviceUrl.RawQuery, err)
+ return &s, perrors.Errorf("url.ParseQuery(raw url string{%s}), error{%v}", serviceUrl.RawQuery, err)
}
s.PrimitiveURL = urlString
@@ -252,25 +260,29 @@
if strings.Contains(s.Location, ":") {
s.Ip, s.Port, err = net.SplitHostPort(s.Location)
if err != nil {
- return s, perrors.Errorf("net.SplitHostPort(url.Host{%s}), error{%v}", s.Location, err)
+ return &s, perrors.Errorf("net.SplitHostPort(url.Host{%s}), error{%v}", s.Location, err)
}
}
for _, opt := range opts {
opt(&s)
}
- return s, nil
+ return &s, nil
}
// URLEqual judge @url and @c is equal or not.
-func (c URL) URLEqual(url URL) bool {
- c.Ip = ""
- c.Port = ""
- url.Ip = ""
- url.Port = ""
- cGroup := c.GetParam(constant.GROUP_KEY, "")
- urlGroup := url.GetParam(constant.GROUP_KEY, "")
- cKey := c.Key()
- urlKey := url.Key()
+func (c *URL) URLEqual(url *URL) bool {
+ tmpC := c.Clone()
+ tmpC.Ip = ""
+ tmpC.Port = ""
+
+ tmpUrl := url.Clone()
+ tmpUrl.Ip = ""
+ tmpUrl.Port = ""
+
+ cGroup := tmpC.GetParam(constant.GROUP_KEY, "")
+ urlGroup := tmpUrl.GetParam(constant.GROUP_KEY, "")
+ cKey := tmpC.Key()
+ urlKey := tmpUrl.Key()
if cGroup == constant.ANY_VALUE {
cKey = strings.Replace(cKey, "group=*", "group="+urlGroup, 1)
@@ -284,12 +296,12 @@
}
// 2. if url contains enabled key, should be true, or *
- if url.GetParam(constant.ENABLED_KEY, "true") != "true" && url.GetParam(constant.ENABLED_KEY, "") != constant.ANY_VALUE {
+ if tmpUrl.GetParam(constant.ENABLED_KEY, "true") != "true" && tmpUrl.GetParam(constant.ENABLED_KEY, "") != constant.ANY_VALUE {
return false
}
// TODO :may need add interface key any value condition
- return isMatchCategory(url.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY), c.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY))
+ return isMatchCategory(tmpUrl.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY), tmpC.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY))
}
func isMatchCategory(category1 string, category2 string) bool {
@@ -304,31 +316,26 @@
}
}
-func (c URL) String() string {
+func (c *URL) String() string {
var buf strings.Builder
if len(c.Username) == 0 && len(c.Password) == 0 {
- buf.WriteString(fmt.Sprintf(
- "%s://%s:%s%s?",
- c.Protocol, c.Ip, c.Port, c.Path))
+ buf.WriteString(fmt.Sprintf("%s://%s:%s%s?", c.Protocol, c.Ip, c.Port, c.Path))
} else {
- buf.WriteString(fmt.Sprintf(
- "%s://%s:%s@%s:%s%s?",
- c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Path))
+ buf.WriteString(fmt.Sprintf("%s://%s:%s@%s:%s%s?", c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Path))
}
buf.WriteString(c.params.Encode())
return buf.String()
}
// Key gets key
-func (c URL) Key() string {
- buildString := fmt.Sprintf(
- "%s://%s:%s@%s:%s/?interface=%s&group=%s&version=%s",
+func (c *URL) Key() string {
+ buildString := fmt.Sprintf("%s://%s:%s@%s:%s/?interface=%s&group=%s&version=%s",
c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Service(), c.GetParam(constant.GROUP_KEY, ""), c.GetParam(constant.VERSION_KEY, ""))
return buildString
}
// ServiceKey gets a unique key of a service.
-func (c URL) ServiceKey() string {
+func (c *URL) ServiceKey() string {
return ServiceKey(c.GetParam(constant.INTERFACE_KEY, strings.TrimPrefix(c.Path, "/")),
c.GetParam(constant.GROUP_KEY, ""), c.GetParam(constant.VERSION_KEY, ""))
}
@@ -382,7 +389,7 @@
}
// Service gets service
-func (c URL) Service() string {
+func (c *URL) Service() string {
service := c.GetParam(constant.INTERFACE_KEY, strings.TrimPrefix(c.Path, "/"))
if service != "" {
return service
@@ -409,7 +416,6 @@
if c.params == nil {
c.params = url.Values{}
}
-
c.params.Add(key, value)
}
@@ -433,7 +439,7 @@
}
// GetParam gets value by key
-func (c URL) GetParam(s string, d string) string {
+func (c *URL) GetParam(s string, d string) string {
c.paramsLock.RLock()
defer c.paramsLock.RUnlock()
r := c.params.Get(s)
@@ -444,19 +450,19 @@
}
// GetParams gets values
-func (c URL) GetParams() url.Values {
+func (c *URL) GetParams() url.Values {
return c.params
}
// GetParamAndDecoded gets values and decode
-func (c URL) GetParamAndDecoded(key string) (string, error) {
+func (c *URL) GetParamAndDecoded(key string) (string, error) {
ruleDec, err := base64.URLEncoding.DecodeString(c.GetParam(key, ""))
value := string(ruleDec)
return value, err
}
// GetRawParam gets raw param
-func (c URL) GetRawParam(key string) string {
+func (c *URL) GetRawParam(key string) string {
switch key {
case PROTOCOL:
return c.Protocol
@@ -476,7 +482,7 @@
}
// GetParamBool judge whether @key exists or not
-func (c URL) GetParamBool(key string, d bool) bool {
+func (c *URL) GetParamBool(key string, d bool) bool {
r, err := strconv.ParseBool(c.GetParam(key, ""))
if err != nil {
return d
@@ -485,34 +491,34 @@
}
// GetParamInt gets int64 value by @key
-func (c URL) GetParamInt(key string, d int64) int64 {
+func (c *URL) GetParamInt(key string, d int64) int64 {
r, err := strconv.ParseInt(c.GetParam(key, ""), 10, 64)
- if err != nil {
+ if err != nil {
return d
}
return r
}
// GetParamInt32 gets int32 value by @key
-func (c URL) GetParamInt32(key string, d int32) int32 {
+func (c *URL) GetParamInt32(key string, d int32) int32 {
r, err := strconv.ParseInt(c.GetParam(key, ""), 10, 32)
- if err != nil {
+ if err != nil {
return d
}
return int32(r)
}
// GetParamByIntValue gets int value by @key
-func (c URL) GetParamByIntValue(key string, d int) int {
+func (c *URL) GetParamByIntValue(key string, d int) int {
r, err := strconv.ParseInt(c.GetParam(key, ""), 10, 0)
- if err != nil {
+ if err != nil {
return d
}
return int(r)
}
// GetMethodParamInt gets int method param
-func (c URL) GetMethodParamInt(method string, key string, d int64) int64 {
+func (c *URL) GetMethodParamInt(method string, key string, d int64) int64 {
r, err := strconv.ParseInt(c.GetParam("methods."+method+"."+key, ""), 10, 64)
if err != nil {
return d
@@ -521,7 +527,7 @@
}
// GetMethodParamIntValue gets int method param
-func (c URL) GetMethodParamIntValue(method string, key string, d int) int {
+func (c *URL) GetMethodParamIntValue(method string, key string, d int) int {
r, err := strconv.ParseInt(c.GetParam("methods."+method+"."+key, ""), 10, 0)
if err != nil {
return d
@@ -530,7 +536,7 @@
}
// GetMethodParamInt64 gets int64 method param
-func (c URL) GetMethodParamInt64(method string, key string, d int64) int64 {
+func (c *URL) GetMethodParamInt64(method string, key string, d int64) int64 {
r := c.GetMethodParamInt(method, key, math.MinInt64)
if r == math.MinInt64 {
return c.GetParamInt(key, d)
@@ -539,7 +545,7 @@
}
// GetMethodParam gets method param
-func (c URL) GetMethodParam(method string, key string, d string) string {
+func (c *URL) GetMethodParam(method string, key string, d string) string {
r := c.GetParam("methods."+method+"."+key, "")
if r == "" {
r = d
@@ -548,7 +554,7 @@
}
// GetMethodParamBool judge whether @method param exists or not
-func (c URL) GetMethodParamBool(method string, key string, d bool) bool {
+func (c *URL) GetMethodParamBool(method string, key string, d bool) bool {
r := c.GetParamBool("methods."+method+"."+key, d)
return r
}
@@ -564,7 +570,7 @@
}
// ToMap transfer URL to Map
-func (c URL) ToMap() map[string]string {
+func (c *URL) ToMap() map[string]string {
paramsMap := make(map[string]string)
c.RangeParams(func(key, value string) bool {
@@ -668,6 +674,19 @@
return newUrl
}
+func (c *URL) Compare(comp cm.Comparator) int {
+ a := c.String()
+ b := comp.(*URL).String()
+ switch {
+ case a > b:
+ return 1
+ case a < b:
+ return -1
+ default:
+ return 0
+ }
+}
+
// Copy url based on the reserved parameter's keys.
func (c *URL) CloneWithParams(reserveParams []string) *URL {
params := url.Values{}
@@ -691,7 +710,7 @@
}
// IsEquals compares if two URLs equals with each other. Excludes are all parameter keys which should ignored.
-func IsEquals(left URL, right URL, excludes ...string) bool {
+func IsEquals(left *URL, right *URL, excludes ...string) bool {
if left.Ip != right.Ip || left.Port != right.Port {
return false
}
@@ -735,7 +754,7 @@
// URLSlice will be used to sort URL instance
// Instances will be order by URL.String()
-type URLSlice []URL
+type URLSlice []*URL
// nolint
func (s URLSlice) Len() int {
diff --git a/common/url_test.go b/common/url_test.go
index 12020f4..05377c1 100644
--- a/common/url_test.go
+++ b/common/url_test.go
@@ -289,7 +289,7 @@
referenceUrl, _ := NewURL("mock1://127.0.0.1:1111", WithParams(referenceUrlParams), WithMethods([]string{"testMethod"}))
serviceUrl, _ := NewURL("mock2://127.0.0.1:20000", WithParams(serviceUrlParams))
- mergedUrl := MergeUrl(&serviceUrl, &referenceUrl)
+ mergedUrl := MergeUrl(serviceUrl, referenceUrl)
assert.Equal(t, "random", mergedUrl.GetParam(constant.CLUSTER_KEY, ""))
assert.Equal(t, "1", mergedUrl.GetParam("test2", ""))
assert.Equal(t, "1", mergedUrl.GetParam("test3", ""))
diff --git a/config/config_center_config.go b/config/config_center_config.go
index 0fc4007..752d9d4 100644
--- a/config/config_center_config.go
+++ b/config/config_center_config.go
@@ -91,7 +91,7 @@
// toURL will compatible with baseConfig.ConfigCenterConfig.Address and baseConfig.ConfigCenterConfig.RemoteRef before 1.6.0
// After 1.6.0 will not compatible, only baseConfig.ConfigCenterConfig.RemoteRef
-func (b *configCenter) toURL(baseConfig BaseConfig) (common.URL, error) {
+func (b *configCenter) toURL(baseConfig BaseConfig) (*common.URL, error) {
if len(baseConfig.ConfigCenterConfig.Address) > 0 {
return common.NewURL(baseConfig.ConfigCenterConfig.Address,
common.WithProtocol(baseConfig.ConfigCenterConfig.Protocol), common.WithParams(baseConfig.ConfigCenterConfig.GetUrlMap()))
@@ -101,7 +101,7 @@
rc, ok := baseConfig.GetRemoteConfig(remoteRef)
if !ok {
- return common.URL{}, perrors.New("Could not find out the remote ref config, name: " + remoteRef)
+ return nil, perrors.New("Could not find out the remote ref config, name: " + remoteRef)
}
newURL, err := rc.toURL()
@@ -114,11 +114,11 @@
// startConfigCenter will start the config center.
// it will prepare the environment
func (b *configCenter) startConfigCenter(baseConfig BaseConfig) error {
- url, err := b.toURL(baseConfig)
+ newUrl, err := b.toURL(baseConfig)
if err != nil {
return err
}
- if err = b.prepareEnvironment(baseConfig, &url); err != nil {
+ if err = b.prepareEnvironment(baseConfig, newUrl); err != nil {
return perrors.WithMessagef(err, "start config center error!")
}
// c.fresh()
diff --git a/config/config_loader.go b/config/config_loader.go
index f210224..ec591aa 100644
--- a/config/config_loader.go
+++ b/config/config_loader.go
@@ -216,7 +216,7 @@
if url == nil {
return
}
- instance, err := createInstance(*url)
+ instance, err := createInstance(url)
if err != nil {
panic(err)
}
@@ -240,7 +240,7 @@
}
// nolint
-func createInstance(url common.URL) (registry.ServiceInstance, error) {
+func createInstance(url *common.URL) (registry.ServiceInstance, error) {
appConfig := GetApplicationConfig()
port, err := strconv.ParseInt(url.Port, 10, 32)
if err != nil {
@@ -250,9 +250,6 @@
host := url.Ip
if len(host) == 0 {
host = common.GetLocalIp()
- if err != nil {
- return nil, perrors.WithMessage(err, "could not get the local Ip")
- }
}
// usually we will add more metadata
@@ -272,7 +269,7 @@
// selectMetadataServiceExportedURL get already be exported url
func selectMetadataServiceExportedURL() *common.URL {
- var selectedUrl common.URL
+ var selectedUrl *common.URL
metaDataService, err := extension.GetMetadataService(GetApplicationConfig().MetadataType)
if err != nil {
logger.Warn(err)
@@ -297,7 +294,7 @@
break
}
}
- return &selectedUrl
+ return selectedUrl
}
func initRouter() {
diff --git a/config/config_loader_test.go b/config/config_loader_test.go
index 461e607..9b25303 100644
--- a/config/config_loader_test.go
+++ b/config/config_loader_test.go
@@ -25,7 +25,6 @@
)
import (
- cm "github.com/Workiva/go-datastructures/common"
"github.com/Workiva/go-datastructures/slice/skip"
gxset "github.com/dubbogo/gost/container/set"
gxpage "github.com/dubbogo/gost/page"
@@ -353,27 +352,27 @@
panic("implement me")
}
-func (m *mockMetadataService) ExportURL(url common.URL) (bool, error) {
- return m.addURL(m.exportedServiceURLs, &url), nil
+func (m *mockMetadataService) ExportURL(url *common.URL) (bool, error) {
+ return m.addURL(m.exportedServiceURLs, url), nil
}
-func (m *mockMetadataService) UnexportURL(url common.URL) error {
+func (m *mockMetadataService) UnexportURL(*common.URL) error {
panic("implement me")
}
-func (m *mockMetadataService) SubscribeURL(url common.URL) (bool, error) {
+func (m *mockMetadataService) SubscribeURL(*common.URL) (bool, error) {
panic("implement me")
}
-func (m *mockMetadataService) UnsubscribeURL(url common.URL) error {
+func (m *mockMetadataService) UnsubscribeURL(*common.URL) error {
panic("implement me")
}
-func (m *mockMetadataService) PublishServiceDefinition(url common.URL) error {
+func (m *mockMetadataService) PublishServiceDefinition(*common.URL) error {
return nil
}
-func (m *mockMetadataService) GetExportedURLs(serviceInterface string, group string, version string, protocol string) ([]interface{}, error) {
+func (m *mockMetadataService) GetExportedURLs(string, string, string, string) ([]interface{}, error) {
return ConvertURLArrToIntfArr(m.getAllService(m.exportedServiceURLs)), nil
}
@@ -381,19 +380,19 @@
panic("implement me")
}
-func (m *mockMetadataService) GetSubscribedURLs() ([]common.URL, error) {
+func (m *mockMetadataService) GetSubscribedURLs() ([]*common.URL, error) {
panic("implement me")
}
-func (m *mockMetadataService) GetServiceDefinition(interfaceName string, group string, version string) (string, error) {
+func (m *mockMetadataService) GetServiceDefinition(string, string, string) (string, error) {
panic("implement me")
}
-func (m *mockMetadataService) GetServiceDefinitionByServiceKey(serviceKey string) (string, error) {
+func (m *mockMetadataService) GetServiceDefinitionByServiceKey(string) (string, error) {
panic("implement me")
}
-func (m *mockMetadataService) RefreshMetadata(exportedRevision string, subscribedRevision string) (bool, error) {
+func (m *mockMetadataService) RefreshMetadata(string, string) (bool, error) {
panic("implement me")
}
@@ -409,7 +408,7 @@
logger.Debug(url.ServiceKey())
if urlSet, loaded = targetMap.LoadOrStore(url.ServiceKey(), skip.New(uint64(0))); loaded {
mts.lock.RLock()
- wantedUrl := urlSet.(*skip.SkipList).Get(Comparator(*url))
+ wantedUrl := urlSet.(*skip.SkipList).Get(url)
if len(wantedUrl) > 0 && wantedUrl[0] != nil {
mts.lock.RUnlock()
return false
@@ -418,23 +417,23 @@
}
mts.lock.Lock()
// double chk
- wantedUrl := urlSet.(*skip.SkipList).Get(Comparator(*url))
+ wantedUrl := urlSet.(*skip.SkipList).Get(url)
if len(wantedUrl) > 0 && wantedUrl[0] != nil {
mts.lock.Unlock()
return false
}
- urlSet.(*skip.SkipList).Insert(Comparator(*url))
+ urlSet.(*skip.SkipList).Insert(url)
mts.lock.Unlock()
return true
}
-func (m *mockMetadataService) getAllService(services *sync.Map) []common.URL {
+func (m *mockMetadataService) getAllService(services *sync.Map) []*common.URL {
// using skip list to dedup and sorting
- res := make([]common.URL, 0)
+ var res []*common.URL
services.Range(func(key, value interface{}) bool {
urls := value.(*skip.SkipList)
for i := uint64(0); i < urls.Len(); i++ {
- url := common.URL(urls.ByPosition(i).(Comparator))
+ url := urls.ByPosition(i).(*common.URL)
if url.GetParam(constant.INTERFACE_KEY, url.Path) != constant.METADATA_SERVICE_NAME {
res = append(res, url)
}
@@ -445,26 +444,10 @@
return res
}
-type Comparator common.URL
-
-// Compare is defined as Comparator for skip list to compare the URL
-func (c Comparator) Compare(comp cm.Comparator) int {
- a := common.URL(c).String()
- b := common.URL(comp.(Comparator)).String()
- switch {
- case a > b:
- return 1
- case a < b:
- return -1
- default:
- return 0
- }
-}
-
type mockServiceDiscoveryRegistry struct {
}
-func (mr *mockServiceDiscoveryRegistry) GetUrl() common.URL {
+func (mr *mockServiceDiscoveryRegistry) GetUrl() *common.URL {
panic("implement me")
}
@@ -476,11 +459,11 @@
panic("implement me")
}
-func (mr *mockServiceDiscoveryRegistry) Register(url common.URL) error {
+func (mr *mockServiceDiscoveryRegistry) Register(*common.URL) error {
panic("implement me")
}
-func (mr *mockServiceDiscoveryRegistry) UnRegister(url common.URL) error {
+func (mr *mockServiceDiscoveryRegistry) UnRegister(*common.URL) error {
panic("implement me")
}
@@ -507,15 +490,15 @@
panic("implement me")
}
-func (m *mockServiceDiscovery) Register(instance registry.ServiceInstance) error {
+func (m *mockServiceDiscovery) Register(registry.ServiceInstance) error {
return nil
}
-func (m *mockServiceDiscovery) Update(instance registry.ServiceInstance) error {
+func (m *mockServiceDiscovery) Update(registry.ServiceInstance) error {
panic("implement me")
}
-func (m *mockServiceDiscovery) Unregister(instance registry.ServiceInstance) error {
+func (m *mockServiceDiscovery) Unregister(registry.ServiceInstance) error {
panic("implement me")
}
@@ -527,39 +510,39 @@
panic("implement me")
}
-func (m *mockServiceDiscovery) GetInstances(serviceName string) []registry.ServiceInstance {
+func (m *mockServiceDiscovery) GetInstances(string) []registry.ServiceInstance {
panic("implement me")
}
-func (m *mockServiceDiscovery) GetInstancesByPage(serviceName string, offset int, pageSize int) gxpage.Pager {
+func (m *mockServiceDiscovery) GetInstancesByPage(string, int, int) gxpage.Pager {
panic("implement me")
}
-func (m *mockServiceDiscovery) GetHealthyInstancesByPage(serviceName string, offset int, pageSize int, healthy bool) gxpage.Pager {
+func (m *mockServiceDiscovery) GetHealthyInstancesByPage(string, int, int, bool) gxpage.Pager {
panic("implement me")
}
-func (m *mockServiceDiscovery) GetRequestInstances(serviceNames []string, offset int, requestedSize int) map[string]gxpage.Pager {
+func (m *mockServiceDiscovery) GetRequestInstances([]string, int, int) map[string]gxpage.Pager {
panic("implement me")
}
-func (m *mockServiceDiscovery) AddListener(listener *registry.ServiceInstancesChangedListener) error {
+func (m *mockServiceDiscovery) AddListener(*registry.ServiceInstancesChangedListener) error {
panic("implement me")
}
-func (m *mockServiceDiscovery) DispatchEventByServiceName(serviceName string) error {
+func (m *mockServiceDiscovery) DispatchEventByServiceName(string) error {
panic("implement me")
}
-func (m *mockServiceDiscovery) DispatchEventForInstances(serviceName string, instances []registry.ServiceInstance) error {
+func (m *mockServiceDiscovery) DispatchEventForInstances(string, []registry.ServiceInstance) error {
panic("implement me")
}
-func (m *mockServiceDiscovery) DispatchEvent(event *registry.ServiceInstancesChangedEvent) error {
+func (m *mockServiceDiscovery) DispatchEvent(*registry.ServiceInstancesChangedEvent) error {
panic("implement me")
}
-func ConvertURLArrToIntfArr(urls []common.URL) []interface{} {
+func ConvertURLArrToIntfArr(urls []*common.URL) []interface{} {
if len(urls) == 0 {
return []interface{}{}
}
diff --git a/config/instance/metadata_report.go b/config/instance/metadata_report.go
index 8e833dd..68a197d 100644
--- a/config/instance/metadata_report.go
+++ b/config/instance/metadata_report.go
@@ -29,7 +29,7 @@
var (
instance report.MetadataReport
- reportUrl common.URL
+ reportUrl *common.URL
once sync.Once
)
@@ -41,18 +41,18 @@
if len(selectiveUrl) > 0 {
url = selectiveUrl[0]
instance = extension.GetMetadataReportFactory(url.Protocol).CreateMetadataReport(url)
- reportUrl = *url
+ reportUrl = url
}
})
return instance
}
// GetMetadataReportUrl will return the report instance url
-func GetMetadataReportUrl() common.URL {
+func GetMetadataReportUrl() *common.URL {
return reportUrl
}
// SetMetadataReportUrl will only can be used by unit test to mock url
-func SetMetadataReportUrl(url common.URL) {
+func SetMetadataReportUrl(url *common.URL) {
reportUrl = url
}
diff --git a/config/instance/metadata_report_test.go b/config/instance/metadata_report_test.go
index d489af0..110903a 100644
--- a/config/instance/metadata_report_test.go
+++ b/config/instance/metadata_report_test.go
@@ -38,7 +38,7 @@
return &mockMetadataReportFactory{}
})
u, _ := common.NewURL("mock://127.0.0.1")
- rpt := GetMetadataReportInstance(&u)
+ rpt := GetMetadataReportInstance(u)
assert.NotNil(t, rpt)
}
@@ -60,7 +60,7 @@
panic("implement me")
}
-func (m mockMetadataReport) SaveServiceMetadata(*identifier.ServiceMetadataIdentifier, common.URL) error {
+func (m mockMetadataReport) SaveServiceMetadata(*identifier.ServiceMetadataIdentifier, *common.URL) error {
panic("implement me")
}
diff --git a/config/metadata_report_config.go b/config/metadata_report_config.go
index 6d319e5..24eba5e 100644
--- a/config/metadata_report_config.go
+++ b/config/metadata_report_config.go
@@ -84,7 +84,7 @@
return nil, perrors.New("Invalid MetadataReportConfig.")
}
res.SetParam("metadata", res.Protocol)
- return &res, nil
+ return res, nil
}
func (c *MetadataReportConfig) IsValid() bool {
@@ -101,8 +101,8 @@
return perrors.New("MetadataConfig remote ref can not be empty.")
}
- if url, err := metadataReportConfig.ToUrl(); err == nil {
- instance.GetMetadataReportInstance(url)
+ if tmpUrl, err := metadataReportConfig.ToUrl(); err == nil {
+ instance.GetMetadataReportInstance(tmpUrl)
} else {
return perrors.Wrap(err, "Start MetadataReport failed.")
}
diff --git a/config/reference_config.go b/config/reference_config.go
index cd10f89..2e914ac 100644
--- a/config/reference_config.go
+++ b/config/reference_config.go
@@ -114,13 +114,13 @@
}
if serviceUrl.Protocol == constant.REGISTRY_PROTOCOL {
serviceUrl.SubURL = cfgURL
- c.urls = append(c.urls, &serviceUrl)
+ c.urls = append(c.urls, serviceUrl)
} else {
if serviceUrl.Path == "" {
serviceUrl.Path = "/" + c.id
}
// merge url need to do
- newUrl := common.MergeUrl(&serviceUrl, cfgURL)
+ newUrl := common.MergeUrl(serviceUrl, cfgURL)
c.urls = append(c.urls, newUrl)
}
}
@@ -135,12 +135,12 @@
}
if len(c.urls) == 1 {
- c.invoker = extension.GetProtocol(c.urls[0].Protocol).Refer(*c.urls[0])
+ c.invoker = extension.GetProtocol(c.urls[0].Protocol).Refer(c.urls[0])
} else {
invokers := make([]protocol.Invoker, 0, len(c.urls))
var regUrl *common.URL
for _, u := range c.urls {
- invokers = append(invokers, extension.GetProtocol(u.Protocol).Refer(*u))
+ invokers = append(invokers, extension.GetProtocol(u.Protocol).Refer(u))
if u.Protocol == constant.REGISTRY_PROTOCOL {
regUrl = u
}
diff --git a/config/reference_config_test.go b/config/reference_config_test.go
index a4345ad..0207e1f 100644
--- a/config/reference_config_test.go
+++ b/config/reference_config_test.go
@@ -334,7 +334,7 @@
type mockRegistryProtocol struct{}
-func (*mockRegistryProtocol) Refer(url common.URL) protocol.Invoker {
+func (*mockRegistryProtocol) Refer(url *common.URL) protocol.Invoker {
return protocol.NewBaseInvoker(url)
}
@@ -345,7 +345,7 @@
if err != nil {
panic(err)
}
- ok, err := metaDataService.ExportURL(*invoker.GetUrl().SubURL.Clone())
+ ok, err := metaDataService.ExportURL(invoker.GetUrl().SubURL.Clone())
if err != nil {
panic(err)
}
@@ -367,7 +367,7 @@
protocol := url.GetParam(constant.REGISTRY_KEY, "")
url.Protocol = protocol
}
- return &url
+ return url
}
func (p *mockRegistryProtocol) GetRegistries() []registry.Registry {
diff --git a/config/registry_config.go b/config/registry_config.go
index 89566c4..5aff45d 100644
--- a/config/registry_config.go
+++ b/config/registry_config.go
@@ -53,7 +53,7 @@
//ZoneForce bool `yaml:"zoneForce" json:"zoneForce,omitempty" property:"zoneForce"`
// Affects traffic distribution among registries,
// useful when subscribe to multiple registries Take effect only when no preferred registry is specified.
- Weight int64 `yaml:"weight" json:"params,omitempty" property:"weight"`
+ Weight int64 `yaml:"weight" json:"weight,omitempty" property:"weight"`
Params map[string]string `yaml:"params" json:"params,omitempty" property:"params"`
}
@@ -114,7 +114,7 @@
logger.Errorf("The registry id: %s url is invalid, error: %#v", k, err)
panic(err)
} else {
- urls = append(urls, &url)
+ urls = append(urls, url)
}
}
}
diff --git a/config/remote_config.go b/config/remote_config.go
index 0f0c3e5..61d4dce 100644
--- a/config/remote_config.go
+++ b/config/remote_config.go
@@ -63,9 +63,9 @@
return param
}
-func (rc *RemoteConfig) toURL() (common.URL, error) {
+func (rc *RemoteConfig) toURL() (*common.URL, error) {
if len(rc.Protocol) == 0 {
- return common.URL{}, perrors.Errorf("Must provide protocol in RemoteConfig.")
+ return nil, perrors.Errorf("Must provide protocol in RemoteConfig.")
}
return common.NewURL(rc.Address,
common.WithUsername(rc.Username),
diff --git a/config/service_config.go b/config/service_config.go
index 9a27443..b3febc6 100644
--- a/config/service_config.go
+++ b/config/service_config.go
@@ -208,7 +208,7 @@
for _, regUrl := range regUrls {
regUrl.SubURL = ivkURL
- invoker := proxyFactory.GetInvoker(*regUrl)
+ invoker := proxyFactory.GetInvoker(regUrl)
exporter := c.cacheProtocol.Export(invoker)
if exporter == nil {
return perrors.New(fmt.Sprintf("Registry protocol new exporter error, registry is {%v}, url is {%v}", regUrl, ivkURL))
@@ -216,7 +216,7 @@
c.exporters = append(c.exporters, exporter)
}
} else {
- invoker := proxyFactory.GetInvoker(*ivkURL)
+ invoker := proxyFactory.GetInvoker(ivkURL)
exporter := extension.GetProtocol(protocolwrapper.FILTER).Export(invoker)
if exporter == nil {
return perrors.New(fmt.Sprintf("Filter protocol without registry new exporter error, url is {%v}", ivkURL))
@@ -326,8 +326,7 @@
if c.exported.Load() {
var urls []*common.URL
for _, exporter := range c.exporters {
- url := exporter.GetInvoker().GetUrl()
- urls = append(urls, &url)
+ urls = append(urls, exporter.GetInvoker().GetUrl())
}
return urls
}
diff --git a/config_center/apollo/impl.go b/config_center/apollo/impl.go
index ac5328c..c69fc2f 100644
--- a/config_center/apollo/impl.go
+++ b/config_center/apollo/impl.go
@@ -109,11 +109,11 @@
}
func (c *apolloConfiguration) GetInternalProperty(key string, opts ...cc.Option) (string, error) {
- config := agollo.GetConfig(c.appConf.NamespaceName)
- if config == nil {
+ newConfig := agollo.GetConfig(c.appConf.NamespaceName)
+ if newConfig == nil {
return "", perrors.New(fmt.Sprintf("nothing in namespace:%s ", key))
}
- return config.GetStringValue(key, ""), nil
+ return newConfig.GetStringValue(key, ""), nil
}
func (c *apolloConfiguration) GetRule(key string, opts ...cc.Option) (string, error) {
@@ -135,11 +135,11 @@
* when group is not null, we are getting startup configs(config file) from Config Center, for example:
* key=dubbo.propertie
*/
- config := agollo.GetConfig(key)
- if config == nil {
+ tmpConfig := agollo.GetConfig(key)
+ if tmpConfig == nil {
return "", perrors.New(fmt.Sprintf("nothing in namespace:%s ", key))
}
- return config.GetContent(), nil
+ return tmpConfig.GetContent(), nil
}
func (c *apolloConfiguration) getAddressWithProtocolPrefix(url *common.URL) string {
diff --git a/config_center/apollo/impl_test.go b/config_center/apollo/impl_test.go
index 50c4e68..4720775 100644
--- a/config_center/apollo/impl_test.go
+++ b/config_center/apollo/impl_test.go
@@ -197,7 +197,7 @@
apolloUrl := strings.ReplaceAll(apollo.URL, "http", "apollo")
url, err := common.NewURL(apolloUrl, common.WithParams(c.ConfigCenterConfig.GetUrlMap()))
assert.NoError(t, err)
- configuration, err := newApolloConfiguration(&url)
+ configuration, err := newApolloConfiguration(url)
assert.NoError(t, err)
return configuration
}
diff --git a/config_center/configurator/override_test.go b/config_center/configurator/override_test.go
index 8eccb50..bb9c367 100644
--- a/config_center/configurator/override_test.go
+++ b/config_center/configurator/override_test.go
@@ -40,36 +40,36 @@
func TestConfigureVerison2p6(t *testing.T) {
url, err := common.NewURL("override://0.0.0.0:0/com.xxx.mock.userProvider?group=1&version=1&cluster=failfast&application=BDTService")
assert.NoError(t, err)
- configurator := extension.GetConfigurator(defaults, &url)
+ configurator := extension.GetConfigurator(defaults, url)
assert.Equal(t, override, configurator.GetUrl().Protocol)
providerUrl, err := common.NewURL("jsonrpc://127.0.0.1:20001/com.ikurento.user.UserProvider?anyhost=true&app.version=0.0.1&application=BDTService&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&group=&interface=com.ikurento.user.UserProvider&ip=10.32.20.124&loadbalance=random&methods.GetUser.loadbalance=random&methods.GetUser.retries=1&methods.GetUser.weight=0&module=dubbogo+user-info+server&name=BDTService&organization=ikurento.com&owner=ZX&pid=64225&retries=0&service.filter=echo&side=provider×tamp=1562076628&version=&warmup=100")
assert.NoError(t, err)
- configurator.Configure(&providerUrl)
+ configurator.Configure(providerUrl)
assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, ""))
}
func TestConfigureVerisonOverrideAddr(t *testing.T) {
url, err := common.NewURL("override://0.0.0.0:0/com.xxx.mock.userProvider?group=1&version=1&cluster=failfast&application=BDTService&providerAddresses=127.0.0.2:20001|127.0.0.3:20001")
assert.NoError(t, err)
- configurator := extension.GetConfigurator(defaults, &url)
+ configurator := extension.GetConfigurator(defaults, url)
assert.Equal(t, override, configurator.GetUrl().Protocol)
providerUrl, err := common.NewURL("jsonrpc://127.0.0.1:20001/com.ikurento.user.UserProvider?anyhost=true&app.version=0.0.1&application=BDTService&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&group=&interface=com.ikurento.user.UserProvider&ip=10.32.20.124&loadbalance=random&methods.GetUser.loadbalance=random&methods.GetUser.retries=1&methods.GetUser.weight=0&module=dubbogo+user-info+server&name=BDTService&organization=ikurento.com&owner=ZX&pid=64225&retries=0&service.filter=echo&side=provider×tamp=1562076628&version=&warmup=100")
assert.NoError(t, err)
- configurator.Configure(&providerUrl)
+ configurator.Configure(providerUrl)
assert.Equal(t, failover, providerUrl.GetParam(constant.CLUSTER_KEY, ""))
}
func TestConfigureVerison2p6WithIp(t *testing.T) {
url, err := common.NewURL("override://127.0.0.1:20001/com.xxx.mock.userProvider?group=1&version=1&cluster=failfast&application=BDTService")
assert.NoError(t, err)
- configurator := extension.GetConfigurator(defaults, &url)
+ configurator := extension.GetConfigurator(defaults, url)
assert.Equal(t, override, configurator.GetUrl().Protocol)
providerUrl, err := common.NewURL("jsonrpc://127.0.0.1:20001/com.ikurento.user.UserProvider?anyhost=true&app.version=0.0.1&application=BDTService&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&group=&interface=com.ikurento.user.UserProvider&ip=10.32.20.124&loadbalance=random&methods.GetUser.loadbalance=random&methods.GetUser.retries=1&methods.GetUser.weight=0&module=dubbogo+user-info+server&name=BDTService&organization=ikurento.com&owner=ZX&pid=64225&retries=0&service.filter=echo&side=provider×tamp=1562076628&version=&warmup=100")
assert.NoError(t, err)
- configurator.Configure(&providerUrl)
+ configurator.Configure(providerUrl)
assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, ""))
}
@@ -77,11 +77,11 @@
func TestConfigureVerison2p7(t *testing.T) {
url, err := common.NewURL("jsonrpc://0.0.0.0:20001/com.xxx.mock.userProvider?group=1&version=1&cluster=failfast&application=BDTService&configVersion=1.0&side=provider")
assert.NoError(t, err)
- configurator := extension.GetConfigurator(defaults, &url)
+ configurator := extension.GetConfigurator(defaults, url)
providerUrl, err := common.NewURL("jsonrpc://127.0.0.1:20001/com.ikurento.user.UserProvider?anyhost=true&app.version=0.0.1&application=BDTService&category=providers&cluster=failover&dubbo=dubbo-provider-golang-2.6.0&environment=dev&group=&interface=com.ikurento.user.UserProvider&ip=10.32.20.124&loadbalance=random&methods.GetUser.loadbalance=random&methods.GetUser.retries=1&methods.GetUser.weight=0&module=dubbogo+user-info+server&name=BDTService&organization=ikurento.com&owner=ZX&pid=64225&retries=0&service.filter=echo&side=provider×tamp=1562076628&version=&warmup=100")
assert.NoError(t, err)
- configurator.Configure(&providerUrl)
+ configurator.Configure(providerUrl)
assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, ""))
}
diff --git a/config_center/dynamic_configuration.go b/config_center/dynamic_configuration.go
index cbf8e8c..69f8421 100644
--- a/config_center/dynamic_configuration.go
+++ b/config_center/dynamic_configuration.go
@@ -89,6 +89,6 @@
}
// GetRuleKey The format is '{interfaceName}:[version]:[group]'
-func GetRuleKey(url common.URL) string {
+func GetRuleKey(url *common.URL) string {
return url.ColonSeparatedKey()
}
diff --git a/config_center/file/impl.go b/config_center/file/impl.go
index 9d82540..f29a33d 100644
--- a/config_center/file/impl.go
+++ b/config_center/file/impl.go
@@ -113,9 +113,8 @@
opt(tmpOpts)
}
- path := fsdc.GetPath(key, tmpOpts.Group)
-
- fsdc.cacheListener.AddListener(path, listener)
+ tmpPath := fsdc.GetPath(key, tmpOpts.Group)
+ fsdc.cacheListener.AddListener(tmpPath, listener)
}
// RemoveListener Remove listener
@@ -126,9 +125,8 @@
opt(tmpOpts)
}
- path := fsdc.GetPath(key, tmpOpts.Group)
-
- fsdc.cacheListener.RemoveListener(path, listener)
+ tmpPath := fsdc.GetPath(key, tmpOpts.Group)
+ fsdc.cacheListener.RemoveListener(tmpPath, listener)
}
// GetProperties get properties file
@@ -138,12 +136,11 @@
opt(tmpOpts)
}
- path := fsdc.GetPath(key, tmpOpts.Group)
- file, err := ioutil.ReadFile(path)
+ tmpPath := fsdc.GetPath(key, tmpOpts.Group)
+ file, err := ioutil.ReadFile(tmpPath)
if err != nil {
return "", perrors.WithStack(err)
}
-
return string(file), nil
}
@@ -160,16 +157,16 @@
// PublishConfig will publish the config with the (key, group, value) pair
func (fsdc *FileSystemDynamicConfiguration) PublishConfig(key string, group string, value string) error {
- path := fsdc.GetPath(key, group)
- return fsdc.write2File(path, value)
+ tmpPath := fsdc.GetPath(key, group)
+ return fsdc.write2File(tmpPath, value)
}
// GetConfigKeysByGroup will return all keys with the group
func (fsdc *FileSystemDynamicConfiguration) GetConfigKeysByGroup(group string) (*gxset.HashSet, error) {
- path := fsdc.GetPath("", group)
+ tmpPath := fsdc.GetPath("", group)
r := gxset.NewSet()
- fileInfo, _ := ioutil.ReadDir(path)
+ fileInfo, _ := ioutil.ReadDir(tmpPath)
for _, file := range fileInfo {
// list file
@@ -185,8 +182,8 @@
// RemoveConfig will remove the config whit hte (key, group)
func (fsdc *FileSystemDynamicConfiguration) RemoveConfig(key string, group string) error {
- path := fsdc.GetPath(key, group)
- _, err := fsdc.deleteDelay(path)
+ tmpPath := fsdc.GetPath(key, group)
+ _, err := fsdc.deleteDelay(tmpPath)
return err
}
@@ -261,9 +258,9 @@
// This uses an OS-specific method for discovering the home directory.
// An error is returned if a home directory cannot be detected.
func Home() (string, error) {
- user, err := user.Current()
+ currentUser, err := user.Current()
if nil == err {
- return user.HomeDir, nil
+ return currentUser.HomeDir, nil
}
// cross compile support
@@ -299,9 +296,9 @@
func homeWindows() (string, error) {
drive := os.Getenv("HOMEDRIVE")
- path := os.Getenv("HOMEPATH")
- home := drive + path
- if drive == "" || path == "" {
+ homePath := os.Getenv("HOMEPATH")
+ home := drive + homePath
+ if drive == "" || homePath == "" {
home = os.Getenv("USERPROFILE")
}
if home == "" {
diff --git a/config_center/file/impl_test.go b/config_center/file/impl_test.go
index 5889295..e912cb7 100644
--- a/config_center/file/impl_test.go
+++ b/config_center/file/impl_test.go
@@ -42,7 +42,7 @@
urlString := "registry://127.0.0.1:2181"
regurl, err := common.NewURL(urlString)
assert.NoError(t, err)
- dc, err := extension.GetConfigCenterFactory("file").GetDynamicConfiguration(®url)
+ dc, err := extension.GetConfigCenterFactory("file").GetDynamicConfiguration(regurl)
assert.NoError(t, err)
return dc.(*FileSystemDynamicConfiguration), err
diff --git a/config_center/nacos/client.go b/config_center/nacos/client.go
index acfe260..f3942c0 100644
--- a/config_center/nacos/client.go
+++ b/config_center/nacos/client.go
@@ -122,7 +122,7 @@
return perrors.WithMessagef(nil, "newNacosClient(address:%+v)", url.PrimitiveURL)
}
-func newNacosClient(name string, nacosAddrs []string, timeout time.Duration, url common.URL) (*NacosClient, error) {
+func newNacosClient(name string, nacosAddrs []string, timeout time.Duration, url *common.URL) (*NacosClient, error) {
var (
err error
n *NacosClient
@@ -149,8 +149,8 @@
return n, nil
}
-func initNacosConfigClient(nacosAddrs []string, timeout time.Duration, url common.URL) (config_client.IConfigClient, error) {
- svrConfList := []nacosconst.ServerConfig{}
+func initNacosConfigClient(nacosAddrs []string, timeout time.Duration, url *common.URL) (config_client.IConfigClient, error) {
+ var svrConfList []nacosconst.ServerConfig
for _, nacosAddr := range nacosAddrs {
split := strings.Split(nacosAddr, ":")
port, err := strconv.ParseUint(split[1], 10, 64)
diff --git a/config_center/nacos/client_test.go b/config_center/nacos/client_test.go
index 01319f3..2ce3e37 100644
--- a/config_center/nacos/client_test.go
+++ b/config_center/nacos/client_test.go
@@ -36,7 +36,7 @@
nacosURL := strings.ReplaceAll(server.URL, "http", "registry")
registryUrl, _ := common.NewURL(nacosURL)
c := &nacosDynamicConfiguration{
- url: ®istryUrl,
+ url: registryUrl,
done: make(chan struct{}),
}
err := ValidateNacosClient(c, WithNacosName(nacosClientName))
@@ -59,7 +59,7 @@
nacosURL := "registry://" + server.Listener.Addr().String()
registryUrl, _ := common.NewURL(nacosURL)
c := &nacosDynamicConfiguration{
- url: ®istryUrl,
+ url: registryUrl,
done: make(chan struct{}),
}
var client *NacosClient
@@ -93,7 +93,7 @@
registryUrl, err := common.NewURL(nacosURL)
assert.NoError(t, err)
c := &nacosDynamicConfiguration{
- url: ®istryUrl,
+ url: registryUrl,
done: make(chan struct{}),
}
err = ValidateNacosClient(c, WithNacosName(nacosClientName))
diff --git a/config_center/nacos/impl.go b/config_center/nacos/impl.go
index be94b9a..7c67930 100644
--- a/config_center/nacos/impl.go
+++ b/config_center/nacos/impl.go
@@ -186,8 +186,8 @@
}
// GetUrl Get Url
-func (n *nacosDynamicConfiguration) GetUrl() common.URL {
- return *n.url
+func (n *nacosDynamicConfiguration) GetUrl() *common.URL {
+ return n.url
}
// Destroy Destroy configuration instance
diff --git a/config_center/nacos/impl_test.go b/config_center/nacos/impl_test.go
index 88d200e..40efa5f 100644
--- a/config_center/nacos/impl_test.go
+++ b/config_center/nacos/impl_test.go
@@ -73,7 +73,7 @@
nacosURL := strings.ReplaceAll(server.URL, "http", "registry")
regurl, _ := common.NewURL(nacosURL)
factory := &nacosDynamicConfigurationFactory{}
- nacosConfiguration, err := factory.GetDynamicConfiguration(®url)
+ nacosConfiguration, err := factory.GetDynamicConfiguration(regurl)
assert.NoError(t, err)
nacosConfiguration.SetParser(&parser.DefaultConfigurationParser{})
@@ -105,7 +105,7 @@
nacosURL := strings.ReplaceAll(ts.URL, "http", "registry")
regurl, _ := common.NewURL(nacosURL)
- nacosConfiguration, err := newNacosDynamicConfiguration(®url)
+ nacosConfiguration, err := newNacosDynamicConfiguration(regurl)
assert.NoError(t, err)
nacosConfiguration.SetParser(&parser.DefaultConfigurationParser{})
diff --git a/config_center/parser/configuration_parser.go b/config_center/parser/configuration_parser.go
index f794221..b104d3d 100644
--- a/config_center/parser/configuration_parser.go
+++ b/config_center/parser/configuration_parser.go
@@ -144,14 +144,14 @@
if err != nil {
return nil, perrors.WithStack(err)
}
- urls = append(urls, &url)
+ urls = append(urls, url)
}
} else {
url, err := common.NewURL(urlStr)
if err != nil {
return nil, perrors.WithStack(err)
}
- urls = append(urls, &url)
+ urls = append(urls, url)
}
}
return urls, nil
@@ -192,7 +192,7 @@
if err != nil {
return nil, perrors.WithStack(err)
}
- urls = append(urls, &url)
+ urls = append(urls, url)
}
}
return urls, nil
diff --git a/config_center/zookeeper/impl.go b/config_center/zookeeper/impl.go
index 485abcb..17812e9 100644
--- a/config_center/zookeeper/impl.go
+++ b/config_center/zookeeper/impl.go
@@ -183,8 +183,8 @@
return c.done
}
-func (c *zookeeperDynamicConfiguration) GetUrl() common.URL {
- return *c.url
+func (c *zookeeperDynamicConfiguration) GetUrl() *common.URL {
+ return c.url
}
func (c *zookeeperDynamicConfiguration) Destroy() {
diff --git a/config_center/zookeeper/impl_test.go b/config_center/zookeeper/impl_test.go
index ecc3527..d4a9de4 100644
--- a/config_center/zookeeper/impl_test.go
+++ b/config_center/zookeeper/impl_test.go
@@ -50,7 +50,7 @@
assert.NoError(t, err)
regurl.AddParam(constant.REGISTRY_TIMEOUT_KEY, "15s")
zkFactory := &zookeeperDynamicConfigurationFactory{}
- reg, err := zkFactory.GetDynamicConfiguration(®url)
+ reg, err := zkFactory.GetDynamicConfiguration(regurl)
zreg, ok := reg.(*zookeeperDynamicConfiguration)
assert.True(t, ok)
assert.NoError(t, err)
diff --git a/filter/filter_impl/auth/consumer_sign.go b/filter/filter_impl/auth/consumer_sign.go
index 945cf3e..823db82 100644
--- a/filter/filter_impl/auth/consumer_sign.go
+++ b/filter/filter_impl/auth/consumer_sign.go
@@ -42,8 +42,8 @@
logger.Infof("invoking ConsumerSign filter.")
url := invoker.GetUrl()
- err := doAuthWork(&url, func(authenticator filter.Authenticator) error {
- return authenticator.Sign(invocation, &url)
+ err := doAuthWork(url, func(authenticator filter.Authenticator) error {
+ return authenticator.Sign(invocation, url)
})
if err != nil {
panic(fmt.Sprintf("Sign for invocation %s # %s failed", url.ServiceKey(), invocation.MethodName()))
diff --git a/filter/filter_impl/auth/default_authenticator_test.go b/filter/filter_impl/auth/default_authenticator_test.go
index 8b0fb6b..37c7e9d 100644
--- a/filter/filter_impl/auth/default_authenticator_test.go
+++ b/filter/filter_impl/auth/default_authenticator_test.go
@@ -48,7 +48,7 @@
}{"YUYU", 1}}
inv := invocation.NewRPCInvocation("test", parmas, nil)
requestTime := strconv.Itoa(int(time.Now().Unix() * 1000))
- signature, _ := getSignature(&testurl, inv, secret, requestTime)
+ signature, _ := getSignature(testurl, inv, secret, requestTime)
var authenticator = &DefaultAuthenticator{}
@@ -58,7 +58,7 @@
constant.REQUEST_TIMESTAMP_KEY: requestTime,
constant.AK_KEY: access,
})
- err := authenticator.Authenticate(invcation, &testurl)
+ err := authenticator.Authenticate(invcation, testurl)
assert.Nil(t, err)
// modify the params
invcation = invocation.NewRPCInvocation("test", parmas[:1], map[string]interface{}{
@@ -67,7 +67,7 @@
constant.REQUEST_TIMESTAMP_KEY: requestTime,
constant.AK_KEY: access,
})
- err = authenticator.Authenticate(invcation, &testurl)
+ err = authenticator.Authenticate(invcation, testurl)
assert.NotNil(t, err)
}
@@ -79,7 +79,7 @@
testurl.SetParam(constant.SECRET_ACCESS_KEY_KEY, "skey")
testurl.SetParam(constant.PARAMTER_SIGNATURE_ENABLE_KEY, "false")
inv := invocation.NewRPCInvocation("test", []interface{}{"OK"}, nil)
- _ = authenticator.Sign(inv, &testurl)
+ _ = authenticator.Sign(inv, testurl)
assert.NotEqual(t, inv.AttachmentsByKey(constant.REQUEST_SIGNATURE_KEY, ""), "")
assert.NotEqual(t, inv.AttachmentsByKey(constant.CONSUMER, ""), "")
assert.NotEqual(t, inv.AttachmentsByKey(constant.REQUEST_TIMESTAMP_KEY, ""), "")
@@ -124,7 +124,7 @@
})
secret := "dubbo"
current := strconv.Itoa(int(time.Now().Unix() * 1000))
- signature, _ := getSignature(&testurl, inv, secret, current)
+ signature, _ := getSignature(testurl, inv, secret, current)
requestString := fmt.Sprintf(constant.SIGNATURE_STRING_FORMAT,
testurl.ColonSeparatedKey(), inv.MethodName(), secret, current)
s, _ := SignWithParams(inv.Arguments(), requestString, secret)
@@ -138,7 +138,7 @@
inv := invocation.NewRPCInvocation("test", []interface{}{"OK"}, nil)
secret := "dubbo"
current := strconv.Itoa(int(time.Now().Unix() * 1000))
- signature, _ := getSignature(&testurl, inv, secret, current)
+ signature, _ := getSignature(testurl, inv, secret, current)
requestString := fmt.Sprintf(constant.SIGNATURE_STRING_FORMAT,
testurl.ColonSeparatedKey(), inv.MethodName(), secret, current)
s := Sign(requestString, secret)
diff --git a/filter/filter_impl/auth/provider_auth.go b/filter/filter_impl/auth/provider_auth.go
index d5f5db3..774fdb2 100644
--- a/filter/filter_impl/auth/provider_auth.go
+++ b/filter/filter_impl/auth/provider_auth.go
@@ -42,8 +42,8 @@
logger.Infof("invoking providerAuth filter.")
url := invoker.GetUrl()
- err := doAuthWork(&url, func(authenticator filter.Authenticator) error {
- return authenticator.Authenticate(invocation, &url)
+ err := doAuthWork(url, func(authenticator filter.Authenticator) error {
+ return authenticator.Authenticate(invocation, url)
})
if err != nil {
logger.Infof("auth the request: %v occur exception, cause: %s", invocation, err.Error())
diff --git a/filter/filter_impl/auth/provider_auth_test.go b/filter/filter_impl/auth/provider_auth_test.go
index f6ebfcd..dc130b5 100644
--- a/filter/filter_impl/auth/provider_auth_test.go
+++ b/filter/filter_impl/auth/provider_auth_test.go
@@ -52,7 +52,7 @@
}
inv := invocation.NewRPCInvocation("test", parmas, nil)
requestTime := strconv.Itoa(int(time.Now().Unix() * 1000))
- signature, _ := getSignature(&url, inv, secret, requestTime)
+ signature, _ := getSignature(url, inv, secret, requestTime)
inv = invocation.NewRPCInvocation("test", []interface{}{"OK"}, map[string]interface{}{
constant.REQUEST_SIGNATURE_KEY: signature,
diff --git a/filter/filter_impl/echo_filter_test.go b/filter/filter_impl/echo_filter_test.go
index b821a1a..f2ec81a 100644
--- a/filter/filter_impl/echo_filter_test.go
+++ b/filter/filter_impl/echo_filter_test.go
@@ -34,10 +34,10 @@
func TestEchoFilterInvoke(t *testing.T) {
filter := GetFilter()
- result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(common.URL{}), invocation.NewRPCInvocation("$echo", []interface{}{"OK"}, nil))
+ result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(&common.URL{}), invocation.NewRPCInvocation("$echo", []interface{}{"OK"}, nil))
assert.Equal(t, "OK", result.Result())
- result = filter.Invoke(context.Background(), protocol.NewBaseInvoker(common.URL{}), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, nil))
+ result = filter.Invoke(context.Background(), protocol.NewBaseInvoker(&common.URL{}), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, nil))
assert.Nil(t, result.Error())
assert.Nil(t, result.Result())
}
diff --git a/filter/filter_impl/execute_limit_filter_test.go b/filter/filter_impl/execute_limit_filter_test.go
index 953f5e1..2aebcaa 100644
--- a/filter/filter_impl/execute_limit_filter_test.go
+++ b/filter/filter_impl/execute_limit_filter_test.go
@@ -44,7 +44,7 @@
limitFilter := GetExecuteLimitFilter()
- result := limitFilter.Invoke(context.Background(), protocol.NewBaseInvoker(*invokeUrl), invoc)
+ result := limitFilter.Invoke(context.Background(), protocol.NewBaseInvoker(invokeUrl), invoc)
assert.NotNil(t, result)
assert.Nil(t, result.Error())
}
@@ -61,7 +61,7 @@
limitFilter := GetExecuteLimitFilter()
- result := limitFilter.Invoke(context.Background(), protocol.NewBaseInvoker(*invokeUrl), invoc)
+ result := limitFilter.Invoke(context.Background(), protocol.NewBaseInvoker(invokeUrl), invoc)
assert.NotNil(t, result)
assert.Nil(t, result.Error())
}
@@ -78,7 +78,7 @@
limitFilter := GetExecuteLimitFilter()
- result := limitFilter.Invoke(context.Background(), protocol.NewBaseInvoker(*invokeUrl), invoc)
+ result := limitFilter.Invoke(context.Background(), protocol.NewBaseInvoker(invokeUrl), invoc)
assert.NotNil(t, result)
assert.Nil(t, result.Error())
}
diff --git a/filter/filter_impl/graceful_shutdown_filter_test.go b/filter/filter_impl/graceful_shutdown_filter_test.go
index 220ef6f..447a557 100644
--- a/filter/filter_impl/graceful_shutdown_filter_test.go
+++ b/filter/filter_impl/graceful_shutdown_filter_test.go
@@ -54,7 +54,7 @@
assert.Equal(t, extension.GetRejectedExecutionHandler(constant.DEFAULT_KEY),
shutdownFilter.getRejectHandler())
- result := shutdownFilter.Invoke(context.Background(), protocol.NewBaseInvoker(*invokeUrl), invoc)
+ result := shutdownFilter.Invoke(context.Background(), protocol.NewBaseInvoker(invokeUrl), invoc)
assert.NotNil(t, result)
assert.Nil(t, result.Error())
@@ -65,7 +65,7 @@
shutdownFilter.shutdownConfig = providerConfig.ShutdownConfig
assert.True(t, shutdownFilter.rejectNewRequest())
- result = shutdownFilter.OnResponse(nil, nil, protocol.NewBaseInvoker(*invokeUrl), invoc)
+ result = shutdownFilter.OnResponse(nil, nil, protocol.NewBaseInvoker(invokeUrl), invoc)
rejectHandler := &common2.OnlyLogRejectedExecutionHandler{}
extension.SetRejectedExecutionHandler("mock", func() filter.RejectedExecutionHandler {
diff --git a/filter/filter_impl/hystrix_filter_test.go b/filter/filter_impl/hystrix_filter_test.go
index eebbae5..4973ce7 100644
--- a/filter/filter_impl/hystrix_filter_test.go
+++ b/filter/filter_impl/hystrix_filter_test.go
@@ -18,6 +18,7 @@
import (
"context"
+ "fmt"
"regexp"
"testing"
)
@@ -29,6 +30,8 @@
)
import (
+ "github.com/apache/dubbo-go/common"
+ "github.com/apache/dubbo-go/common/constant"
"github.com/apache/dubbo-go/protocol"
"github.com/apache/dubbo-go/protocol/invocation"
)
@@ -147,7 +150,11 @@
func TestHystrixFilterInvokeSuccess(t *testing.T) {
hf := &HystrixFilter{}
- result := hf.Invoke(context.Background(), &testMockSuccessInvoker{}, &invocation.RPCInvocation{})
+ testUrl, err := common.NewURL(
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ assert.NoError(t, err)
+ testInvoker := testMockSuccessInvoker{*protocol.NewBaseInvoker(testUrl)}
+ result := hf.Invoke(context.Background(), &testInvoker, &invocation.RPCInvocation{})
assert.NotNil(t, result)
assert.NoError(t, result.Error())
assert.NotNil(t, result.Result())
@@ -155,7 +162,11 @@
func TestHystrixFilterInvokeFail(t *testing.T) {
hf := &HystrixFilter{}
- result := hf.Invoke(context.Background(), &testMockFailInvoker{}, &invocation.RPCInvocation{})
+ testUrl, err := common.NewURL(
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ assert.NoError(t, err)
+ testInvoker := testMockFailInvoker{*protocol.NewBaseInvoker(testUrl)}
+ result := hf.Invoke(context.Background(), &testInvoker, &invocation.RPCInvocation{})
assert.NotNil(t, result)
assert.Error(t, result.Error())
}
@@ -167,7 +178,11 @@
resChan := make(chan protocol.Result, 50)
for i := 0; i < 50; i++ {
go func() {
- result := hf.Invoke(context.Background(), &testMockFailInvoker{}, &invocation.RPCInvocation{})
+ testUrl, err := common.NewURL(
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ assert.NoError(t, err)
+ testInvoker := testMockSuccessInvoker{*protocol.NewBaseInvoker(testUrl)}
+ result := hf.Invoke(context.Background(), &testInvoker, &invocation.RPCInvocation{})
resChan <- result
}()
}
@@ -192,7 +207,11 @@
resChan := make(chan protocol.Result, 50)
for i := 0; i < 50; i++ {
go func() {
- result := hf.Invoke(context.Background(), &testMockFailInvoker{}, &invocation.RPCInvocation{})
+ testUrl, err := common.NewURL(
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ assert.NoError(t, err)
+ testInvoker := testMockSuccessInvoker{*protocol.NewBaseInvoker(testUrl)}
+ result := hf.Invoke(context.Background(), &testInvoker, &invocation.RPCInvocation{})
resChan <- result
}()
}
diff --git a/filter/filter_impl/sentinel_filter.go b/filter/filter_impl/sentinel_filter.go
index 86d6460..aec814d 100644
--- a/filter/filter_impl/sentinel_filter.go
+++ b/filter/filter_impl/sentinel_filter.go
@@ -229,7 +229,7 @@
return true
}
-func getColonSeparatedKey(url common.URL) string {
+func getColonSeparatedKey(url *common.URL) string {
return fmt.Sprintf("%s:%s:%s",
url.Service(),
url.GetParam(constant.GROUP_KEY, ""),
diff --git a/filter/filter_impl/token_filter_test.go b/filter/filter_impl/token_filter_test.go
index cd1bba3..9ef8c98 100644
--- a/filter/filter_impl/token_filter_test.go
+++ b/filter/filter_impl/token_filter_test.go
@@ -43,7 +43,7 @@
attch := make(map[string]interface{}, 0)
attch[constant.TOKEN_KEY] = "ori_key"
result := filter.Invoke(context.Background(),
- protocol.NewBaseInvoker(*url),
+ protocol.NewBaseInvoker(url),
invocation.NewRPCInvocation("MethodName",
[]interface{}{"OK"}, attch))
assert.Nil(t, result.Error())
@@ -56,7 +56,7 @@
testUrl := common.URL{}
attch := make(map[string]interface{}, 0)
attch[constant.TOKEN_KEY] = "ori_key"
- result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
+ result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(&testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
assert.Nil(t, result.Error())
assert.Nil(t, result.Result())
}
@@ -68,7 +68,7 @@
common.WithParams(url.Values{}),
common.WithParamsValue(constant.TOKEN_KEY, "ori_key"))
attch := make(map[string]interface{}, 0)
- result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(*testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
+ result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
assert.NotNil(t, result.Error())
}
@@ -81,6 +81,6 @@
attch := make(map[string]interface{}, 0)
attch[constant.TOKEN_KEY] = "err_key"
result := filter.Invoke(context.Background(),
- protocol.NewBaseInvoker(*testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
+ protocol.NewBaseInvoker(testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
assert.NotNil(t, result.Error())
}
diff --git a/filter/filter_impl/tps/tps_limiter_method_service.go b/filter/filter_impl/tps/tps_limiter_method_service.go
index 5761579..f0c2764 100644
--- a/filter/filter_impl/tps/tps_limiter_method_service.go
+++ b/filter/filter_impl/tps/tps_limiter_method_service.go
@@ -120,7 +120,7 @@
// The key point is how to keep thread-safe
// This implementation use concurrent map + loadOrStore to make implementation thread-safe
// You can image that even multiple threads create limiter, but only one could store the limiter into tpsState
-func (limiter MethodServiceTpsLimiterImpl) IsAllowable(url common.URL, invocation protocol.Invocation) bool {
+func (limiter MethodServiceTpsLimiterImpl) IsAllowable(url *common.URL, invocation protocol.Invocation) bool {
methodConfigPrefix := "methods." + invocation.MethodName() + "."
@@ -176,7 +176,7 @@
// If we can convert the methodLevelConfig to int64, return;
// Or, we will try to look up server-level configuration and then convert it to int64
func getLimitConfig(methodLevelConfig string,
- url common.URL,
+ url *common.URL,
invocation protocol.Invocation,
configKey string,
defaultVal string) int64 {
diff --git a/filter/filter_impl/tps/tps_limiter_method_service_test.go b/filter/filter_impl/tps/tps_limiter_method_service_test.go
index 61f28e4..7435d9b 100644
--- a/filter/filter_impl/tps/tps_limiter_method_service_test.go
+++ b/filter/filter_impl/tps/tps_limiter_method_service_test.go
@@ -57,7 +57,7 @@
})
limiter := GetMethodServiceTpsLimiter()
- result := limiter.IsAllowable(*invokeUrl, invoc)
+ result := limiter.IsAllowable(invokeUrl, invoc)
assert.True(t, result)
}
@@ -73,7 +73,7 @@
common.WithParamsValue(constant.TPS_LIMIT_RATE_KEY, ""))
limiter := GetMethodServiceTpsLimiter()
- result := limiter.IsAllowable(*invokeUrl, invoc)
+ result := limiter.IsAllowable(invokeUrl, invoc)
assert.True(t, result)
}
@@ -106,7 +106,7 @@
})
limiter := GetMethodServiceTpsLimiter()
- result := limiter.IsAllowable(*invokeUrl, invoc)
+ result := limiter.IsAllowable(invokeUrl, invoc)
assert.True(t, result)
}
@@ -136,7 +136,7 @@
})
limiter := GetMethodServiceTpsLimiter()
- result := limiter.IsAllowable(*invokeUrl, invoc)
+ result := limiter.IsAllowable(invokeUrl, invoc)
assert.True(t, result)
}
diff --git a/filter/filter_impl/tps/tps_limiter_mock.go b/filter/filter_impl/tps/tps_limiter_mock.go
index b49084f..34c2790 100644
--- a/filter/filter_impl/tps/tps_limiter_mock.go
+++ b/filter/filter_impl/tps/tps_limiter_mock.go
@@ -58,7 +58,7 @@
}
// IsAllowable mocks base method
-func (m *MockTpsLimiter) IsAllowable(arg0 common.URL, arg1 protocol.Invocation) bool {
+func (m *MockTpsLimiter) IsAllowable(arg0 *common.URL, arg1 protocol.Invocation) bool {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "IsAllowable", arg0, arg1)
ret0, _ := ret[0].(bool)
diff --git a/filter/filter_impl/tps_limit_filter_test.go b/filter/filter_impl/tps_limit_filter_test.go
index da0fc48..88e7781 100644
--- a/filter/filter_impl/tps_limit_filter_test.go
+++ b/filter/filter_impl/tps_limit_filter_test.go
@@ -47,7 +47,7 @@
attch := make(map[string]interface{}, 0)
result := tpsFilter.Invoke(context.Background(),
- protocol.NewBaseInvoker(*invokeUrl),
+ protocol.NewBaseInvoker(invokeUrl),
invocation.NewRPCInvocation("MethodName",
[]interface{}{"OK"}, attch))
assert.Nil(t, result.Error())
@@ -71,7 +71,7 @@
attch := make(map[string]interface{}, 0)
result := tpsFilter.Invoke(context.Background(),
- protocol.NewBaseInvoker(*invokeUrl),
+ protocol.NewBaseInvoker(invokeUrl),
invocation.NewRPCInvocation("MethodName",
[]interface{}{"OK"}, attch))
assert.Nil(t, result.Error())
@@ -102,7 +102,9 @@
attch := make(map[string]interface{}, 0)
result := tpsFilter.Invoke(context.Background(),
- protocol.NewBaseInvoker(*invokeUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
+ protocol.NewBaseInvoker(
+
+ invokeUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
assert.Nil(t, result.Error())
assert.Nil(t, result.Result())
}
diff --git a/filter/handler/rejected_execution_handler_mock.go b/filter/handler/rejected_execution_handler_mock.go
index bff5476..5f2f458 100644
--- a/filter/handler/rejected_execution_handler_mock.go
+++ b/filter/handler/rejected_execution_handler_mock.go
@@ -58,7 +58,7 @@
}
// RejectedExecution mocks base method
-func (m *MockRejectedExecutionHandler) RejectedExecution(url common.URL, invocation protocol.Invocation) protocol.Result {
+func (m *MockRejectedExecutionHandler) RejectedExecution(url *common.URL, invocation protocol.Invocation) protocol.Result {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RejectedExecution", url, invocation)
ret0, _ := ret[0].(protocol.Result)
diff --git a/filter/handler/rejected_execution_handler_only_log.go b/filter/handler/rejected_execution_handler_only_log.go
index 52ac176..5242b5b 100644
--- a/filter/handler/rejected_execution_handler_only_log.go
+++ b/filter/handler/rejected_execution_handler_only_log.go
@@ -63,7 +63,7 @@
}
// RejectedExecution will do nothing, it only log the invocation.
-func (handler *OnlyLogRejectedExecutionHandler) RejectedExecution(url common.URL,
+func (handler *OnlyLogRejectedExecutionHandler) RejectedExecution(url *common.URL,
_ protocol.Invocation) protocol.Result {
logger.Errorf("The invocation was rejected. url: %s", url.String())
diff --git a/filter/handler/rejected_execution_handler_only_log_test.go b/filter/handler/rejected_execution_handler_only_log_test.go
index 409f09f..7aa4aff 100644
--- a/filter/handler/rejected_execution_handler_only_log_test.go
+++ b/filter/handler/rejected_execution_handler_only_log_test.go
@@ -31,5 +31,5 @@
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
common.WithParamsValue(constant.INTERFACE_KEY, "methodName"))
- handler.RejectedExecution(*invokeUrl, nil)
+ handler.RejectedExecution(invokeUrl, nil)
}
diff --git a/filter/rejected_execution_handler.go b/filter/rejected_execution_handler.go
index 3d1e1c1..73ac3d3 100644
--- a/filter/rejected_execution_handler.go
+++ b/filter/rejected_execution_handler.go
@@ -33,5 +33,5 @@
type RejectedExecutionHandler interface {
// RejectedExecution will be called if the invocation was rejected by some component.
- RejectedExecution(url common.URL, invocation protocol.Invocation) protocol.Result
+ RejectedExecution(url *common.URL, invocation protocol.Invocation) protocol.Result
}
diff --git a/filter/tps_limiter.go b/filter/tps_limiter.go
index 8385d7b..6f2466c 100644
--- a/filter/tps_limiter.go
+++ b/filter/tps_limiter.go
@@ -35,5 +35,5 @@
*/
type TpsLimiter interface {
// IsAllowable will check whether this invocation should be enabled for further process
- IsAllowable(common.URL, protocol.Invocation) bool
+ IsAllowable(*common.URL, protocol.Invocation) bool
}
diff --git a/metadata/definition/definition.go b/metadata/definition/definition.go
index dbbc0c8..a032313 100644
--- a/metadata/definition/definition.go
+++ b/metadata/definition/definition.go
@@ -93,7 +93,7 @@
}
// BuildServiceDefinition can build service definition which will be used to describe a service
-func BuildServiceDefinition(service common.Service, url common.URL) *ServiceDefinition {
+func BuildServiceDefinition(service common.Service, url *common.URL) *ServiceDefinition {
sd := &ServiceDefinition{}
sd.CanonicalName = url.Service()
diff --git a/metadata/identifier/service_metadata_identifier.go b/metadata/identifier/service_metadata_identifier.go
index b9e6596..3035cf3 100644
--- a/metadata/identifier/service_metadata_identifier.go
+++ b/metadata/identifier/service_metadata_identifier.go
@@ -32,7 +32,7 @@
// NewServiceMetadataIdentifier create instance.
// The ServiceInterface is the @url.Service()
// other parameters are read from @url
-func NewServiceMetadataIdentifier(url common.URL) *ServiceMetadataIdentifier {
+func NewServiceMetadataIdentifier(url *common.URL) *ServiceMetadataIdentifier {
return &ServiceMetadataIdentifier{
BaseMetadataIdentifier: BaseMetadataIdentifier{
ServiceInterface: url.Service(),
diff --git a/metadata/report/consul/report.go b/metadata/report/consul/report.go
index eb2bdc2..e211f7f 100644
--- a/metadata/report/consul/report.go
+++ b/metadata/report/consul/report.go
@@ -61,7 +61,7 @@
}
// SaveServiceMetadata saves the metadata.
-func (m *consulMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url common.URL) error {
+func (m *consulMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url *common.URL) error {
kv := &consul.KVPair{Key: metadataIdentifier.GetIdentifierKey(), Value: []byte(url.String())}
_, err := m.client.KV().Put(kv, nil)
return err
diff --git a/metadata/report/consul/report_test.go b/metadata/report/consul/report_test.go
index e07a742..13d0c41 100644
--- a/metadata/report/consul/report_test.go
+++ b/metadata/report/consul/report_test.go
@@ -100,7 +100,7 @@
assert.NoError(suite.t, err)
}
-func (suite *consulMetadataReportTestSuite) testSaveServiceMetadata(url common.URL) {
+func (suite *consulMetadataReportTestSuite) testSaveServiceMetadata(url *common.URL) {
serviceMi := newServiceMetadataIdentifier("provider")
err := suite.m.SaveServiceMetadata(serviceMi, url)
assert.NoError(suite.t, err)
@@ -119,7 +119,7 @@
assert.NoError(suite.t, err)
}
-func (suite *consulMetadataReportTestSuite) testSaveSubscribedData(url common.URL) {
+func (suite *consulMetadataReportTestSuite) testSaveSubscribedData(url *common.URL) {
subscribeMi := newSubscribeMetadataIdentifier("provider")
urls := []string{url.String()}
bytes, _ := json.Marshal(urls)
@@ -152,10 +152,10 @@
suite := newConsulMetadataReportTestSuite(t, m)
suite.testStoreProviderMetadata()
suite.testStoreConsumerMetadata()
- suite.testSaveServiceMetadata(*url)
+ suite.testSaveServiceMetadata(url)
suite.testGetExportedURLs()
suite.testRemoveServiceMetadata()
- suite.testSaveSubscribedData(*url)
+ suite.testSaveSubscribedData(url)
suite.testGetSubscribedURLs()
suite.testGetServiceDefinition()
}
diff --git a/metadata/report/delegate/delegate_report.go b/metadata/report/delegate/delegate_report.go
index cdd29ab..836a8f9 100644
--- a/metadata/report/delegate/delegate_report.go
+++ b/metadata/report/delegate/delegate_report.go
@@ -94,7 +94,7 @@
// MetadataReport is a absolute delegate for MetadataReport
type MetadataReport struct {
- reportUrl common.URL
+ reportUrl *common.URL
syncReport bool
metadataReportRetry *metadataReportRetry
@@ -215,7 +215,7 @@
}
// SaveServiceMetadata will delegate to call remote metadata's sdk to save service metadata
-func (mr *MetadataReport) SaveServiceMetadata(identifier *identifier.ServiceMetadataIdentifier, url common.URL) error {
+func (mr *MetadataReport) SaveServiceMetadata(identifier *identifier.ServiceMetadataIdentifier, url *common.URL) error {
report := instance.GetMetadataReportInstance()
if mr.syncReport {
return report.SaveServiceMetadata(identifier, url)
@@ -241,7 +241,7 @@
}
// SaveSubscribedData will delegate to call remote metadata's sdk to save subscribed data
-func (mr *MetadataReport) SaveSubscribedData(identifier *identifier.SubscriberMetadataIdentifier, urls []common.URL) error {
+func (mr *MetadataReport) SaveSubscribedData(identifier *identifier.SubscriberMetadataIdentifier, urls []*common.URL) error {
urlStrList := make([]string, 0, len(urls))
for _, url := range urls {
urlStrList = append(urlStrList, url.String())
@@ -260,13 +260,13 @@
}
// GetSubscribedURLs will delegate to call remote metadata's sdk to get subscribed urls
-func (MetadataReport) GetSubscribedURLs(identifier *identifier.SubscriberMetadataIdentifier) ([]string, error) {
+func (mr *MetadataReport) GetSubscribedURLs(identifier *identifier.SubscriberMetadataIdentifier) ([]string, error) {
report := instance.GetMetadataReportInstance()
return report.GetSubscribedURLs(identifier)
}
// GetServiceDefinition will delegate to call remote metadata's sdk to get service definitions
-func (MetadataReport) GetServiceDefinition(identifier *identifier.MetadataIdentifier) (string, error) {
+func (mr *MetadataReport) GetServiceDefinition(identifier *identifier.MetadataIdentifier) (string, error) {
report := instance.GetMetadataReportInstance()
return report.GetServiceDefinition(identifier)
}
diff --git a/metadata/report/etcd/report.go b/metadata/report/etcd/report.go
index 097835c..1939b91 100644
--- a/metadata/report/etcd/report.go
+++ b/metadata/report/etcd/report.go
@@ -63,7 +63,7 @@
// SaveServiceMetadata will store the metadata
// metadata including the basic info of the server, service info, and other user custom info
-func (e *etcdMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url common.URL) error {
+func (e *etcdMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url *common.URL) error {
key := e.getNodeKey(metadataIdentifier)
return e.client.Create(key, url.String())
}
diff --git a/metadata/report/etcd/report_test.go b/metadata/report/etcd/report_test.go
index 5dd8780..28c0486 100644
--- a/metadata/report/etcd/report_test.go
+++ b/metadata/report/etcd/report_test.go
@@ -60,7 +60,7 @@
t.Fatal(err)
}
metadataReportFactory := &etcdMetadataReportFactory{}
- metadataReport := metadataReportFactory.CreateMetadataReport(&url)
+ metadataReport := metadataReportFactory.CreateMetadataReport(url)
assert.NotNil(t, metadataReport)
e.Close()
}
@@ -72,7 +72,7 @@
t.Fatal(err)
}
metadataReportFactory := &etcdMetadataReportFactory{}
- metadataReport := metadataReportFactory.CreateMetadataReport(&url)
+ metadataReport := metadataReportFactory.CreateMetadataReport(url)
assert.NotNil(t, metadataReport)
err = metadataReport.StoreConsumerMetadata(newMetadataIdentifier("consumer"), "consumer metadata")
diff --git a/metadata/report/nacos/report.go b/metadata/report/nacos/report.go
index d69913b..42e9859 100644
--- a/metadata/report/nacos/report.go
+++ b/metadata/report/nacos/report.go
@@ -69,7 +69,7 @@
}
// SaveServiceMetadata saves the metadata.
-func (n *nacosMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url common.URL) error {
+func (n *nacosMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url *common.URL) error {
return n.storeMetadata(vo.ConfigParam{
DataId: metadataIdentifier.GetIdentifierKey(),
Group: metadataIdentifier.Group,
diff --git a/metadata/report/nacos/report_test.go b/metadata/report/nacos/report_test.go
index be01eb2..b40b438 100644
--- a/metadata/report/nacos/report_test.go
+++ b/metadata/report/nacos/report_test.go
@@ -111,6 +111,6 @@
func newTestReport() report.MetadataReport {
regurl, _ := common.NewURL("registry://console.nacos.io:80", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
- res := extension.GetMetadataReportFactory("nacos").CreateMetadataReport(®url)
+ res := extension.GetMetadataReportFactory("nacos").CreateMetadataReport(regurl)
return res
}
diff --git a/metadata/report/report.go b/metadata/report/report.go
index 62a9055..dcb4142 100644
--- a/metadata/report/report.go
+++ b/metadata/report/report.go
@@ -38,7 +38,7 @@
// SaveServiceMetadata saves the metadata.
// Metadata includes the basic info of the server,
// service info, and other user custom info.
- SaveServiceMetadata(*identifier.ServiceMetadataIdentifier, common.URL) error
+ SaveServiceMetadata(*identifier.ServiceMetadataIdentifier, *common.URL) error
// RemoveServiceMetadata removes the metadata.
RemoveServiceMetadata(*identifier.ServiceMetadataIdentifier) error
diff --git a/metadata/report/zookeeper/report.go b/metadata/report/zookeeper/report.go
index 8f46bb0..5d5e740 100644
--- a/metadata/report/zookeeper/report.go
+++ b/metadata/report/zookeeper/report.go
@@ -63,7 +63,7 @@
}
// SaveServiceMetadata saves the metadata.
-func (m *zookeeperMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url common.URL) error {
+func (m *zookeeperMetadataReport) SaveServiceMetadata(metadataIdentifier *identifier.ServiceMetadataIdentifier, url *common.URL) error {
k := m.rootDir + metadataIdentifier.GetFilePathKey()
return m.client.CreateWithValue(k, []byte(url.String()))
}
diff --git a/metadata/report/zookeeper/report_test.go b/metadata/report/zookeeper/report_test.go
index a1e46e2..adedaaa 100644
--- a/metadata/report/zookeeper/report_test.go
+++ b/metadata/report/zookeeper/report_test.go
@@ -100,7 +100,7 @@
assert.NoError(suite.t, err)
}
-func (suite *zookeeperMetadataReportTestSuite) testSaveServiceMetadata(url common.URL) {
+func (suite *zookeeperMetadataReportTestSuite) testSaveServiceMetadata(url *common.URL) {
serviceMi := newServiceMetadataIdentifier("provider")
err := suite.m.SaveServiceMetadata(serviceMi, url)
assert.NoError(suite.t, err)
@@ -119,7 +119,7 @@
assert.NoError(suite.t, err)
}
-func (suite *zookeeperMetadataReportTestSuite) testSaveSubscribedData(url common.URL) {
+func (suite *zookeeperMetadataReportTestSuite) testSaveSubscribedData(url *common.URL) {
subscribeMi := newSubscribeMetadataIdentifier("provider")
urls := []string{url.String()}
bytes, _ := json.Marshal(urls)
@@ -153,10 +153,10 @@
suite := newZookeeperMetadataReportTestSuite(t, m)
suite.testStoreProviderMetadata()
suite.testStoreConsumerMetadata()
- suite.testSaveServiceMetadata(*url)
+ suite.testSaveServiceMetadata(url)
suite.testGetExportedURLs()
suite.testRemoveServiceMetadata()
- suite.testSaveSubscribedData(*url)
+ suite.testSaveSubscribedData(url)
suite.testGetSubscribedURLs()
suite.testGetServiceDefinition()
}
diff --git a/metadata/service/exporter/configurable/exporter_test.go b/metadata/service/exporter/configurable/exporter_test.go
index ceda255..2a5e646 100644
--- a/metadata/service/exporter/configurable/exporter_test.go
+++ b/metadata/service/exporter/configurable/exporter_test.go
@@ -65,9 +65,9 @@
t.Run("configurableExporter", func(t *testing.T) {
registryURL, _ := common.NewURL("service-discovery://localhost:12345")
subURL, _ := common.NewURL("dubbo://localhost:20003")
- registryURL.SubURL = &subURL
+ registryURL.SubURL = subURL
assert.Equal(t, false, exported.IsExported())
- assert.NoError(t, exported.Export(®istryURL))
+ assert.NoError(t, exported.Export(registryURL))
assert.Equal(t, true, exported.IsExported())
assert.Regexp(t, "dubbo://:20003/MetadataService*", exported.GetExportedURLs()[0].String())
exported.Unexport()
diff --git a/metadata/service/inmemory/metadata_service_proxy_factory.go b/metadata/service/inmemory/metadata_service_proxy_factory.go
index 1f8eeaa..becd804 100644
--- a/metadata/service/inmemory/metadata_service_proxy_factory.go
+++ b/metadata/service/inmemory/metadata_service_proxy_factory.go
@@ -50,7 +50,7 @@
u := urls[0]
p := extension.GetProtocol(u.Protocol)
- invoker := p.Refer(*u)
+ invoker := p.Refer(u)
return &MetadataServiceProxy{
invkr: invoker,
}
diff --git a/metadata/service/inmemory/metadata_service_proxy_factory_test.go b/metadata/service/inmemory/metadata_service_proxy_factory_test.go
index 96020e1..f5e519c 100644
--- a/metadata/service/inmemory/metadata_service_proxy_factory_test.go
+++ b/metadata/service/inmemory/metadata_service_proxy_factory_test.go
@@ -66,11 +66,11 @@
type mockProtocol struct {
}
-func (m mockProtocol) Export(invoker protocol.Invoker) protocol.Exporter {
+func (m mockProtocol) Export(protocol.Invoker) protocol.Exporter {
panic("implement me")
}
-func (m mockProtocol) Refer(url common.URL) protocol.Invoker {
+func (m mockProtocol) Refer(*common.URL) protocol.Invoker {
return &mockInvoker{}
}
@@ -81,7 +81,7 @@
type mockInvoker struct {
}
-func (m *mockInvoker) GetUrl() common.URL {
+func (m *mockInvoker) GetUrl() *common.URL {
panic("implement me")
}
diff --git a/metadata/service/inmemory/service.go b/metadata/service/inmemory/service.go
index 8269e69..d9cbd54 100644
--- a/metadata/service/inmemory/service.go
+++ b/metadata/service/inmemory/service.go
@@ -22,7 +22,6 @@
)
import (
- cm "github.com/Workiva/go-datastructures/common"
"github.com/Workiva/go-datastructures/slice/skip"
)
@@ -75,23 +74,6 @@
return metadataServiceInstance, nil
}
-// Comparator is defined as Comparator for skip list to compare the URL
-type Comparator common.URL
-
-// Compare is defined as Comparator for skip list to compare the URL
-func (c Comparator) Compare(comp cm.Comparator) int {
- a := common.URL(c).String()
- b := common.URL(comp.(Comparator)).String()
- switch {
- case a > b:
- return 1
- case a < b:
- return -1
- default:
- return 0
- }
-}
-
// addURL will add URL in memory
func (mts *MetadataService) addURL(targetMap *sync.Map, url *common.URL) bool {
var (
@@ -101,7 +83,7 @@
logger.Debug(url.ServiceKey())
if urlSet, loaded = targetMap.LoadOrStore(url.ServiceKey(), skip.New(uint64(0))); loaded {
mts.lock.RLock()
- wantedUrl := urlSet.(*skip.SkipList).Get(Comparator(*url))
+ wantedUrl := urlSet.(*skip.SkipList).Get(url)
if len(wantedUrl) > 0 && wantedUrl[0] != nil {
mts.lock.RUnlock()
return false
@@ -110,12 +92,12 @@
}
mts.lock.Lock()
// double chk
- wantedUrl := urlSet.(*skip.SkipList).Get(Comparator(*url))
+ wantedUrl := urlSet.(*skip.SkipList).Get(url)
if len(wantedUrl) > 0 && wantedUrl[0] != nil {
mts.lock.Unlock()
return false
}
- urlSet.(*skip.SkipList).Insert(Comparator(*url))
+ urlSet.(*skip.SkipList).Insert(url)
mts.lock.Unlock()
return true
}
@@ -124,7 +106,7 @@
func (mts *MetadataService) removeURL(targetMap *sync.Map, url *common.URL) {
if value, loaded := targetMap.Load(url.ServiceKey()); loaded {
mts.lock.Lock()
- value.(*skip.SkipList).Delete(Comparator(*url))
+ value.(*skip.SkipList).Delete(url)
mts.lock.Unlock()
mts.lock.RLock()
defer mts.lock.RUnlock()
@@ -135,13 +117,13 @@
}
// getAllService can return all the exportedUrlString except for metadataService
-func (mts *MetadataService) getAllService(services *sync.Map) []common.URL {
+func (mts *MetadataService) getAllService(services *sync.Map) []*common.URL {
// using skip list to dedup and sorting
- res := make([]common.URL, 0)
+ var res []*common.URL
services.Range(func(key, value interface{}) bool {
urls := value.(*skip.SkipList)
for i := uint64(0); i < urls.Len(); i++ {
- url := common.URL(urls.ByPosition(i).(Comparator))
+ url := urls.ByPosition(i).(*common.URL)
if url.GetParam(constant.INTERFACE_KEY, url.Path) != constant.METADATA_SERVICE_NAME {
res = append(res, url)
}
@@ -153,13 +135,13 @@
}
// getSpecifiedService can return specified service url by serviceKey
-func (mts *MetadataService) getSpecifiedService(services *sync.Map, serviceKey string, protocol string) []common.URL {
- res := make([]common.URL, 0)
+func (mts *MetadataService) getSpecifiedService(services *sync.Map, serviceKey string, protocol string) []*common.URL {
+ var res []*common.URL
serviceList, loaded := services.Load(serviceKey)
if loaded {
urls := serviceList.(*skip.SkipList)
for i := uint64(0); i < urls.Len(); i++ {
- url := common.URL(urls.ByPosition(i).(Comparator))
+ url := urls.ByPosition(i).(*common.URL)
if len(protocol) == 0 || protocol == constant.ANY_VALUE || url.Protocol == protocol || url.GetParam(constant.PROTOCOL_KEY, "") == protocol {
res = append(res, url)
}
@@ -170,34 +152,34 @@
}
// ExportURL can store the in memory
-func (mts *MetadataService) ExportURL(url common.URL) (bool, error) {
- return mts.addURL(mts.exportedServiceURLs, &url), nil
+func (mts *MetadataService) ExportURL(url *common.URL) (bool, error) {
+ return mts.addURL(mts.exportedServiceURLs, url), nil
}
// UnexportURL can remove the url store in memory
-func (mts *MetadataService) UnexportURL(url common.URL) error {
- mts.removeURL(mts.exportedServiceURLs, &url)
+func (mts *MetadataService) UnexportURL(url *common.URL) error {
+ mts.removeURL(mts.exportedServiceURLs, url)
return nil
}
// SubscribeURL can store the in memory
-func (mts *MetadataService) SubscribeURL(url common.URL) (bool, error) {
- return mts.addURL(mts.subscribedServiceURLs, &url), nil
+func (mts *MetadataService) SubscribeURL(url *common.URL) (bool, error) {
+ return mts.addURL(mts.subscribedServiceURLs, url), nil
}
// UnsubscribeURL can remove the url store in memory
-func (mts *MetadataService) UnsubscribeURL(url common.URL) error {
- mts.removeURL(mts.subscribedServiceURLs, &url)
+func (mts *MetadataService) UnsubscribeURL(url *common.URL) error {
+ mts.removeURL(mts.subscribedServiceURLs, url)
return nil
}
// PublishServiceDefinition: publish url's service metadata info, and write into memory
-func (mts *MetadataService) PublishServiceDefinition(url common.URL) error {
+func (mts *MetadataService) PublishServiceDefinition(url *common.URL) error {
interfaceName := url.GetParam(constant.INTERFACE_KEY, "")
isGeneric := url.GetParamBool(constant.GENERIC_KEY, false)
if len(interfaceName) > 0 && !isGeneric {
- service := common.ServiceMap.GetService(url.Protocol, url.GetParam(constant.BEAN_NAME_KEY, url.Service()))
- sd := definition.BuildServiceDefinition(*service, url)
+ tmpService := common.ServiceMap.GetService(url.Protocol, url.GetParam(constant.BEAN_NAME_KEY, url.Service()))
+ sd := definition.BuildServiceDefinition(*tmpService, url)
data, err := sd.ToBytes()
if err != nil {
logger.Errorf("publishProvider getServiceDescriptor error. providerUrl:%v , error:%v ", url, err)
@@ -221,7 +203,7 @@
}
// GetSubscribedURLs get all subscribedUrl
-func (mts *MetadataService) GetSubscribedURLs() ([]common.URL, error) {
+func (mts *MetadataService) GetSubscribedURLs() ([]*common.URL, error) {
return mts.getAllService(mts.subscribedServiceURLs), nil
}
@@ -239,7 +221,7 @@
}
// RefreshMetadata will always return true because it will be implement by remote service
-func (mts *MetadataService) RefreshMetadata(exportedRevision string, subscribedRevision string) (bool, error) {
+func (mts *MetadataService) RefreshMetadata(string, string) (bool, error) {
return true, nil
}
diff --git a/metadata/service/inmemory/service_proxy.go b/metadata/service/inmemory/service_proxy.go
index e2b2968..7e14293 100644
--- a/metadata/service/inmemory/service_proxy.go
+++ b/metadata/service/inmemory/service_proxy.go
@@ -88,34 +88,34 @@
return "", nil
}
-func (m *MetadataServiceProxy) ExportURL(url common.URL) (bool, error) {
+func (m *MetadataServiceProxy) ExportURL(url *common.URL) (bool, error) {
logger.Error("you should never invoke this implementation")
return false, nil
}
-func (m *MetadataServiceProxy) UnexportURL(url common.URL) error {
+func (m *MetadataServiceProxy) UnexportURL(url *common.URL) error {
logger.Error("you should never invoke this implementation")
return nil
}
-func (m *MetadataServiceProxy) SubscribeURL(url common.URL) (bool, error) {
+func (m *MetadataServiceProxy) SubscribeURL(url *common.URL) (bool, error) {
logger.Error("you should never invoke this implementation")
return false, nil
}
-func (m *MetadataServiceProxy) UnsubscribeURL(url common.URL) error {
+func (m *MetadataServiceProxy) UnsubscribeURL(url *common.URL) error {
logger.Error("you should never invoke this implementation")
return nil
}
-func (m *MetadataServiceProxy) PublishServiceDefinition(url common.URL) error {
+func (m *MetadataServiceProxy) PublishServiceDefinition(url *common.URL) error {
logger.Error("you should never invoke this implementation")
return nil
}
-func (m *MetadataServiceProxy) GetSubscribedURLs() ([]common.URL, error) {
+func (m *MetadataServiceProxy) GetSubscribedURLs() ([]*common.URL, error) {
logger.Error("you should never invoke this implementation")
- return []common.URL{}, nil
+ return nil, nil
}
func (m *MetadataServiceProxy) GetServiceDefinition(interfaceName string, group string, version string) (string, error) {
diff --git a/metadata/service/inmemory/service_proxy_test.go b/metadata/service/inmemory/service_proxy_test.go
index 0d75517..f7fc8fd 100644
--- a/metadata/service/inmemory/service_proxy_test.go
+++ b/metadata/service/inmemory/service_proxy_test.go
@@ -49,16 +49,16 @@
func TestNewMetadataService(t *testing.T) {
pxy := createPxy()
pxy.ServiceName()
- pxy.PublishServiceDefinition(common.URL{})
+ pxy.PublishServiceDefinition(&common.URL{})
pxy.GetServiceDefinition(constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE)
pxy.Version()
pxy.GetSubscribedURLs()
- pxy.UnsubscribeURL(common.URL{})
+ pxy.UnsubscribeURL(&common.URL{})
pxy.GetServiceDefinitionByServiceKey("any")
- pxy.ExportURL(common.URL{})
- pxy.SubscribeURL(common.URL{})
+ pxy.ExportURL(&common.URL{})
+ pxy.SubscribeURL(&common.URL{})
pxy.MethodMapper()
- pxy.UnexportURL(common.URL{})
+ pxy.UnexportURL(&common.URL{})
pxy.RefreshMetadata(constant.ANY_VALUE, constant.ANY_VALUE)
}
diff --git a/metadata/service/remote/service.go b/metadata/service/remote/service.go
index ae83a69..d1b17e8 100644
--- a/metadata/service/remote/service.go
+++ b/metadata/service/remote/service.go
@@ -89,29 +89,29 @@
}
// ExportURL will be implemented by in memory service
-func (mts *MetadataService) ExportURL(url common.URL) (bool, error) {
+func (mts *MetadataService) ExportURL(url *common.URL) (bool, error) {
return mts.inMemoryMetadataService.ExportURL(url)
}
// UnexportURL remove @url's metadata
-func (mts *MetadataService) UnexportURL(url common.URL) error {
+func (mts *MetadataService) UnexportURL(url *common.URL) error {
smi := identifier.NewServiceMetadataIdentifier(url)
smi.Revision = mts.exportedRevision.Load()
return mts.delegateReport.RemoveServiceMetadata(smi)
}
// SubscribeURL will be implemented by in memory service
-func (mts *MetadataService) SubscribeURL(url common.URL) (bool, error) {
+func (mts *MetadataService) SubscribeURL(url *common.URL) (bool, error) {
return mts.inMemoryMetadataService.SubscribeURL(url)
}
// UnsubscribeURL will be implemented by in memory service
-func (mts *MetadataService) UnsubscribeURL(url common.URL) error {
+func (mts *MetadataService) UnsubscribeURL(url *common.URL) error {
return mts.UnsubscribeURL(url)
}
// PublishServiceDefinition will call remote metadata's StoreProviderMetadata to store url info and service definition
-func (mts *MetadataService) PublishServiceDefinition(url common.URL) error {
+func (mts *MetadataService) PublishServiceDefinition(url *common.URL) error {
interfaceName := url.GetParam(constant.INTERFACE_KEY, "")
isGeneric := url.GetParamBool(constant.GENERIC_KEY, false)
if len(interfaceName) > 0 && !isGeneric {
@@ -139,7 +139,7 @@
}
// GetSubscribedURLs will be implemented by in memory service
-func (mts *MetadataService) GetSubscribedURLs() ([]common.URL, error) {
+func (mts *MetadataService) GetSubscribedURLs() ([]*common.URL, error) {
return mts.inMemoryMetadataService.GetSubscribedURLs()
}
diff --git a/metadata/service/remote/service_proxy.go b/metadata/service/remote/service_proxy.go
index eaf7a02..3199aa6 100644
--- a/metadata/service/remote/service_proxy.go
+++ b/metadata/service/remote/service_proxy.go
@@ -45,27 +45,27 @@
return m.serviceName, nil
}
-func (m *metadataServiceProxy) ExportURL(url common.URL) (bool, error) {
+func (m *metadataServiceProxy) ExportURL(url *common.URL) (bool, error) {
logger.Error("you should never invoke this implementation")
return true, nil
}
-func (m *metadataServiceProxy) UnexportURL(url common.URL) error {
+func (m *metadataServiceProxy) UnexportURL(url *common.URL) error {
logger.Error("you should never invoke this implementation")
return nil
}
-func (m *metadataServiceProxy) SubscribeURL(url common.URL) (bool, error) {
+func (m *metadataServiceProxy) SubscribeURL(url *common.URL) (bool, error) {
logger.Error("you should never invoke this implementation")
return true, nil
}
-func (m *metadataServiceProxy) UnsubscribeURL(url common.URL) error {
+func (m *metadataServiceProxy) UnsubscribeURL(url *common.URL) error {
logger.Error("you should never invoke this implementation")
return nil
}
-func (m *metadataServiceProxy) PublishServiceDefinition(url common.URL) error {
+func (m *metadataServiceProxy) PublishServiceDefinition(url *common.URL) error {
logger.Error("you should never invoke this implementation")
return nil
}
@@ -85,7 +85,7 @@
if err != nil {
return []interface{}{}, nil
}
- res := make([]common.URL, 0, len(urls))
+ var res []*common.URL
for _, s := range urls {
u, err := common.NewURL(s)
if err != nil {
@@ -101,9 +101,9 @@
return map[string]string{}
}
-func (m *metadataServiceProxy) GetSubscribedURLs() ([]common.URL, error) {
+func (m *metadataServiceProxy) GetSubscribedURLs() ([]*common.URL, error) {
logger.Error("you should never invoke this implementation")
- return []common.URL{}, nil
+ return nil, nil
}
func (m *metadataServiceProxy) GetServiceDefinition(interfaceName string, group string, version string) (string, error) {
diff --git a/metadata/service/remote/service_proxy_test.go b/metadata/service/remote/service_proxy_test.go
index c284bb2..8bccbb8 100644
--- a/metadata/service/remote/service_proxy_test.go
+++ b/metadata/service/remote/service_proxy_test.go
@@ -55,15 +55,15 @@
func TestMetadataServiceProxy(t *testing.T) {
pxy := createProxy()
pxy.ServiceName()
- pxy.PublishServiceDefinition(common.URL{})
+ pxy.PublishServiceDefinition(&common.URL{})
pxy.Version()
pxy.GetSubscribedURLs()
- pxy.UnsubscribeURL(common.URL{})
+ pxy.UnsubscribeURL(&common.URL{})
pxy.GetServiceDefinitionByServiceKey("any")
- pxy.ExportURL(common.URL{})
- pxy.SubscribeURL(common.URL{})
+ pxy.ExportURL(&common.URL{})
+ pxy.SubscribeURL(&common.URL{})
pxy.MethodMapper()
- pxy.UnexportURL(common.URL{})
+ pxy.UnexportURL(&common.URL{})
pxy.Reference()
pxy.RefreshMetadata(constant.ANY_VALUE, constant.ANY_VALUE)
}
@@ -89,7 +89,7 @@
return &mockMetadataReportFactory{}
})
u, _ := common.NewURL("mock://localhost")
- instance.GetMetadataReportInstance(&u)
+ instance.GetMetadataReportInstance(u)
}
type mockMetadataReportFactory struct {
@@ -110,7 +110,7 @@
panic("implement me")
}
-func (m mockMetadataReport) SaveServiceMetadata(*identifier.ServiceMetadataIdentifier, common.URL) error {
+func (m mockMetadataReport) SaveServiceMetadata(*identifier.ServiceMetadataIdentifier, *common.URL) error {
return nil
}
diff --git a/metadata/service/remote/service_test.go b/metadata/service/remote/service_test.go
index 734f098..1cbe5ee 100644
--- a/metadata/service/remote/service_test.go
+++ b/metadata/service/remote/service_test.go
@@ -39,7 +39,7 @@
)
var (
- serviceMetadata = make(map[*identifier.ServiceMetadataIdentifier]common.URL, 4)
+ serviceMetadata = make(map[*identifier.ServiceMetadataIdentifier]*common.URL, 4)
subscribedMetadata = make(map[*identifier.SubscriberMetadataIdentifier]string, 4)
)
@@ -65,7 +65,7 @@
return nil
}
-func (mr *metadataReport) SaveServiceMetadata(id *identifier.ServiceMetadataIdentifier, url common.URL) error {
+func (mr *metadataReport) SaveServiceMetadata(id *identifier.ServiceMetadataIdentifier, url *common.URL) error {
logger.Infof("SaveServiceMetadata , url is %v", url)
serviceMetadata[id] = url
return nil
@@ -97,7 +97,7 @@
extension.SetMetadataReportFactory("mock", getMetadataReportFactory)
u, err := common.NewURL(fmt.Sprintf("mock://127.0.0.1:20000/?sync.report=true"))
assert.NoError(t, err)
- instance.GetMetadataReportInstance(&u)
+ instance.GetMetadataReportInstance(u)
mts, err := newMetadataService()
assert.NoError(t, err)
mts.(*MetadataService).setInMemoryMetadataService(mockInmemoryProc(t))
diff --git a/metadata/service/service.go b/metadata/service/service.go
index f6509d0..1d90f8a 100644
--- a/metadata/service/service.go
+++ b/metadata/service/service.go
@@ -34,15 +34,15 @@
// ServiceName will get the service's name in meta service , which is application name
ServiceName() (string, error)
// ExportURL will store the exported url in metadata
- ExportURL(url common.URL) (bool, error)
+ ExportURL(url *common.URL) (bool, error)
// UnexportURL will delete the exported url in metadata
- UnexportURL(url common.URL) error
+ UnexportURL(url *common.URL) error
// SubscribeURL will store the subscribed url in metadata
- SubscribeURL(url common.URL) (bool, error)
+ SubscribeURL(url *common.URL) (bool, error)
// UnsubscribeURL will delete the subscribed url in metadata
- UnsubscribeURL(url common.URL) error
+ UnsubscribeURL(url *common.URL) error
// PublishServiceDefinition will generate the target url's code info
- PublishServiceDefinition(url common.URL) error
+ PublishServiceDefinition(url *common.URL) error
// GetExportedURLs will get the target exported url in metadata
// the url should be unique
// due to dubbo-go only support return array []interface{} in RPCService, so we should declare the return type as []interface{}
@@ -53,7 +53,7 @@
// GetExportedURLs will get the target subscribed url in metadata
// the url should be unique
- GetSubscribedURLs() ([]common.URL, error)
+ GetSubscribedURLs() ([]*common.URL, error)
// GetServiceDefinition will get the target service info store in metadata
GetServiceDefinition(interfaceName string, group string, version string) (string, error)
// GetServiceDefinition will get the target service info store in metadata by service key
@@ -122,7 +122,7 @@
return metaData[constant.EXPORTED_SERVICES_REVISION_PROPERTY_NAME]
}
-func ConvertURLArrToIntfArr(urls []common.URL) []interface{} {
+func ConvertURLArrToIntfArr(urls []*common.URL) []interface{} {
if len(urls) == 0 {
return []interface{}{}
}
diff --git a/metrics/prometheus/reporter.go b/metrics/prometheus/reporter.go
index bd1e798..810a13d 100644
--- a/metrics/prometheus/reporter.go
+++ b/metrics/prometheus/reporter.go
@@ -130,13 +130,13 @@
}
// whether this url represents the application received the request as server
-func isProvider(url common.URL) bool {
+func isProvider(url *common.URL) bool {
role := url.GetParam(constant.ROLE_KEY, "")
return strings.EqualFold(role, strconv.Itoa(common.PROVIDER))
}
// whether this url represents the application sent then request as client
-func isConsumer(url common.URL) bool {
+func isConsumer(url *common.URL) bool {
role := url.GetParam(constant.ROLE_KEY, "")
return strings.EqualFold(role, strconv.Itoa(common.CONSUMER))
}
diff --git a/protocol/dubbo/dubbo_invoker.go b/protocol/dubbo/dubbo_invoker.go
index e72ca28..acddfd6 100644
--- a/protocol/dubbo/dubbo_invoker.go
+++ b/protocol/dubbo/dubbo_invoker.go
@@ -66,7 +66,7 @@
}
// NewDubboInvoker constructor
-func NewDubboInvoker(url common.URL, client *remoting.ExchangeClient) *DubboInvoker {
+func NewDubboInvoker(url *common.URL, client *remoting.ExchangeClient) *DubboInvoker {
requestTimeout := config.GetConsumerConfig().RequestTimeout
requestTimeoutStr := url.GetParam(constant.TIMEOUT_KEY, config.GetConsumerConfig().Request_Timeout)
diff --git a/protocol/dubbo/dubbo_invoker_test.go b/protocol/dubbo/dubbo_invoker_test.go
index c80f412..49d853e 100644
--- a/protocol/dubbo/dubbo_invoker_test.go
+++ b/protocol/dubbo/dubbo_invoker_test.go
@@ -93,7 +93,7 @@
proto.Destroy()
}
-func InitTest(t *testing.T) (protocol.Protocol, common.URL) {
+func InitTest(t *testing.T) (protocol.Protocol, *common.URL) {
hessian.RegisterPOJO(&User{})
diff --git a/protocol/dubbo/dubbo_protocol.go b/protocol/dubbo/dubbo_protocol.go
index 8dda52b..4f03b8a 100644
--- a/protocol/dubbo/dubbo_protocol.go
+++ b/protocol/dubbo/dubbo_protocol.go
@@ -90,7 +90,7 @@
}
// Refer create dubbo service reference.
-func (dp *DubboProtocol) Refer(url common.URL) protocol.Invoker {
+func (dp *DubboProtocol) Refer(url *common.URL) protocol.Invoker {
exchangeClient := getExchangeClient(url)
if exchangeClient == nil {
logger.Warnf("can't dial the server: %+v", url.Location)
@@ -115,7 +115,7 @@
}
}
-func (dp *DubboProtocol) openServer(url common.URL) {
+func (dp *DubboProtocol) openServer(url *common.URL) {
_, ok := dp.serverMap[url.Location]
if !ok {
_, ok := dp.ExporterMap().Load(url.ServiceKey())
@@ -176,7 +176,7 @@
return result
}
-func getExchangeClient(url common.URL) *remoting.ExchangeClient {
+func getExchangeClient(url *common.URL) *remoting.ExchangeClient {
clientTmp, ok := exchangeClientMap.Load(url.Location)
if !ok {
var exchangeClientTmp *remoting.ExchangeClient
diff --git a/protocol/dubbo/hessian2/hessian_dubbo_test.go b/protocol/dubbo/hessian2/hessian_dubbo_test.go
index c3f19f0..13dab92 100644
--- a/protocol/dubbo/hessian2/hessian_dubbo_test.go
+++ b/protocol/dubbo/hessian2/hessian_dubbo_test.go
@@ -223,7 +223,7 @@
type AttachTestObject struct {
Id int32
- Name string `dubbo:name`
+ Name string `dubbo:"name"`
}
func (AttachTestObject) JavaClassName() string {
diff --git a/protocol/grpc/client.go b/protocol/grpc/client.go
index 9b31a8c..33f0a08 100644
--- a/protocol/grpc/client.go
+++ b/protocol/grpc/client.go
@@ -90,7 +90,7 @@
}
// NewClient creates a new gRPC client.
-func NewClient(url common.URL) *Client {
+func NewClient(url *common.URL) *Client {
// if global trace instance was set , it means trace function enabled. If not , will return Nooptracer
tracer := opentracing.GlobalTracer()
dailOpts := make([]grpc.DialOption, 0, 4)
@@ -117,7 +117,7 @@
}
func getInvoker(impl interface{}, conn *grpc.ClientConn) interface{} {
- in := []reflect.Value{}
+ var in []reflect.Value
in = append(in, reflect.ValueOf(conn))
method := reflect.ValueOf(impl).MethodByName("GetDubboStub")
res := method.Call(in)
diff --git a/protocol/grpc/grpc_invoker.go b/protocol/grpc/grpc_invoker.go
index 737e8c4..02e7716 100644
--- a/protocol/grpc/grpc_invoker.go
+++ b/protocol/grpc/grpc_invoker.go
@@ -45,7 +45,7 @@
}
// NewGrpcInvoker returns a Grpc invoker instance
-func NewGrpcInvoker(url common.URL, client *Client) *GrpcInvoker {
+func NewGrpcInvoker(url *common.URL, client *Client) *GrpcInvoker {
return &GrpcInvoker{
BaseInvoker: *protocol.NewBaseInvoker(url),
client: client,
@@ -62,7 +62,7 @@
result.Err = errNoReply
}
- in := []reflect.Value{}
+ var in []reflect.Value
in = append(in, reflect.ValueOf(context.Background()))
in = append(in, invocation.ParameterValues()...)
diff --git a/protocol/grpc/grpc_protocol.go b/protocol/grpc/grpc_protocol.go
index 396ff47..3ad1245 100644
--- a/protocol/grpc/grpc_protocol.go
+++ b/protocol/grpc/grpc_protocol.go
@@ -67,7 +67,7 @@
return exporter
}
-func (gp *GrpcProtocol) openServer(url common.URL) {
+func (gp *GrpcProtocol) openServer(url *common.URL) {
_, ok := gp.serverMap[url.Location]
if !ok {
_, ok := gp.ExporterMap().Load(url.ServiceKey())
@@ -89,7 +89,7 @@
}
// Refer a remote gRPC service
-func (gp *GrpcProtocol) Refer(url common.URL) protocol.Invoker {
+func (gp *GrpcProtocol) Refer(url *common.URL) protocol.Invoker {
invoker := NewGrpcInvoker(url, NewClient(url))
gp.SetInvokers(invoker)
logger.Infof("Refer service: %s", url.String())
diff --git a/protocol/grpc/server.go b/protocol/grpc/server.go
index 30bdf77..e77e2ba 100644
--- a/protocol/grpc/server.go
+++ b/protocol/grpc/server.go
@@ -63,7 +63,7 @@
}
// Start gRPC server with @url
-func (s *Server) Start(url common.URL) {
+func (s *Server) Start(url *common.URL) {
var (
addr string
err error
diff --git a/protocol/invoker.go b/protocol/invoker.go
index 91814e2..5657b6b 100644
--- a/protocol/invoker.go
+++ b/protocol/invoker.go
@@ -41,13 +41,13 @@
// BaseInvoker provides default invoker implement
type BaseInvoker struct {
- url common.URL
+ url *common.URL
available bool
destroyed bool
}
// NewBaseInvoker creates a new BaseInvoker
-func NewBaseInvoker(url common.URL) *BaseInvoker {
+func NewBaseInvoker(url *common.URL) *BaseInvoker {
return &BaseInvoker{
url: url,
available: true,
@@ -56,7 +56,7 @@
}
// GetUrl gets base invoker URL
-func (bi *BaseInvoker) GetUrl() common.URL {
+func (bi *BaseInvoker) GetUrl() *common.URL {
return bi.url
}
diff --git a/protocol/jsonrpc/http.go b/protocol/jsonrpc/http.go
index 2a2ddfe..869617e 100644
--- a/protocol/jsonrpc/http.go
+++ b/protocol/jsonrpc/http.go
@@ -101,7 +101,7 @@
}
// NewRequest creates a new HTTP request with @service ,@method and @arguments.
-func (c *HTTPClient) NewRequest(service common.URL, method string, args interface{}) *Request {
+func (c *HTTPClient) NewRequest(service *common.URL, method string, args interface{}) *Request {
return &Request{
ID: atomic.AddInt64(&c.ID, 1),
@@ -115,7 +115,7 @@
}
// Call makes a HTTP call with @ctx , @service ,@req and @rsp
-func (c *HTTPClient) Call(ctx context.Context, service common.URL, req *Request, rsp interface{}) error {
+func (c *HTTPClient) Call(ctx context.Context, service *common.URL, req *Request, rsp interface{}) error {
// header
httpHeader := http.Header{}
httpHeader.Set("Content-Type", "application/json")
diff --git a/protocol/jsonrpc/jsonrpc_invoker.go b/protocol/jsonrpc/jsonrpc_invoker.go
index d84b980..f10aaad 100644
--- a/protocol/jsonrpc/jsonrpc_invoker.go
+++ b/protocol/jsonrpc/jsonrpc_invoker.go
@@ -36,7 +36,7 @@
}
// NewJsonrpcInvoker creates JSON RPC invoker with @url and @client
-func NewJsonrpcInvoker(url common.URL, client *HTTPClient) *JsonrpcInvoker {
+func NewJsonrpcInvoker(url *common.URL, client *HTTPClient) *JsonrpcInvoker {
return &JsonrpcInvoker{
BaseInvoker: *protocol.NewBaseInvoker(url),
client: client,
diff --git a/protocol/jsonrpc/jsonrpc_protocol.go b/protocol/jsonrpc/jsonrpc_protocol.go
index 1778d99..643bcde 100644
--- a/protocol/jsonrpc/jsonrpc_protocol.go
+++ b/protocol/jsonrpc/jsonrpc_protocol.go
@@ -75,7 +75,7 @@
}
// Refer a remote JSON PRC service from registry
-func (jp *JsonrpcProtocol) Refer(url common.URL) protocol.Invoker {
+func (jp *JsonrpcProtocol) Refer(url *common.URL) protocol.Invoker {
//default requestTimeout
var requestTimeout = config.GetConsumerConfig().RequestTimeout
@@ -106,7 +106,7 @@
}
}
-func (jp *JsonrpcProtocol) openServer(url common.URL) {
+func (jp *JsonrpcProtocol) openServer(url *common.URL) {
_, ok := jp.serverMap[url.Location]
if !ok {
_, loadOk := jp.ExporterMap().Load(strings.TrimPrefix(url.Path, "/"))
diff --git a/protocol/jsonrpc/server.go b/protocol/jsonrpc/server.go
index 9755a48..755aa7d 100644
--- a/protocol/jsonrpc/server.go
+++ b/protocol/jsonrpc/server.go
@@ -229,7 +229,7 @@
}
// Start JSON RPC server then ready for accept request.
-func (s *Server) Start(url common.URL) {
+func (s *Server) Start(url *common.URL) {
listener, err := net.Listen("tcp", url.Location)
if err != nil {
logger.Errorf("jsonrpc server [%s] start failed: %v", url.Path, err)
diff --git a/protocol/mock/mock_invoker.go b/protocol/mock/mock_invoker.go
index 0c88b47..8a0973b 100644
--- a/protocol/mock/mock_invoker.go
+++ b/protocol/mock/mock_invoker.go
@@ -59,9 +59,9 @@
}
// GetUrl mocks base method
-func (m *MockInvoker) GetUrl() common.URL {
+func (m *MockInvoker) GetUrl() *common.URL {
ret := m.ctrl.Call(m, "GetUrl")
- ret0, _ := ret[0].(common.URL)
+ ret0, _ := ret[0].(*common.URL)
return ret0
}
diff --git a/protocol/protocol.go b/protocol/protocol.go
index 6bed5ec..d03e70f 100644
--- a/protocol/protocol.go
+++ b/protocol/protocol.go
@@ -32,7 +32,7 @@
// Export service for remote invocation
Export(invoker Invoker) Exporter
// Refer a remote service
- Refer(url common.URL) Invoker
+ Refer(url *common.URL) Invoker
// Destroy will destroy all invoker and exporter, so it only is called once.
Destroy()
}
@@ -89,7 +89,7 @@
}
// Refer is default refer implement.
-func (bp *BaseProtocol) Refer(url common.URL) Invoker {
+func (bp *BaseProtocol) Refer(url *common.URL) Invoker {
return NewBaseInvoker(url)
}
diff --git a/protocol/protocolwrapper/mock_protocol_filter.go b/protocol/protocolwrapper/mock_protocol_filter.go
index 2e9ffed..18a4e15 100644
--- a/protocol/protocolwrapper/mock_protocol_filter.go
+++ b/protocol/protocolwrapper/mock_protocol_filter.go
@@ -39,7 +39,7 @@
}
// Refer a mock remote service
-func (pfw *mockProtocolFilter) Refer(url common.URL) protocol.Invoker {
+func (pfw *mockProtocolFilter) Refer(url *common.URL) protocol.Invoker {
return protocol.NewBaseInvoker(url)
}
diff --git a/protocol/protocolwrapper/protocol_filter_wrapper.go b/protocol/protocolwrapper/protocol_filter_wrapper.go
index 4b2702b..79d2cf7 100644
--- a/protocol/protocolwrapper/protocol_filter_wrapper.go
+++ b/protocol/protocolwrapper/protocol_filter_wrapper.go
@@ -55,7 +55,7 @@
}
// Refer a remote service
-func (pfw *ProtocolFilterWrapper) Refer(url common.URL) protocol.Invoker {
+func (pfw *ProtocolFilterWrapper) Refer(url *common.URL) protocol.Invoker {
if pfw.protocol == nil {
pfw.protocol = extension.GetProtocol(url.Protocol)
}
@@ -101,7 +101,7 @@
}
// GetUrl is used to get url from FilterInvoker
-func (fi *FilterInvoker) GetUrl() common.URL {
+func (fi *FilterInvoker) GetUrl() *common.URL {
return fi.invoker.GetUrl()
}
diff --git a/protocol/protocolwrapper/protocol_filter_wrapper_test.go b/protocol/protocolwrapper/protocol_filter_wrapper_test.go
index b03ea7b..8f063f8 100644
--- a/protocol/protocolwrapper/protocol_filter_wrapper_test.go
+++ b/protocol/protocolwrapper/protocol_filter_wrapper_test.go
@@ -43,7 +43,7 @@
u := common.NewURLWithOptions(
common.WithParams(url.Values{}),
common.WithParamsValue(constant.SERVICE_FILTER_KEY, "echo"))
- exporter := filtProto.Export(protocol.NewBaseInvoker(*u))
+ exporter := filtProto.Export(protocol.NewBaseInvoker(u))
_, ok := exporter.GetInvoker().(*FilterInvoker)
assert.True(t, ok)
}
@@ -55,7 +55,7 @@
u := common.NewURLWithOptions(
common.WithParams(url.Values{}),
common.WithParamsValue(constant.REFERENCE_FILTER_KEY, "echo"))
- invoker := filtProto.Refer(*u)
+ invoker := filtProto.Refer(u)
_, ok := invoker.(*FilterInvoker)
assert.True(t, ok)
}
diff --git a/protocol/rest/rest_invoker.go b/protocol/rest/rest_invoker.go
index 691beed..898890e 100644
--- a/protocol/rest/rest_invoker.go
+++ b/protocol/rest/rest_invoker.go
@@ -43,7 +43,7 @@
}
// NewRestInvoker returns a RestInvoker
-func NewRestInvoker(url common.URL, client *client.RestClient, restMethodConfig map[string]*config.RestMethodConfig) *RestInvoker {
+func NewRestInvoker(url *common.URL, client *client.RestClient, restMethodConfig map[string]*config.RestMethodConfig) *RestInvoker {
return &RestInvoker{
BaseInvoker: *protocol.NewBaseInvoker(url),
client: *client,
diff --git a/protocol/rest/rest_protocol.go b/protocol/rest/rest_protocol.go
index 0cd26c2..05e119b 100644
--- a/protocol/rest/rest_protocol.go
+++ b/protocol/rest/rest_protocol.go
@@ -86,7 +86,7 @@
}
// Refer create rest service reference
-func (rp *RestProtocol) Refer(url common.URL) protocol.Invoker {
+func (rp *RestProtocol) Refer(url *common.URL) protocol.Invoker {
// create rest_invoker
var requestTimeout = config.GetConsumerConfig().RequestTimeout
requestTimeoutStr := url.GetParam(constant.TIMEOUT_KEY, config.GetConsumerConfig().Request_Timeout)
@@ -107,7 +107,7 @@
}
// nolint
-func (rp *RestProtocol) getServer(url common.URL, serverType string) server.RestServer {
+func (rp *RestProtocol) getServer(url *common.URL, serverType string) server.RestServer {
restServer, ok := rp.serverMap[url.Location]
if ok {
return restServer
@@ -149,8 +149,8 @@
func (rp *RestProtocol) Destroy() {
// destroy rest_server
rp.BaseProtocol.Destroy()
- for key, server := range rp.serverMap {
- server.Destroy()
+ for key, tmpServer := range rp.serverMap {
+ tmpServer.Destroy()
delete(rp.serverMap, key)
}
for key := range rp.clientMap {
diff --git a/protocol/rest/server/rest_server.go b/protocol/rest/server/rest_server.go
index d9542bb..5ef04ff 100644
--- a/protocol/rest/server/rest_server.go
+++ b/protocol/rest/server/rest_server.go
@@ -43,7 +43,7 @@
// RestServer user can implement this server interface
type RestServer interface {
// Start rest server
- Start(url common.URL)
+ Start(url *common.URL)
// Deploy a http api
Deploy(restMethodConfig *rest_config.RestMethodConfig, routeFunc func(request RestServerRequest, response RestServerResponse))
// UnDeploy a http api
diff --git a/protocol/rest/server/server_impl/go_restful_server.go b/protocol/rest/server/server_impl/go_restful_server.go
index 6fb9ee8..e4b2e26 100644
--- a/protocol/rest/server/server_impl/go_restful_server.go
+++ b/protocol/rest/server/server_impl/go_restful_server.go
@@ -59,7 +59,7 @@
// Start go-restful server
// It will add all go-restful filters
-func (grs *GoRestfulServer) Start(url common.URL) {
+func (grs *GoRestfulServer) Start(url *common.URL) {
container := restful.NewContainer()
for _, filter := range filterSlice {
container.Filter(filter)
diff --git a/protocol/rpc_status.go b/protocol/rpc_status.go
index 978534e..8d443e8 100644
--- a/protocol/rpc_status.go
+++ b/protocol/rpc_status.go
@@ -97,7 +97,7 @@
}
// GetURLStatus get URL RPC status.
-func GetURLStatus(url common.URL) *RPCStatus {
+func GetURLStatus(url *common.URL) *RPCStatus {
rpcStatus, found := serviceStatistic.Load(url.Key())
if !found {
rpcStatus, _ = serviceStatistic.LoadOrStore(url.Key(), &RPCStatus{})
@@ -106,7 +106,7 @@
}
// GetMethodStatus get method RPC status.
-func GetMethodStatus(url common.URL, methodName string) *RPCStatus {
+func GetMethodStatus(url *common.URL, methodName string) *RPCStatus {
identifier := url.Key()
methodMap, found := methodStatistics.Load(identifier)
if !found {
@@ -124,13 +124,13 @@
}
// BeginCount gets begin count.
-func BeginCount(url common.URL, methodName string) {
+func BeginCount(url *common.URL, methodName string) {
beginCount0(GetURLStatus(url))
beginCount0(GetMethodStatus(url, methodName))
}
// EndCount gets end count.
-func EndCount(url common.URL, methodName string, elapsed int64, succeeded bool) {
+func EndCount(url *common.URL, methodName string, elapsed int64, succeeded bool) {
endCount0(GetURLStatus(url), elapsed, succeeded)
endCount0(GetMethodStatus(url, methodName), elapsed, succeeded)
}
diff --git a/protocol/rpc_status_test.go b/protocol/rpc_status_test.go
index cc12753..6fd449c 100644
--- a/protocol/rpc_status_test.go
+++ b/protocol/rpc_status_test.go
@@ -79,7 +79,7 @@
assert.Equal(t, int32(0), status.total)
}
-func TestbeginCount0(t *testing.T) {
+func TestBeginCount0(t *testing.T) {
defer CleanAllStatus()
url, _ := common.NewURL(mockCommonDubboUrl)
@@ -142,7 +142,7 @@
}
-func request(url common.URL, method string, elapsed int64, active, succeeded bool) {
+func request(url *common.URL, method string, elapsed int64, active, succeeded bool) {
BeginCount(url, method)
if !active {
EndCount(url, method, elapsed, succeeded)
diff --git a/registry/base_registry.go b/registry/base_registry.go
index d6f5ceb..a6693be 100644
--- a/registry/base_registry.go
+++ b/registry/base_registry.go
@@ -99,8 +99,8 @@
birth int64 // time of file birth, seconds since Epoch; 0 if unknown
wg sync.WaitGroup // wg+done for zk restart
done chan struct{}
- cltLock sync.RWMutex //ctl lock is a lock for services map
- services map[string]common.URL // service name + protocol -> service config, for store the service registered
+ cltLock sync.RWMutex //ctl lock is a lock for services map
+ services map[string]*common.URL // service name + protocol -> service config, for store the service registered
}
// InitBaseRegistry for init some local variables and set BaseRegistry's subclass to it
@@ -108,14 +108,14 @@
r.URL = url
r.birth = time.Now().UnixNano()
r.done = make(chan struct{})
- r.services = make(map[string]common.URL)
+ r.services = make(map[string]*common.URL)
r.facadeBasedRegistry = facadeRegistry
return r
}
// GetUrl for get registry's url
-func (r *BaseRegistry) GetUrl() common.URL {
- return *r.URL
+func (r *BaseRegistry) GetUrl() *common.URL {
+ return r.URL
}
// Destroy for graceful down
@@ -132,7 +132,7 @@
}
// Register implement interface registry to register
-func (r *BaseRegistry) Register(conf common.URL) error {
+func (r *BaseRegistry) Register(conf *common.URL) error {
var (
ok bool
err error
@@ -160,11 +160,11 @@
}
// UnRegister implement interface registry to unregister
-func (r *BaseRegistry) UnRegister(conf common.URL) error {
+func (r *BaseRegistry) UnRegister(conf *common.URL) error {
var (
ok bool
err error
- oldURL common.URL
+ oldURL *common.URL
)
func() {
@@ -197,7 +197,7 @@
}
// service is for getting service path stored in url
-func (r *BaseRegistry) service(c common.URL) string {
+func (r *BaseRegistry) service(c *common.URL) string {
return url.QueryEscape(c.Service())
}
@@ -205,7 +205,7 @@
func (r *BaseRegistry) RestartCallBack() bool {
// copy r.services
- services := make([]common.URL, 0, len(r.services))
+ services := make([]*common.URL, 0, len(r.services))
for _, confIf := range r.services {
services = append(services, confIf)
}
@@ -230,16 +230,16 @@
}
// register for register url to registry, include init params
-func (r *BaseRegistry) register(c common.URL) error {
+func (r *BaseRegistry) register(c *common.URL) error {
return r.processURL(c, r.facadeBasedRegistry.DoRegister, r.createPath)
}
// unregister for unregister url to registry, include init params
-func (r *BaseRegistry) unregister(c common.URL) error {
+func (r *BaseRegistry) unregister(c *common.URL) error {
return r.processURL(c, r.facadeBasedRegistry.DoUnregister, nil)
}
-func (r *BaseRegistry) processURL(c common.URL, f func(string, string) error, cpf createPathFunc) error {
+func (r *BaseRegistry) processURL(c *common.URL, f func(string, string) error, cpf createPathFunc) error {
if f == nil {
panic(" Must provide a `function(string, string) error` to process URL. ")
}
@@ -291,7 +291,7 @@
}
// providerRegistry for provider role do
-func (r *BaseRegistry) providerRegistry(c common.URL, params url.Values, f createPathFunc) (string, string, error) {
+func (r *BaseRegistry) providerRegistry(c *common.URL, params url.Values, f createPathFunc) (string, string, error) {
var (
dubboPath string
rawURL string
@@ -342,7 +342,7 @@
}
// consumerRegistry for consumer role do
-func (r *BaseRegistry) consumerRegistry(c common.URL, params url.Values, f createPathFunc) (string, string, error) {
+func (r *BaseRegistry) consumerRegistry(c *common.URL, params url.Values, f createPathFunc) (string, string, error) {
var (
dubboPath string
rawURL string
diff --git a/registry/consul/listener.go b/registry/consul/listener.go
index b159834..0d665af 100644
--- a/registry/consul/listener.go
+++ b/registry/consul/listener.go
@@ -39,17 +39,17 @@
// registry.
type consulListener struct {
// Registry url.
- registryUrl common.URL
+ registryUrl *common.URL
// Consumer url.
- consumerUrl common.URL
+ consumerUrl *common.URL
// Consul watcher.
plan *watch.Plan
// Most recent service urls return by
// watcher.
- urls []common.URL
+ urls []*common.URL
// All service information changes will
// be wrapped into ServiceEvent, and be
@@ -78,7 +78,7 @@
wg sync.WaitGroup
}
-func newConsulListener(registryUrl common.URL, consumerUrl common.URL) (*consulListener, error) {
+func newConsulListener(registryUrl *common.URL, consumerUrl *common.URL) (*consulListener, error) {
params := make(map[string]interface{}, 8)
params["type"] = "service"
params["service"] = consumerUrl.Service()
@@ -93,7 +93,7 @@
registryUrl: registryUrl,
consumerUrl: consumerUrl,
plan: plan,
- urls: make([]common.URL, 0, 8),
+ urls: make([]*common.URL, 0, 8),
eventCh: make(chan *registry.ServiceEvent, 32),
errCh: make(chan error, 32),
done: make(chan struct{}),
@@ -142,7 +142,7 @@
func (l *consulListener) handler(idx uint64, raw interface{}) {
var (
service *consul.ServiceEntry
- url common.URL
+ url *common.URL
ok bool
err error
)
@@ -153,7 +153,7 @@
l.errCh <- err
return
}
- newUrls := make([]common.URL, 0, 8)
+ newUrls := make([]*common.URL, 0, 8)
events := make([]*registry.ServiceEvent, 0, 8)
for _, service = range services {
diff --git a/registry/consul/registry.go b/registry/consul/registry.go
index b92e335..0b7ba97 100644
--- a/registry/consul/registry.go
+++ b/registry/consul/registry.go
@@ -76,7 +76,7 @@
// Register register @url
// it delegate the job to register() method
-func (r *consulRegistry) Register(url common.URL) error {
+func (r *consulRegistry) Register(url *common.URL) error {
var err error
role, _ := strconv.Atoi(r.URL.GetParam(constant.ROLE_KEY, ""))
@@ -90,7 +90,7 @@
}
// register actually register the @url
-func (r *consulRegistry) register(url common.URL) error {
+func (r *consulRegistry) register(url *common.URL) error {
service, err := buildService(url)
if err != nil {
return err
@@ -100,7 +100,7 @@
// UnRegister unregister the @url
// it delegate the job to unregister() method
-func (r *consulRegistry) UnRegister(url common.URL) error {
+func (r *consulRegistry) UnRegister(url *common.URL) error {
var err error
role, _ := strconv.Atoi(r.URL.GetParam(constant.ROLE_KEY, ""))
@@ -114,7 +114,7 @@
}
// unregister actually unregister the @url
-func (r *consulRegistry) unregister(url common.URL) error {
+func (r *consulRegistry) unregister(url *common.URL) error {
return r.client.Agent().ServiceDeregister(buildId(url))
}
@@ -141,7 +141,7 @@
return
}
- listener, err := r.getListener(*url)
+ listener, err := r.getListener(url)
if err != nil {
if !r.IsAvailable() {
logger.Warnf("event listener game over.")
@@ -166,14 +166,14 @@
}
}
-func (r *consulRegistry) getListener(url common.URL) (registry.Listener, error) {
- listener, err := newConsulListener(*r.URL, url)
+func (r *consulRegistry) getListener(url *common.URL) (registry.Listener, error) {
+ listener, err := newConsulListener(r.URL, url)
return listener, err
}
// GetUrl get registry URL of consul registry center
-func (r *consulRegistry) GetUrl() common.URL {
- return *r.URL
+func (r *consulRegistry) GetUrl() *common.URL {
+ return r.URL
}
// IsAvailable checks consul registry center whether is available
@@ -197,7 +197,7 @@
}
done <- struct{}{}
}()
- if err := r.UnRegister(*r.URL); err != nil {
+ if err := r.UnRegister(r.URL); err != nil {
logger.Errorf("consul registry unregister with err: %s", err.Error())
}
}()
diff --git a/registry/consul/service_discovery_test.go b/registry/consul/service_discovery_test.go
index ed7220f..2169857 100644
--- a/registry/consul/service_discovery_test.go
+++ b/registry/consul/service_discovery_test.go
@@ -44,7 +44,6 @@
consulCheckPassInterval = 17000
consulDeregisterCriticalServiceAfter = "20s"
consulWatchTimeout = 60000
- registryURL = common.URL{}
)
func TestConsulServiceDiscovery_newConsulServiceDiscovery(t *testing.T) {
@@ -173,7 +172,7 @@
}
}
-func prepareService() (registry.ServiceInstance, common.URL) {
+func prepareService() (registry.ServiceInstance, *common.URL) {
id := "id"
registryUrl, _ := common.NewURL(protocol + "://" + providerHost + ":" + strconv.Itoa(providerPort) + "/" + service + "?anyhost=true&" +
@@ -200,19 +199,19 @@
}
// AddEventListener do nothing
-func (m *MockEventDispatcher) AddEventListener(listener observer.EventListener) {
+func (m *MockEventDispatcher) AddEventListener(observer.EventListener) {
}
// AddEventListeners do nothing
-func (m *MockEventDispatcher) AddEventListeners(listenersSlice []observer.EventListener) {
+func (m *MockEventDispatcher) AddEventListeners([]observer.EventListener) {
}
// RemoveEventListener do nothing
-func (m *MockEventDispatcher) RemoveEventListener(listener observer.EventListener) {
+func (m *MockEventDispatcher) RemoveEventListener(observer.EventListener) {
}
// RemoveEventListeners do nothing
-func (m *MockEventDispatcher) RemoveEventListeners(listenersSlice []observer.EventListener) {
+func (m *MockEventDispatcher) RemoveEventListeners([]observer.EventListener) {
}
// GetAllEventListeners return empty list
diff --git a/registry/consul/utils.go b/registry/consul/utils.go
index f5babf6..468dafb 100644
--- a/registry/consul/utils.go
+++ b/registry/consul/utils.go
@@ -33,12 +33,12 @@
"github.com/apache/dubbo-go/common"
)
-func buildId(url common.URL) string {
+func buildId(url *common.URL) string {
t := md5.Sum([]byte(url.String()))
return hex.EncodeToString(t[:])
}
-func buildService(url common.URL) (*consul.AgentServiceRegistration, error) {
+func buildService(url *common.URL) (*consul.AgentServiceRegistration, error) {
var err error
// id
@@ -93,19 +93,19 @@
return service, nil
}
-func retrieveURL(service *consul.ServiceEntry) (common.URL, error) {
+func retrieveURL(service *consul.ServiceEntry) (*common.URL, error) {
url, ok := service.Service.Meta["url"]
if !ok {
- return common.URL{}, perrors.New("retrieve url fails with no url key in service meta")
+ return nil, perrors.New("retrieve url fails with no url key in service meta")
}
url1, err := common.NewURL(url)
if err != nil {
- return common.URL{}, perrors.WithStack(err)
+ return nil, perrors.WithStack(err)
}
return url1, nil
}
-func in(url common.URL, urls []common.URL) bool {
+func in(url *common.URL, urls []*common.URL) bool {
for _, url1 := range urls {
if url.URLEqual(url1) {
return true
diff --git a/registry/consul/utils_test.go b/registry/consul/utils_test.go
index 0e5bffe..d78c534 100644
--- a/registry/consul/utils_test.go
+++ b/registry/consul/utils_test.go
@@ -63,8 +63,8 @@
)
}
-func newProviderUrl(host string, port int, service string, protocol string) common.URL {
- return *common.NewURLWithOptions(
+func newProviderUrl(host string, port int, service string, protocol string) *common.URL {
+ return common.NewURLWithOptions(
common.WithIp(host),
common.WithPort(strconv.Itoa(port)),
common.WithPath(service),
@@ -72,8 +72,8 @@
)
}
-func newConsumerUrl(host string, port int, service string, protocol string) common.URL {
- return *common.NewURLWithOptions(
+func newConsumerUrl(host string, port int, service string, protocol string) *common.URL {
+ return common.NewURLWithOptions(
common.WithIp(host),
common.WithPort(strconv.Itoa(port)),
common.WithPath(service),
@@ -130,8 +130,8 @@
providerRegistry registry.Registry
consumerRegistry *consulRegistry
listener registry.Listener
- providerUrl common.URL
- consumerUrl common.URL
+ providerUrl *common.URL
+ consumerUrl *common.URL
}
func newConsulRegistryTestSuite(t *testing.T) *consulRegistryTestSuite {
diff --git a/registry/directory/directory.go b/registry/directory/directory.go
index 6f9c4fc..e6ae0f3 100644
--- a/registry/directory/directory.go
+++ b/registry/directory/directory.go
@@ -149,7 +149,7 @@
// eventMatched checks if a cached invoker appears in the incoming invoker list, if no, then it is safe to remove.
func (dir *RegistryDirectory) eventMatched(key string, events []*registry.ServiceEvent) bool {
for _, event := range events {
- if dir.invokerCacheKey(&event.Service) == key {
+ if dir.invokerCacheKey(event.Service) == key {
return true
}
}
@@ -207,7 +207,7 @@
// convertUrl processes override:// and router://
func (dir *RegistryDirectory) convertUrl(res *registry.ServiceEvent) *common.URL {
- ret := &res.Service
+ ret := res.Service
if ret.Protocol == constant.OVERRIDE_PROTOCOL || // 1.for override url in 2.6.x
ret.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY) == constant.CONFIGURATORS_CATEGORY {
dir.configurators = append(dir.configurators, extension.GetDefaultConfigurator(ret))
@@ -296,19 +296,19 @@
dir.overrideUrl(newUrl)
if cacheInvoker, ok := dir.cacheInvokersMap.Load(newUrl.Key()); !ok {
logger.Debugf("service will be added in cache invokers: invokers url is %s!", newUrl)
- newInvoker := extension.GetProtocol(protocolwrapper.FILTER).Refer(*newUrl)
+ newInvoker := extension.GetProtocol(protocolwrapper.FILTER).Refer(newUrl)
if newInvoker != nil {
dir.cacheInvokersMap.Store(newUrl.Key(), newInvoker)
}
} else {
// if cached invoker has the same URL with the new URL, then no need to re-refer, and no need to destroy
// the old invoker.
- if common.IsEquals(*newUrl, cacheInvoker.(protocol.Invoker).GetUrl()) {
+ if common.IsEquals(newUrl, cacheInvoker.(protocol.Invoker).GetUrl()) {
return nil
}
logger.Debugf("service will be updated in cache invokers: new invoker url is %s, old invoker url is %s", newUrl, cacheInvoker.(protocol.Invoker).GetUrl())
- newInvoker := extension.GetProtocol(protocolwrapper.FILTER).Refer(*newUrl)
+ newInvoker := extension.GetProtocol(protocolwrapper.FILTER).Refer(newUrl)
if newInvoker != nil {
dir.cacheInvokersMap.Store(newUrl.Key(), newInvoker)
return cacheInvoker.(protocol.Invoker)
diff --git a/registry/directory/directory_test.go b/registry/directory/directory_test.go
index f2b2f8e..dde944d 100644
--- a/registry/directory/directory_test.go
+++ b/registry/directory/directory_test.go
@@ -72,7 +72,7 @@
func TestSubscribe_InvalidUrl(t *testing.T) {
url, _ := common.NewURL("mock://127.0.0.1:1111")
mockRegistry, _ := registry.NewMockRegistry(&common.URL{})
- _, err := NewRegistryDirectory(&url, mockRegistry)
+ _, err := NewRegistryDirectory(url, mockRegistry)
assert.Error(t, err)
}
@@ -83,9 +83,9 @@
regurl, _ := common.NewURL("mock://127.0.0.1:1111")
suburl, _ := common.NewURL("dubbo://127.0.0.1:20000")
suburl.SetParam(constant.CLUSTER_KEY, "mock")
- regurl.SubURL = &suburl
+ regurl.SubURL = suburl
mockRegistry, _ := registry.NewMockRegistry(&common.URL{})
- dir, _ := NewRegistryDirectory(®url, mockRegistry)
+ dir, _ := NewRegistryDirectory(regurl, mockRegistry)
go dir.(*RegistryDirectory).subscribe(common.NewURLWithOptions(common.WithPath("testservice")))
//for group1
@@ -93,7 +93,7 @@
urlmap.Set(constant.GROUP_KEY, "group1")
urlmap.Set(constant.CLUSTER_KEY, "failover") //to test merge url
for i := 0; i < 3; i++ {
- mockRegistry.(*registry.MockRegistry).MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: *common.NewURLWithOptions(common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)), common.WithProtocol("dubbo"),
+ mockRegistry.(*registry.MockRegistry).MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: common.NewURLWithOptions(common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)), common.WithProtocol("dubbo"),
common.WithParams(urlmap))})
}
//for group2
@@ -101,7 +101,7 @@
urlmap2.Set(constant.GROUP_KEY, "group2")
urlmap2.Set(constant.CLUSTER_KEY, "failover") //to test merge url
for i := 0; i < 3; i++ {
- mockRegistry.(*registry.MockRegistry).MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: *common.NewURLWithOptions(common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)), common.WithProtocol("dubbo"),
+ mockRegistry.(*registry.MockRegistry).MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: common.NewURLWithOptions(common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)), common.WithProtocol("dubbo"),
common.WithParams(urlmap2))})
}
@@ -202,17 +202,17 @@
common.WithParamsValue(constant.GROUP_KEY, "group"),
common.WithParamsValue(constant.VERSION_KEY, "1.0.0"),
)
- url.SubURL = &suburl
+ url.SubURL = suburl
mockRegistry, _ := registry.NewMockRegistry(&common.URL{})
- dir, _ := NewRegistryDirectory(&url, mockRegistry)
+ dir, _ := NewRegistryDirectory(url, mockRegistry)
- go dir.(*RegistryDirectory).subscribe(&suburl)
+ go dir.(*RegistryDirectory).subscribe(suburl)
if len(noMockEvent) == 0 {
for i := 0; i < 3; i++ {
mockRegistry.(*registry.MockRegistry).MockEvent(
®istry.ServiceEvent{
Action: remoting.EventTypeAdd,
- Service: *common.NewURLWithOptions(
+ Service: common.NewURLWithOptions(
common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)),
common.WithProtocol("dubbo"),
),
diff --git a/registry/etcdv3/listener.go b/registry/etcdv3/listener.go
index 436b6ec..4bc387c 100644
--- a/registry/etcdv3/listener.go
+++ b/registry/etcdv3/listener.go
@@ -64,7 +64,7 @@
}
for _, v := range l.interestedURL {
- if serviceURL.URLEqual(*v) {
+ if serviceURL.URLEqual(v) {
l.listener.Process(
&config_center.ConfigChangeEvent{
Key: eventType.Path,
@@ -113,7 +113,7 @@
}
continue
}
- return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(common.URL)}, nil
+ return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(*common.URL)}, nil
}
}
}
diff --git a/registry/etcdv3/listener_test.go b/registry/etcdv3/listener_test.go
index 1cf06d1..ff7f63f 100644
--- a/registry/etcdv3/listener_test.go
+++ b/registry/etcdv3/listener_test.go
@@ -80,7 +80,7 @@
listener := NewRegistryDataListener(&MockDataListener{})
url, _ := common.NewURL("jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100")
- listener.AddInterestedURL(&url)
+ listener.AddInterestedURL(url)
if !listener.DataChange(remoting.Event{Path: "/dubbo/com.ikurento.user.UserProvider/providers/jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100"}) {
t.Fatal("data change not ok")
}
diff --git a/registry/etcdv3/registry_test.go b/registry/etcdv3/registry_test.go
index 164fe9c..d94eff6 100644
--- a/registry/etcdv3/registry_test.go
+++ b/registry/etcdv3/registry_test.go
@@ -39,7 +39,7 @@
t.Fatal(err)
}
- reg, err := newETCDV3Registry(®url)
+ reg, err := newETCDV3Registry(regurl)
if err != nil {
t.Fatal(err)
}
@@ -86,7 +86,7 @@
err = reg2.Register(url)
assert.NoError(t, err)
- listener, err := reg2.DoSubscribe(&url)
+ listener, err := reg2.DoSubscribe(url)
if err != nil {
t.Fatal(err)
}
@@ -104,7 +104,7 @@
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
reg := initRegistry(t)
- _, err := reg.DoSubscribe(&url)
+ _, err := reg.DoSubscribe(url)
if err != nil {
t.Fatal(err)
}
diff --git a/registry/event.go b/registry/event.go
index 39fb00c..c934158 100644
--- a/registry/event.go
+++ b/registry/event.go
@@ -40,7 +40,7 @@
// ServiceEvent includes create, update, delete event
type ServiceEvent struct {
Action remoting.EventType
- Service common.URL
+ Service *common.URL
}
// String return the description of event
diff --git a/registry/event/metadata_service_url_params_customizer_test.go b/registry/event/metadata_service_url_params_customizer_test.go
index 98ae2df..c041232 100644
--- a/registry/event/metadata_service_url_params_customizer_test.go
+++ b/registry/event/metadata_service_url_params_customizer_test.go
@@ -70,27 +70,27 @@
panic("implement me")
}
-func (m *mockMetadataService) ExportURL(url common.URL) (bool, error) {
+func (m *mockMetadataService) ExportURL(*common.URL) (bool, error) {
panic("implement me")
}
-func (m *mockMetadataService) UnexportURL(url common.URL) error {
+func (m *mockMetadataService) UnexportURL(*common.URL) error {
panic("implement me")
}
-func (m *mockMetadataService) SubscribeURL(url common.URL) (bool, error) {
+func (m *mockMetadataService) SubscribeURL(*common.URL) (bool, error) {
panic("implement me")
}
-func (m *mockMetadataService) UnsubscribeURL(url common.URL) error {
+func (m *mockMetadataService) UnsubscribeURL(*common.URL) error {
panic("implement me")
}
-func (m *mockMetadataService) PublishServiceDefinition(url common.URL) error {
+func (m *mockMetadataService) PublishServiceDefinition(*common.URL) error {
panic("implement me")
}
-func (m *mockMetadataService) GetExportedURLs(serviceInterface string, group string, version string, protocol string) ([]interface{}, error) {
+func (m *mockMetadataService) GetExportedURLs(string, string, string, string) ([]interface{}, error) {
return m.urls, nil
}
@@ -98,8 +98,8 @@
panic("implement me")
}
-func (m *mockMetadataService) GetSubscribedURLs() ([]common.URL, error) {
- res := make([]common.URL, 0, len(m.urls))
+func (m *mockMetadataService) GetSubscribedURLs() ([]*common.URL, error) {
+ var res []*common.URL
for _, ui := range m.urls {
u, _ := common.NewURL(ui.(string))
res = append(res, u)
@@ -107,15 +107,15 @@
return res, nil
}
-func (m *mockMetadataService) GetServiceDefinition(interfaceName string, group string, version string) (string, error) {
+func (m *mockMetadataService) GetServiceDefinition(string, string, string) (string, error) {
panic("implement me")
}
-func (m *mockMetadataService) GetServiceDefinitionByServiceKey(serviceKey string) (string, error) {
+func (m *mockMetadataService) GetServiceDefinitionByServiceKey(string) (string, error) {
panic("implement me")
}
-func (m *mockMetadataService) RefreshMetadata(exportedRevision string, subscribedRevision string) (bool, error) {
+func (m *mockMetadataService) RefreshMetadata(string, string) (bool, error) {
panic("implement me")
}
diff --git a/registry/file/service_discovery.go b/registry/file/service_discovery.go
index 59c5cf9..254c126 100644
--- a/registry/file/service_discovery.go
+++ b/registry/file/service_discovery.go
@@ -70,7 +70,7 @@
p := path.Join(rp, ".dubbo", constant.REGISTRY_KEY)
url, _ := common.NewURL("")
url.AddParamAvoidNil(file.CONFIG_CENTER_DIR_PARAM_NAME, p)
- c, err := fdcf.GetDynamicConfiguration(&url)
+ c, err := fdcf.GetDynamicConfiguration(url)
if err != nil {
return nil, perrors.WithStack(err)
}
diff --git a/registry/kubernetes/listener.go b/registry/kubernetes/listener.go
index 24c8d81..e20b7c7 100644
--- a/registry/kubernetes/listener.go
+++ b/registry/kubernetes/listener.go
@@ -65,7 +65,7 @@
}
for _, v := range l.interestedURL {
- if serviceURL.URLEqual(*v) {
+ if serviceURL.URLEqual(v) {
l.listener.Process(
&config_center.ConfigChangeEvent{
Key: eventType.Path,
@@ -114,7 +114,7 @@
}
continue
}
- return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(common.URL)}, nil
+ return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(*common.URL)}, nil
}
}
}
diff --git a/registry/kubernetes/listener_test.go b/registry/kubernetes/listener_test.go
index ccaaf80..f1d8ff4 100644
--- a/registry/kubernetes/listener_test.go
+++ b/registry/kubernetes/listener_test.go
@@ -166,7 +166,7 @@
func Test_DataChange(t *testing.T) {
listener := NewRegistryDataListener(&MockDataListener{})
url, _ := common.NewURL("jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100")
- listener.AddInterestedURL(&url)
+ listener.AddInterestedURL(url)
int := listener.DataChange(remoting.Event{Path: "/dubbo/com.ikurento.user.UserProvider/providers/jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100"})
assert.Equal(t, true, int)
}
@@ -179,7 +179,7 @@
listener := NewRegistryDataListener(&MockDataListener{})
url, _ := common.NewURL("jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100")
- listener.AddInterestedURL(&url)
+ listener.AddInterestedURL(url)
if !listener.DataChange(remoting.Event{Path: "/dubbo/com.ikurento.user.UserProvider/providers/jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100"}) {
t.Fatal("data change not ok")
}
diff --git a/registry/kubernetes/registry_test.go b/registry/kubernetes/registry_test.go
index 347dadc..9fb409a 100644
--- a/registry/kubernetes/registry_test.go
+++ b/registry/kubernetes/registry_test.go
@@ -231,7 +231,7 @@
if err != nil {
t.Fatal(err)
}
- out, err := newMockKubernetesRegistry(®url, pl)
+ out, err := newMockKubernetesRegistry(regurl, pl)
if err != nil {
t.Fatal(err)
}
@@ -268,7 +268,7 @@
t.Fatal(err)
}
- listener, err := r.DoSubscribe(&url)
+ listener, err := r.DoSubscribe(url)
if err != nil {
t.Fatal(err)
}
@@ -301,7 +301,7 @@
common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
common.WithMethods([]string{"GetUser", "AddUser"}))
- _, err := r.DoSubscribe(&url)
+ _, err := r.DoSubscribe(url)
if err != nil {
t.Fatal(err)
}
@@ -336,7 +336,7 @@
if err != nil {
t.Fatal(err)
}
- _, err = newKubernetesRegistry(®Url)
+ _, err = newKubernetesRegistry(regUrl)
if err == nil {
t.Fatal("not in cluster, should be a err")
}
diff --git a/registry/mock_registry.go b/registry/mock_registry.go
index 10561d0..18c87ee 100644
--- a/registry/mock_registry.go
+++ b/registry/mock_registry.go
@@ -47,12 +47,12 @@
}
// Register is used as a mock registry
-func (*MockRegistry) Register(url common.URL) error {
+func (*MockRegistry) Register(url *common.URL) error {
return nil
}
// nolint
-func (r *MockRegistry) UnRegister(conf common.URL) error {
+func (r *MockRegistry) UnRegister(conf *common.URL) error {
return nil
}
@@ -68,8 +68,8 @@
}
// nolint
-func (r *MockRegistry) GetUrl() common.URL {
- return common.URL{}
+func (r *MockRegistry) GetUrl() *common.URL {
+ return nil
}
func (r *MockRegistry) subscribe(*common.URL) (Listener, error) {
diff --git a/registry/nacos/listener.go b/registry/nacos/listener.go
index cf6a73d..7f27326 100644
--- a/registry/nacos/listener.go
+++ b/registry/nacos/listener.go
@@ -43,7 +43,7 @@
type nacosListener struct {
namingClient naming_client.INamingClient
- listenUrl common.URL
+ listenUrl *common.URL
events chan *config_center.ConfigChangeEvent
instanceMap map[string]model.Instance
cacheLock sync.Mutex
@@ -52,7 +52,7 @@
}
// NewRegistryDataListener creates a data listener for nacos
-func NewNacosListener(url common.URL, namingClient naming_client.INamingClient) (*nacosListener, error) {
+func NewNacosListener(url *common.URL, namingClient naming_client.INamingClient) (*nacosListener, error) {
listener := &nacosListener{
namingClient: namingClient,
listenUrl: url, events: make(chan *config_center.ConfigChangeEvent, 32),
@@ -154,25 +154,25 @@
for i := range addInstances {
newUrl := generateUrl(addInstances[i])
if newUrl != nil {
- nl.process(&config_center.ConfigChangeEvent{Value: *newUrl, ConfigType: remoting.EventTypeAdd})
+ nl.process(&config_center.ConfigChangeEvent{Value: newUrl, ConfigType: remoting.EventTypeAdd})
}
}
for i := range delInstances {
newUrl := generateUrl(delInstances[i])
if newUrl != nil {
- nl.process(&config_center.ConfigChangeEvent{Value: *newUrl, ConfigType: remoting.EventTypeDel})
+ nl.process(&config_center.ConfigChangeEvent{Value: newUrl, ConfigType: remoting.EventTypeDel})
}
}
for i := range updateInstances {
newUrl := generateUrl(updateInstances[i])
if newUrl != nil {
- nl.process(&config_center.ConfigChangeEvent{Value: *newUrl, ConfigType: remoting.EventTypeUpdate})
+ nl.process(&config_center.ConfigChangeEvent{Value: newUrl, ConfigType: remoting.EventTypeUpdate})
}
}
}
-func getSubscribeName(url common.URL) string {
+func getSubscribeName(url *common.URL) string {
var buffer bytes.Buffer
buffer.Write([]byte(common.DubboNodes[common.PROVIDER]))
@@ -210,7 +210,7 @@
case e := <-nl.events:
logger.Debugf("got nacos event %s", e)
- return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(common.URL)}, nil
+ return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(*common.URL)}, nil
}
}
}
diff --git a/registry/nacos/registry.go b/registry/nacos/registry.go
index 5142886..ae2345e 100644
--- a/registry/nacos/registry.go
+++ b/registry/nacos/registry.go
@@ -58,16 +58,16 @@
type nacosRegistry struct {
*common.URL
namingClient naming_client.INamingClient
- registryUrls []common.URL
+ registryUrls []*common.URL
}
-func getCategory(url common.URL) string {
+func getCategory(url *common.URL) string {
role, _ := strconv.Atoi(url.GetParam(constant.ROLE_KEY, strconv.Itoa(constant.NACOS_DEFAULT_ROLETYPE)))
category := common.DubboNodes[role]
return category
}
-func getServiceName(url common.URL) string {
+func getServiceName(url *common.URL) string {
var buffer bytes.Buffer
buffer.Write([]byte(getCategory(url)))
@@ -77,7 +77,7 @@
return buffer.String()
}
-func appendParam(target *bytes.Buffer, url common.URL, key string) {
+func appendParam(target *bytes.Buffer, url *common.URL, key string) {
value := url.GetParam(key, "")
if strings.TrimSpace(value) != "" {
target.Write([]byte(constant.NACOS_SERVICE_NAME_SEPARATOR))
@@ -85,7 +85,7 @@
}
}
-func createRegisterParam(url common.URL, serviceName string) vo.RegisterInstanceParam {
+func createRegisterParam(url *common.URL, serviceName string) vo.RegisterInstanceParam {
category := getCategory(url)
params := make(map[string]string)
@@ -118,7 +118,7 @@
}
// Register will register the service @url to its nacos registry center
-func (nr *nacosRegistry) Register(url common.URL) error {
+func (nr *nacosRegistry) Register(url *common.URL) error {
serviceName := getServiceName(url)
param := createRegisterParam(url, serviceName)
isRegistry, err := nr.namingClient.RegisterInstance(param)
@@ -132,7 +132,7 @@
return nil
}
-func createDeregisterParam(url common.URL, serviceName string) vo.DeregisterInstanceParam {
+func createDeregisterParam(url *common.URL, serviceName string) vo.DeregisterInstanceParam {
if len(url.Ip) == 0 {
url.Ip = localIP
}
@@ -148,7 +148,7 @@
}
}
-func (nr *nacosRegistry) DeRegister(url common.URL) error {
+func (nr *nacosRegistry) DeRegister(url *common.URL) error {
serviceName := getServiceName(url)
param := createDeregisterParam(url, serviceName)
isDeRegistry, err := nr.namingClient.DeregisterInstance(param)
@@ -162,12 +162,12 @@
}
// UnRegister
-func (nr *nacosRegistry) UnRegister(conf common.URL) error {
+func (nr *nacosRegistry) UnRegister(conf *common.URL) error {
return perrors.New("UnRegister is not support in nacosRegistry")
}
func (nr *nacosRegistry) subscribe(conf *common.URL) (registry.Listener, error) {
- return NewNacosListener(*conf, nr.namingClient)
+ return NewNacosListener(conf, nr.namingClient)
}
// subscribe from registry
@@ -202,7 +202,6 @@
}
}
- return nil
}
// UnSubscribe :
@@ -211,8 +210,8 @@
}
// GetUrl gets its registration URL
-func (nr *nacosRegistry) GetUrl() common.URL {
- return *nr.URL
+func (nr *nacosRegistry) GetUrl() *common.URL {
+ return nr.URL
}
// IsAvailable determines nacos registry center whether it is available
@@ -243,12 +242,12 @@
if err != nil {
return &nacosRegistry{}, err
}
- registry := &nacosRegistry{
+ tmpRegistry := &nacosRegistry{
URL: url,
namingClient: client,
- registryUrls: []common.URL{},
+ registryUrls: []*common.URL{},
}
- return registry, nil
+ return tmpRegistry, nil
}
// getNacosConfig will return the nacos config
diff --git a/registry/nacos/registry_test.go b/registry/nacos/registry_test.go
index d0311b2..43a6da7 100644
--- a/registry/nacos/registry_test.go
+++ b/registry/nacos/registry_test.go
@@ -44,7 +44,7 @@
urlMap.Set(constant.CLUSTER_KEY, "mock")
testUrl, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"}))
- reg, err := newNacosRegistry(®url)
+ reg, err := newNacosRegistry(regurl)
assert.Nil(t, err)
if err != nil {
t.Errorf("new nacos registry error:%s \n", err.Error())
@@ -74,7 +74,7 @@
urlMap.Set(constant.NACOS_PATH_KEY, "")
testUrl, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"}))
- reg, _ := newNacosRegistry(®url)
+ reg, _ := newNacosRegistry(regurl)
err := reg.Register(testUrl)
assert.Nil(t, err)
if err != nil {
@@ -83,8 +83,8 @@
}
regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER))
- reg2, _ := newNacosRegistry(®url)
- listener, err := reg2.(*nacosRegistry).subscribe(&testUrl)
+ reg2, _ := newNacosRegistry(regurl)
+ listener, err := reg2.(*nacosRegistry).subscribe(testUrl)
assert.Nil(t, err)
if err != nil {
t.Errorf("subscribe error:%s \n", err.Error())
@@ -113,7 +113,7 @@
url1, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"}))
url2, _ := common.NewURL("dubbo://127.0.0.2:20000/com.ikurento.user.UserProvider", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"}))
- reg, _ := newNacosRegistry(®url)
+ reg, _ := newNacosRegistry(regurl)
err := reg.Register(url1)
assert.Nil(t, err)
if err != nil {
@@ -128,8 +128,8 @@
}
regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER))
- reg2, _ := newNacosRegistry(®url)
- listener, err := reg2.(*nacosRegistry).subscribe(&url1)
+ reg2, _ := newNacosRegistry(regurl)
+ listener, err := reg2.(*nacosRegistry).subscribe(url1)
assert.Nil(t, err)
if err != nil {
t.Errorf("subscribe error:%s \n", err.Error())
@@ -177,8 +177,8 @@
urlMap.Set(constant.CLUSTER_KEY, "mock")
urlMap.Set(constant.NACOS_PATH_KEY, "")
url1, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider2", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"}))
- reg, _ := newNacosRegistry(®url)
- listener, err := reg.(*nacosRegistry).subscribe(&url1)
+ reg, _ := newNacosRegistry(regurl)
+ listener, err := reg.(*nacosRegistry).subscribe(url1)
assert.Nil(t, err)
if err != nil {
t.Errorf("subscribe error:%s \n", err.Error())
diff --git a/registry/protocol/protocol.go b/registry/protocol/protocol.go
index 69a31ef..e3af9ba 100644
--- a/registry/protocol/protocol.go
+++ b/registry/protocol/protocol.go
@@ -130,31 +130,30 @@
}
// Refer provider service from registry center
-func (proto *registryProtocol) Refer(url common.URL) protocol.Invoker {
+func (proto *registryProtocol) Refer(url *common.URL) protocol.Invoker {
var registryUrl = url
var serviceUrl = registryUrl.SubURL
if registryUrl.Protocol == constant.REGISTRY_PROTOCOL {
- protocol := registryUrl.GetParam(constant.REGISTRY_KEY, "")
- registryUrl.Protocol = protocol
+ registryUrl.Protocol = registryUrl.GetParam(constant.REGISTRY_KEY, "")
}
var reg registry.Registry
if regI, loaded := proto.registries.Load(registryUrl.Key()); !loaded {
- reg = getRegistry(®istryUrl)
+ reg = getRegistry(registryUrl)
proto.registries.Store(registryUrl.Key(), reg)
} else {
reg = regI.(registry.Registry)
}
// new registry directory for store service url from registry
- directory, err := extension.GetDefaultRegistryDirectory(®istryUrl, reg)
+ directory, err := extension.GetDefaultRegistryDirectory(registryUrl, reg)
if err != nil {
logger.Errorf("consumer service %v create registry directory error, error message is %s, and will return nil invoker!",
serviceUrl.String(), err.Error())
return nil
}
- err = reg.Register(*serviceUrl)
+ err = reg.Register(serviceUrl)
if err != nil {
logger.Errorf("consumer service %v register registry %v error, error message is %s",
serviceUrl.String(), registryUrl.String(), err.Error())
@@ -194,7 +193,7 @@
}
registeredProviderUrl := getUrlToRegistry(providerUrl, registryUrl)
- err := reg.Register(*registeredProviderUrl)
+ err := reg.Register(registeredProviderUrl)
if err != nil {
logger.Errorf("provider service %v register registry %v error, error message is %s",
providerUrl.Key(), registryUrl.Key(), err.Error())
@@ -247,8 +246,8 @@
}
event := events[0]
- if isMatched(&(event.Service), nl.url) && event.Action == remoting.EventTypeAdd {
- nl.configurator = extension.GetDefaultConfigurator(&(event.Service))
+ if isMatched(event.Service, nl.url) && event.Action == remoting.EventTypeAdd {
+ nl.configurator = extension.GetDefaultConfigurator(event.Service)
nl.doOverrideIfNecessary()
}
}
@@ -275,9 +274,9 @@
}
if currentUrl.String() != providerUrl.String() {
- newRegUrl := nl.originInvoker.GetUrl()
- setProviderUrl(&newRegUrl, providerUrl)
- nl.protocol.reExport(nl.originInvoker, &newRegUrl)
+ newRegUrl := nl.originInvoker.GetUrl().Clone()
+ setProviderUrl(newRegUrl, providerUrl)
+ nl.protocol.reExport(nl.originInvoker, newRegUrl)
}
}
}
@@ -369,10 +368,9 @@
url := invoker.GetUrl()
// if the protocol == registry, set protocol the registry value in url.params
if url.Protocol == constant.REGISTRY_PROTOCOL {
- protocol := url.GetParam(constant.REGISTRY_KEY, "")
- url.Protocol = protocol
+ url.Protocol = url.GetParam(constant.REGISTRY_KEY, "")
}
- return &url
+ return url
}
func getProviderUrl(invoker protocol.Invoker) *common.URL {
@@ -401,7 +399,7 @@
func newWrappedInvoker(invoker protocol.Invoker, url *common.URL) *wrappedInvoker {
return &wrappedInvoker{
invoker: invoker,
- BaseInvoker: *protocol.NewBaseInvoker(*url),
+ BaseInvoker: *protocol.NewBaseInvoker(url),
}
}
diff --git a/registry/protocol/protocol_test.go b/registry/protocol/protocol_test.go
index 2d6e024..0fca552 100644
--- a/registry/protocol/protocol_test.go
+++ b/registry/protocol/protocol_test.go
@@ -59,7 +59,7 @@
common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
)
- url.SubURL = &suburl
+ url.SubURL = suburl
invoker := regProtocol.Refer(url)
assert.IsType(t, &protocol.BaseInvoker{}, invoker)
@@ -84,7 +84,7 @@
common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
)
- url2.SubURL = &suburl2
+ url2.SubURL = suburl2
regProtocol.Refer(url2)
var count int
@@ -105,7 +105,7 @@
common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
)
- url2.SubURL = &suburl2
+ url2.SubURL = suburl2
regProtocol.Refer(url2)
var count int
@@ -128,13 +128,13 @@
common.WithParamsValue(constant.VERSION_KEY, "1.0.0"),
)
- url.SubURL = &suburl
+ url.SubURL = suburl
invoker := protocol.NewBaseInvoker(url)
exporter := regProtocol.Export(invoker)
assert.IsType(t, &protocol.BaseExporter{}, exporter)
assert.Equal(t, exporter.GetInvoker().GetUrl().String(), suburl.String())
- return &url
+ return url
}
func TestExporter(t *testing.T) {
@@ -153,7 +153,7 @@
common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
)
- url2.SubURL = &suburl2
+ url2.SubURL = suburl2
invoker2 := protocol.NewBaseInvoker(url2)
regProtocol.Export(invoker2)
@@ -184,7 +184,7 @@
common.WithParamsValue(constant.VERSION_KEY, "1.0.0"),
)
- url2.SubURL = &suburl2
+ url2.SubURL = suburl2
invoker2 := protocol.NewBaseInvoker(url2)
regProtocol.Export(invoker2)
@@ -253,7 +253,7 @@
func TestExportWithServiceConfig(t *testing.T) {
extension.SetDefaultConfigurator(configurator.NewMockConfigurator)
ccUrl, _ := common.NewURL("mock://127.0.0.1:1111")
- dc, _ := (&config_center.MockDynamicConfigurationFactory{}).GetDynamicConfiguration(&ccUrl)
+ dc, _ := (&config_center.MockDynamicConfigurationFactory{}).GetDynamicConfiguration(ccUrl)
common_cfg.GetEnvInstance().SetDynamicConfiguration(dc)
regProtocol := newRegistryProtocol()
url := exporterNormal(t, regProtocol)
@@ -265,6 +265,7 @@
newUrl := url.SubURL.Clone()
newUrl.SetParam(constant.CLUSTER_KEY, "mock1")
+
v2, _ := regProtocol.bounds.Load(getCacheKey(newUrl))
assert.NotNil(t, v2)
}
@@ -272,7 +273,7 @@
func TestExportWithApplicationConfig(t *testing.T) {
extension.SetDefaultConfigurator(configurator.NewMockConfigurator)
ccUrl, _ := common.NewURL("mock://127.0.0.1:1111")
- dc, _ := (&config_center.MockDynamicConfigurationFactory{}).GetDynamicConfiguration(&ccUrl)
+ dc, _ := (&config_center.MockDynamicConfigurationFactory{}).GetDynamicConfiguration(ccUrl)
common_cfg.GetEnvInstance().SetDynamicConfiguration(dc)
regProtocol := newRegistryProtocol()
url := exporterNormal(t, regProtocol)
@@ -290,7 +291,7 @@
func TestGetProviderUrlWithHideKey(t *testing.T) {
url, _ := common.NewURL("dubbo://127.0.0.1:1111?a=a1&b=b1&.c=c1&.d=d1&e=e1&protocol=registry")
- providerUrl := getUrlToRegistry(&url, &url)
+ providerUrl := getUrlToRegistry(url, url)
assert.NotContains(t, providerUrl.GetParams(), ".c")
assert.NotContains(t, providerUrl.GetParams(), ".d")
assert.Contains(t, providerUrl.GetParams(), "a")
diff --git a/registry/registry.go b/registry/registry.go
index 2225d2c..73940fa 100644
--- a/registry/registry.go
+++ b/registry/registry.go
@@ -34,7 +34,7 @@
// Register is used for service provider calling, register services
// to registry. And it is also used for service consumer calling, register
// services cared about, for dubbo's admin monitoring.
- Register(url common.URL) error
+ Register(url *common.URL) error
// UnRegister is required to support the contract:
// 1. If it is the persistent stored data of dynamic=false, the
@@ -43,7 +43,7 @@
// 2. Unregister according to the full url match.
// url Registration information, is not allowed to be empty, e.g:
// dubbo://10.20.153.10/org.apache.dubbo.foo.BarService?version=1.0.0&application=kylin
- UnRegister(url common.URL) error
+ UnRegister(url *common.URL) error
// Subscribe is required to support the contract:
// When creating new registry extension, pls select one of the
diff --git a/registry/servicediscovery/instance/random/random_service_instance_selector.go b/registry/servicediscovery/instance/random/random_service_instance_selector.go
index 3f8f30d..7e4e0ee 100644
--- a/registry/servicediscovery/instance/random/random_service_instance_selector.go
+++ b/registry/servicediscovery/instance/random/random_service_instance_selector.go
@@ -41,7 +41,7 @@
return &RandomServiceInstanceSelector{}
}
-func (r *RandomServiceInstanceSelector) Select(url common.URL, serviceInstances []registry.ServiceInstance) registry.ServiceInstance {
+func (r *RandomServiceInstanceSelector) Select(url *common.URL, serviceInstances []registry.ServiceInstance) registry.ServiceInstance {
if len(serviceInstances) == 0 {
return nil
}
diff --git a/registry/servicediscovery/instance/random/random_service_instance_selector_test.go b/registry/servicediscovery/instance/random/random_service_instance_selector_test.go
index cddeb42..c53c058 100644
--- a/registry/servicediscovery/instance/random/random_service_instance_selector_test.go
+++ b/registry/servicediscovery/instance/random/random_service_instance_selector_test.go
@@ -52,5 +52,5 @@
Metadata: nil,
},
}
- assert.NotNil(t, selector.Select(common.URL{}, serviceInstances))
+ assert.NotNil(t, selector.Select(&common.URL{}, serviceInstances))
}
diff --git a/registry/servicediscovery/instance/service_instance_selector.go b/registry/servicediscovery/instance/service_instance_selector.go
index 82fb345..5690ab6 100644
--- a/registry/servicediscovery/instance/service_instance_selector.go
+++ b/registry/servicediscovery/instance/service_instance_selector.go
@@ -24,5 +24,5 @@
type ServiceInstanceSelector interface {
//Select an instance of ServiceInstance by the specified ServiceInstance service instances
- Select(url common.URL, serviceInstances []registry.ServiceInstance) registry.ServiceInstance
+ Select(url *common.URL, serviceInstances []registry.ServiceInstance) registry.ServiceInstance
}
diff --git a/registry/servicediscovery/service_discovery_registry.go b/registry/servicediscovery/service_discovery_registry.go
index 4db2c5a..ad6ec98 100644
--- a/registry/servicediscovery/service_discovery_registry.go
+++ b/registry/servicediscovery/service_discovery_registry.go
@@ -26,7 +26,6 @@
)
import (
- cm "github.com/Workiva/go-datastructures/common"
gxset "github.com/dubbogo/gost/container/set"
perrors "github.com/pkg/errors"
"go.uber.org/atomic"
@@ -70,7 +69,7 @@
metaDataService service.MetadataService
registeredListeners *gxset.HashSet
subscribedURLsSynthesizers []synthesizer.SubscribedURLsSynthesizer
- serviceRevisionExportedURLsCache map[string]map[string][]common.URL
+ serviceRevisionExportedURLsCache map[string]map[string][]*common.URL
}
func newServiceDiscoveryRegistry(url *common.URL) (registry.Registry, error) {
@@ -94,13 +93,13 @@
subscribedServices: subscribedServices,
subscribedURLsSynthesizers: subscribedURLsSynthesizers,
registeredListeners: gxset.NewSet(),
- serviceRevisionExportedURLsCache: make(map[string]map[string][]common.URL, 8),
+ serviceRevisionExportedURLsCache: make(map[string]map[string][]*common.URL, 8),
serviceNameMapping: serviceNameMapping,
metaDataService: metaDataService,
}, nil
}
-func (s *serviceDiscoveryRegistry) UnRegister(url common.URL) error {
+func (s *serviceDiscoveryRegistry) UnRegister(url *common.URL) error {
if !shouldRegister(url) {
return nil
}
@@ -108,10 +107,10 @@
}
func (s *serviceDiscoveryRegistry) UnSubscribe(url *common.URL, listener registry.NotifyListener) error {
- if !shouldSubscribe(*url) {
+ if !shouldSubscribe(url) {
return nil
}
- return s.metaDataService.UnsubscribeURL(*url)
+ return s.metaDataService.UnsubscribeURL(url)
}
func creatServiceDiscovery(url *common.URL) (registry.ServiceDiscovery, error) {
@@ -145,8 +144,8 @@
return s.serviceDiscovery
}
-func (s *serviceDiscoveryRegistry) GetUrl() common.URL {
- return *s.url
+func (s *serviceDiscoveryRegistry) GetUrl() *common.URL {
+ return s.url
}
func (s *serviceDiscoveryRegistry) IsAvailable() bool {
@@ -161,7 +160,7 @@
}
}
-func (s *serviceDiscoveryRegistry) Register(url common.URL) error {
+func (s *serviceDiscoveryRegistry) Register(url *common.URL) error {
if !shouldRegister(url) {
return nil
}
@@ -185,7 +184,7 @@
url.Protocol)
}
-func shouldRegister(url common.URL) bool {
+func shouldRegister(url *common.URL) bool {
side := url.GetParam(constant.SIDE_KEY, "")
if side == constant.PROVIDER_PROTOCOL {
return true
@@ -195,14 +194,14 @@
}
func (s *serviceDiscoveryRegistry) Subscribe(url *common.URL, notify registry.NotifyListener) error {
- if !shouldSubscribe(*url) {
+ if !shouldSubscribe(url) {
return nil
}
- _, err := s.metaDataService.SubscribeURL(*url)
+ _, err := s.metaDataService.SubscribeURL(url)
if err != nil {
return perrors.WithMessage(err, "subscribe url error: "+url.String())
}
- services := s.getServices(*url)
+ services := s.getServices(url)
if services.Empty() {
return perrors.Errorf("Should has at least one way to know which services this interface belongs to, "+
"subscription url:%s", url.String())
@@ -218,12 +217,12 @@
serviceDiscoveryRegistry: s,
},
}
- s.registerServiceInstancesChangedListener(*url, listener)
+ s.registerServiceInstancesChangedListener(url, listener)
}
return nil
}
-func (s *serviceDiscoveryRegistry) registerServiceInstancesChangedListener(url common.URL, listener *registry.ServiceInstancesChangedListener) {
+func (s *serviceDiscoveryRegistry) registerServiceInstancesChangedListener(url *common.URL, listener *registry.ServiceInstancesChangedListener) {
listenerId := listener.ServiceName + ":" + getUrlKey(url)
if !s.subscribedServices.Contains(listenerId) {
err := s.serviceDiscovery.AddListener(listener)
@@ -234,7 +233,7 @@
}
-func getUrlKey(url common.URL) string {
+func getUrlKey(url *common.URL) string {
var bf bytes.Buffer
if len(url.Protocol) != 0 {
bf.WriteString(url.Protocol)
@@ -256,7 +255,7 @@
return bf.String()
}
-func appendParam(buffer bytes.Buffer, paramKey string, url common.URL) {
+func appendParam(buffer bytes.Buffer, paramKey string, url *common.URL) {
buffer.WriteString(paramKey)
buffer.WriteString("=")
buffer.WriteString(url.GetParam(paramKey, ""))
@@ -268,8 +267,8 @@
logger.Warnf("here is no instance in service[name : %s]", serviceName)
return
}
- var subscribedURLs []common.URL
- subscribedURLs = append(subscribedURLs, s.getExportedUrls(*url, serviceInstances)...)
+ var subscribedURLs []*common.URL
+ subscribedURLs = append(subscribedURLs, s.getExportedUrls(url, serviceInstances)...)
if len(subscribedURLs) == 0 {
subscribedURLs = s.synthesizeSubscribedURLs(url, serviceInstances)
}
@@ -282,8 +281,8 @@
}
-func (s *serviceDiscoveryRegistry) synthesizeSubscribedURLs(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []common.URL {
- var urls []common.URL
+func (s *serviceDiscoveryRegistry) synthesizeSubscribedURLs(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []*common.URL {
+ var urls []*common.URL
for _, syn := range s.subscribedURLsSynthesizers {
if syn.Support(subscribedURL) {
urls = append(urls, syn.Synthesize(subscribedURL, serviceInstances)...)
@@ -292,11 +291,11 @@
return urls
}
-func shouldSubscribe(url common.URL) bool {
+func shouldSubscribe(url *common.URL) bool {
return !shouldRegister(url)
}
-func (s *serviceDiscoveryRegistry) getServices(url common.URL) *gxset.HashSet {
+func (s *serviceDiscoveryRegistry) getServices(url *common.URL) *gxset.HashSet {
services := gxset.NewSet()
serviceNames := url.GetParam(constant.PROVIDER_BY, "")
if len(serviceNames) > 0 {
@@ -311,7 +310,7 @@
return services
}
-func (s *serviceDiscoveryRegistry) findMappedServices(url common.URL) *gxset.HashSet {
+func (s *serviceDiscoveryRegistry) findMappedServices(url *common.URL) *gxset.HashSet {
serviceInterface := url.GetParam(constant.INTERFACE_KEY, url.Path)
group := url.GetParam(constant.GROUP_KEY, "")
version := url.GetParam(constant.VERSION_KEY, "")
@@ -325,7 +324,7 @@
return serviceNames
}
-func (s *serviceDiscoveryRegistry) getExportedUrls(subscribedURL common.URL, serviceInstances []registry.ServiceInstance) []common.URL {
+func (s *serviceDiscoveryRegistry) getExportedUrls(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []*common.URL {
var filterInstances []registry.ServiceInstance
for _, s := range serviceInstances {
if !s.IsEnable() || !s.IsHealthy() {
@@ -340,32 +339,15 @@
filterInstances = append(filterInstances, s)
}
if len(filterInstances) == 0 {
- return []common.URL{}
+ return []*common.URL{}
}
s.prepareServiceRevisionExportedURLs(filterInstances)
subscribedURLs := s.cloneExportedURLs(subscribedURL, filterInstances)
return subscribedURLs
}
-// comparator is defined as Comparator for skip list to compare the URL
-type comparator common.URL
-
-// Compare is defined as Comparator for skip list to compare the URL
-func (c comparator) Compare(comp cm.Comparator) int {
- a := common.URL(c).String()
- b := common.URL(comp.(comparator)).String()
- switch {
- case a > b:
- return 1
- case a < b:
- return -1
- default:
- return 0
- }
-}
-
-func (s *serviceDiscoveryRegistry) getExportedUrlsByInst(serviceInstance registry.ServiceInstance) []common.URL {
- var urls []common.URL
+func (s *serviceDiscoveryRegistry) getExportedUrlsByInst(serviceInstance registry.ServiceInstance) []*common.URL {
+ var urls []*common.URL
metadataStorageType := getExportedStoreType(serviceInstance)
proxyFactory := extension.GetMetadataServiceProxyFactory(metadataStorageType)
if proxyFactory == nil {
@@ -381,7 +363,7 @@
return urls
}
- ret := make([]common.URL, 0, len(result))
+ ret := make([]*common.URL, 0, len(result))
for _, ui := range result {
u, err := common.NewURL(ui.(string))
@@ -464,18 +446,18 @@
logger.Errorf("get service instance selector cathe error:%s", err.Error())
return nil
}
- return selector.Select(*s.url, serviceInstances)
+ return selector.Select(s.url, serviceInstances)
}
-func (s *serviceDiscoveryRegistry) initRevisionExportedURLsByInst(serviceInstance registry.ServiceInstance) []common.URL {
+func (s *serviceDiscoveryRegistry) initRevisionExportedURLsByInst(serviceInstance registry.ServiceInstance) []*common.URL {
if serviceInstance == nil {
- return []common.URL{}
+ return nil
}
serviceName := serviceInstance.GetServiceName()
revision := getExportedServicesRevision(serviceInstance)
revisionExportedURLsMap := s.serviceRevisionExportedURLsCache[serviceName]
if revisionExportedURLsMap == nil {
- revisionExportedURLsMap = make(map[string][]common.URL, 4)
+ revisionExportedURLsMap = make(map[string][]*common.URL, 4)
s.serviceRevisionExportedURLsCache[serviceName] = revisionExportedURLsMap
}
revisionExportedURLs := revisionExportedURLsMap[revision]
@@ -521,11 +503,11 @@
return result
}
-func (s *serviceDiscoveryRegistry) cloneExportedURLs(url common.URL, serviceInsances []registry.ServiceInstance) []common.URL {
+func (s *serviceDiscoveryRegistry) cloneExportedURLs(url *common.URL, serviceInsances []registry.ServiceInstance) []*common.URL {
if len(serviceInsances) == 0 {
- return []common.URL{}
+ return []*common.URL{}
}
- var clonedExportedURLs []common.URL
+ var clonedExportedURLs []*common.URL
removeParamSet := gxset.NewSet()
removeParamSet.Add(constant.PID_KEY)
removeParamSet.Add(constant.TIMESTAMP_KEY)
@@ -540,7 +522,7 @@
}
cloneUrl := u.CloneExceptParams(removeParamSet)
- clonedExportedURLs = append(clonedExportedURLs, *cloneUrl)
+ clonedExportedURLs = append(clonedExportedURLs, cloneUrl)
}
}
return clonedExportedURLs
@@ -548,8 +530,8 @@
}
type endpoint struct {
- Port int `json:"port, omitempty"`
- Protocol string `json:"protocol, omitempty"`
+ Port int `json:"port,omitempty"`
+ Protocol string `json:"protocol,omitempty"`
}
func getProtocolPort(serviceInstance registry.ServiceInstance, protocol string) int {
@@ -571,38 +553,38 @@
}
return -1
}
-func (s *serviceDiscoveryRegistry) getTemplateExportedURLs(url common.URL, serviceInstance registry.ServiceInstance) []common.URL {
+func (s *serviceDiscoveryRegistry) getTemplateExportedURLs(url *common.URL, serviceInstance registry.ServiceInstance) []*common.URL {
exportedURLs := s.getRevisionExportedURLs(serviceInstance)
if len(exportedURLs) == 0 {
- return []common.URL{}
+ return []*common.URL{}
}
return filterSubscribedURLs(url, exportedURLs)
}
-func (s *serviceDiscoveryRegistry) getRevisionExportedURLs(serviceInstance registry.ServiceInstance) []common.URL {
+func (s *serviceDiscoveryRegistry) getRevisionExportedURLs(serviceInstance registry.ServiceInstance) []*common.URL {
if serviceInstance == nil {
- return []common.URL{}
+ return []*common.URL{}
}
serviceName := serviceInstance.GetServiceName()
revision := getExportedServicesRevision(serviceInstance)
s.lock.RLock()
revisionExportedURLsMap, exist := s.serviceRevisionExportedURLsCache[serviceName]
if !exist {
- return []common.URL{}
+ return []*common.URL{}
}
exportedURLs, exist := revisionExportedURLsMap[revision]
if !exist {
- return []common.URL{}
+ return []*common.URL{}
}
s.lock.RUnlock()
// Get a copy from source in order to prevent the caller trying to change the cached data
- cloneExportedURLs := make([]common.URL, len(exportedURLs))
+ cloneExportedURLs := make([]*common.URL, len(exportedURLs))
copy(cloneExportedURLs, exportedURLs)
return cloneExportedURLs
}
-func filterSubscribedURLs(subscribedURL common.URL, exportedURLs []common.URL) []common.URL {
- var filterExportedURLs []common.URL
+func filterSubscribedURLs(subscribedURL *common.URL, exportedURLs []*common.URL) []*common.URL {
+ var filterExportedURLs []*common.URL
for _, url := range exportedURLs {
if url.GetParam(constant.INTERFACE_KEY, url.Path) != subscribedURL.GetParam(constant.INTERFACE_KEY, url.Path) {
break
diff --git a/registry/servicediscovery/service_discovery_registry_test.go b/registry/servicediscovery/service_discovery_registry_test.go
index 53eb865..ad6b73d 100644
--- a/registry/servicediscovery/service_discovery_registry_test.go
+++ b/registry/servicediscovery/service_discovery_registry_test.go
@@ -76,7 +76,7 @@
"&service_discovery=mock" +
"&methods=getAllServiceKeys,getServiceRestMetadata,getExportedURLs,getAllExportedURLs" +
"&side=provider")
- registry, err := newServiceDiscoveryRegistry(®istryURL)
+ registry, err := newServiceDiscoveryRegistry(registryURL)
assert.Nil(t, err)
assert.NotNil(t, registry)
registry.Register(url)
@@ -85,19 +85,19 @@
type mockEventDispatcher struct {
}
-func (m *mockEventDispatcher) AddEventListener(listener observer.EventListener) {
+func (m *mockEventDispatcher) AddEventListener(observer.EventListener) {
}
-func (m *mockEventDispatcher) AddEventListeners(listenersSlice []observer.EventListener) {
+func (m *mockEventDispatcher) AddEventListeners([]observer.EventListener) {
}
-func (m *mockEventDispatcher) RemoveEventListener(listener observer.EventListener) {
+func (m *mockEventDispatcher) RemoveEventListener(observer.EventListener) {
panic("implement me")
}
-func (m *mockEventDispatcher) RemoveEventListeners(listenersSlice []observer.EventListener) {
+func (m *mockEventDispatcher) RemoveEventListeners([]observer.EventListener) {
panic("implement me")
}
@@ -109,17 +109,17 @@
panic("implement me")
}
-func (m *mockEventDispatcher) Dispatch(event observer.Event) {
+func (m *mockEventDispatcher) Dispatch(observer.Event) {
}
type mockServiceNameMapping struct {
}
-func (m *mockServiceNameMapping) Map(serviceInterface string, group string, version string, protocol string) error {
+func (m *mockServiceNameMapping) Map(string, string, string, string) error {
return nil
}
-func (m *mockServiceNameMapping) Get(serviceInterface string, group string, version string, protocol string) (*gxset.HashSet, error) {
+func (m *mockServiceNameMapping) Get(string, string, string, string) (*gxset.HashSet, error) {
panic("implement me")
}
@@ -134,15 +134,15 @@
panic("implement me")
}
-func (m *mockServiceDiscovery) Register(instance registry.ServiceInstance) error {
+func (m *mockServiceDiscovery) Register(registry.ServiceInstance) error {
return nil
}
-func (m *mockServiceDiscovery) Update(instance registry.ServiceInstance) error {
+func (m *mockServiceDiscovery) Update(registry.ServiceInstance) error {
panic("implement me")
}
-func (m *mockServiceDiscovery) Unregister(instance registry.ServiceInstance) error {
+func (m *mockServiceDiscovery) Unregister(registry.ServiceInstance) error {
panic("implement me")
}
@@ -154,35 +154,35 @@
panic("implement me")
}
-func (m *mockServiceDiscovery) GetInstances(serviceName string) []registry.ServiceInstance {
+func (m *mockServiceDiscovery) GetInstances(string) []registry.ServiceInstance {
panic("implement me")
}
-func (m *mockServiceDiscovery) GetInstancesByPage(serviceName string, offset int, pageSize int) gxpage.Pager {
+func (m *mockServiceDiscovery) GetInstancesByPage(string, int, int) gxpage.Pager {
panic("implement me")
}
-func (m *mockServiceDiscovery) GetHealthyInstancesByPage(serviceName string, offset int, pageSize int, healthy bool) gxpage.Pager {
+func (m *mockServiceDiscovery) GetHealthyInstancesByPage(string, int, int, bool) gxpage.Pager {
panic("implement me")
}
-func (m *mockServiceDiscovery) GetRequestInstances(serviceNames []string, offset int, requestedSize int) map[string]gxpage.Pager {
+func (m *mockServiceDiscovery) GetRequestInstances([]string, int, int) map[string]gxpage.Pager {
panic("implement me")
}
-func (m *mockServiceDiscovery) AddListener(listener *registry.ServiceInstancesChangedListener) error {
+func (m *mockServiceDiscovery) AddListener(*registry.ServiceInstancesChangedListener) error {
panic("implement me")
}
-func (m *mockServiceDiscovery) DispatchEventByServiceName(serviceName string) error {
+func (m *mockServiceDiscovery) DispatchEventByServiceName(string) error {
panic("implement me")
}
-func (m *mockServiceDiscovery) DispatchEventForInstances(serviceName string, instances []registry.ServiceInstance) error {
+func (m *mockServiceDiscovery) DispatchEventForInstances(string, []registry.ServiceInstance) error {
panic("implement me")
}
-func (m *mockServiceDiscovery) DispatchEvent(event *registry.ServiceInstancesChangedEvent) error {
+func (m *mockServiceDiscovery) DispatchEvent(*registry.ServiceInstancesChangedEvent) error {
panic("implement me")
}
@@ -197,27 +197,27 @@
panic("implement me")
}
-func (m *mockMetadataService) ExportURL(url common.URL) (bool, error) {
+func (m *mockMetadataService) ExportURL(*common.URL) (bool, error) {
return true, nil
}
-func (m *mockMetadataService) UnexportURL(url common.URL) error {
+func (m *mockMetadataService) UnexportURL(*common.URL) error {
panic("implement me")
}
-func (m *mockMetadataService) SubscribeURL(url common.URL) (bool, error) {
+func (m *mockMetadataService) SubscribeURL(*common.URL) (bool, error) {
panic("implement me")
}
-func (m *mockMetadataService) UnsubscribeURL(url common.URL) error {
+func (m *mockMetadataService) UnsubscribeURL(*common.URL) error {
panic("implement me")
}
-func (m *mockMetadataService) PublishServiceDefinition(url common.URL) error {
+func (m *mockMetadataService) PublishServiceDefinition(*common.URL) error {
return nil
}
-func (m *mockMetadataService) GetExportedURLs(serviceInterface string, group string, version string, protocol string) ([]interface{}, error) {
+func (m *mockMetadataService) GetExportedURLs(string, string, string, string) ([]interface{}, error) {
panic("implement me")
}
@@ -225,19 +225,19 @@
panic("implement me")
}
-func (m *mockMetadataService) GetSubscribedURLs() ([]common.URL, error) {
+func (m *mockMetadataService) GetSubscribedURLs() ([]*common.URL, error) {
panic("implement me")
}
-func (m *mockMetadataService) GetServiceDefinition(interfaceName string, group string, version string) (string, error) {
+func (m *mockMetadataService) GetServiceDefinition(string, string, string) (string, error) {
panic("implement me")
}
-func (m *mockMetadataService) GetServiceDefinitionByServiceKey(serviceKey string) (string, error) {
+func (m *mockMetadataService) GetServiceDefinitionByServiceKey(string) (string, error) {
panic("implement me")
}
-func (m *mockMetadataService) RefreshMetadata(exportedRevision string, subscribedRevision string) (bool, error) {
+func (m *mockMetadataService) RefreshMetadata(string, string) (bool, error) {
panic("implement me")
}
diff --git a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
index 086a26d..d1ab611 100644
--- a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
+++ b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
@@ -44,8 +44,8 @@
return false
}
-func (r RestSubscribedURLsSynthesizer) Synthesize(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []common.URL {
- urls := make([]common.URL, len(serviceInstances), len(serviceInstances))
+func (r RestSubscribedURLsSynthesizer) Synthesize(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []*common.URL {
+ urls := make([]*common.URL, len(serviceInstances), len(serviceInstances))
for i, s := range serviceInstances {
splitHost := strings.Split(s.GetHost(), ":")
u := common.NewURLWithOptions(common.WithProtocol(subscribedURL.Protocol), common.WithIp(splitHost[0]),
@@ -55,7 +55,7 @@
common.WithParamsValue(constant.APPLICATION_KEY, s.GetServiceName()),
common.WithParamsValue(constant.REGISTRY_KEY, "true"),
)
- urls[i] = *u
+ urls[i] = u
}
return urls
}
diff --git a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer_test.go b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer_test.go
index b52cc23..1bb38c9 100644
--- a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer_test.go
+++ b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer_test.go
@@ -56,7 +56,7 @@
},
}
- var expectUrls []common.URL
+ var expectUrls []*common.URL
u1 := common.NewURLWithOptions(common.WithProtocol("rest"), common.WithIp("127.0.0.1"),
common.WithPort("80"), common.WithPath("org.apache.dubbo-go.mockService"),
common.WithParams(url.Values{}),
@@ -69,7 +69,7 @@
common.WithParamsValue(constant.SIDE_KEY, constant.PROVIDER_PROTOCOL),
common.WithParamsValue(constant.APPLICATION_KEY, "test2"),
common.WithParamsValue(constant.REGISTRY_KEY, "true"))
- expectUrls = append(expectUrls, *u1, *u2)
- result := syn.Synthesize(&subUrl, instances)
+ expectUrls = append(expectUrls, u1, u2)
+ result := syn.Synthesize(subUrl, instances)
assert.Equal(t, expectUrls, result)
}
diff --git a/registry/servicediscovery/synthesizer/subscribed_urls_synthesizer.go b/registry/servicediscovery/synthesizer/subscribed_urls_synthesizer.go
index 415ca35..557c86e 100644
--- a/registry/servicediscovery/synthesizer/subscribed_urls_synthesizer.go
+++ b/registry/servicediscovery/synthesizer/subscribed_urls_synthesizer.go
@@ -27,5 +27,5 @@
// Supports the synthesis of the subscribed url or not
Support(subscribedURL *common.URL) bool
// synthesize the subscribed url
- Synthesize(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []common.URL
+ Synthesize(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []*common.URL
}
diff --git a/registry/zookeeper/listener.go b/registry/zookeeper/listener.go
index ec82fa0..3b8a51e 100644
--- a/registry/zookeeper/listener.go
+++ b/registry/zookeeper/listener.go
@@ -158,7 +158,7 @@
//r.update(e.res)
//write to invoker
//r.outerEventCh <- e.res
- return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(common.URL)}, nil
+ return ®istry.ServiceEvent{Action: e.ConfigType, Service: e.Value.(*common.URL)}, nil
}
}
}
diff --git a/registry/zookeeper/listener_test.go b/registry/zookeeper/listener_test.go
index a0e9147..20ec1cf 100644
--- a/registry/zookeeper/listener_test.go
+++ b/registry/zookeeper/listener_test.go
@@ -34,7 +34,7 @@
func Test_DataChange(t *testing.T) {
listener := NewRegistryDataListener()
url, _ := common.NewURL("jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-1.3.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100")
- listener.SubscribeURL(&url, &MockConfigurationListener{})
+ listener.SubscribeURL(url, &MockConfigurationListener{})
int := listener.DataChange(remoting.Event{Path: "/dubbo/com.ikurento.user.UserProvider/providers/jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-1.3.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100"})
assert.Equal(t, true, int)
}
diff --git a/registry/zookeeper/registry_test.go b/registry/zookeeper/registry_test.go
index d915fc2..e630db7 100644
--- a/registry/zookeeper/registry_test.go
+++ b/registry/zookeeper/registry_test.go
@@ -37,7 +37,7 @@
regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithParamsValue("serviceid", "soa.mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
- ts, reg, _ := newMockZkRegistry(®url)
+ ts, reg, _ := newMockZkRegistry(regurl)
defer ts.Stop()
err := reg.Register(url)
children, _ := reg.client.GetChildren("/dubbo/com.ikurento.user.UserProvider/providers")
@@ -50,7 +50,7 @@
regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithParamsValue("serviceid", "soa.mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
- ts, reg, _ := newMockZkRegistry(®url)
+ ts, reg, _ := newMockZkRegistry(regurl)
defer ts.Stop()
err := reg.Register(url)
children, _ := reg.client.GetChildren("/dubbo/com.ikurento.user.UserProvider/providers")
@@ -73,7 +73,7 @@
func Test_Subscribe(t *testing.T) {
regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
- ts, reg, _ := newMockZkRegistry(®url)
+ ts, reg, _ := newMockZkRegistry(regurl)
//provider register
err := reg.Register(url)
@@ -85,10 +85,10 @@
//consumer register
regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER))
- _, reg2, _ := newMockZkRegistry(®url, zookeeper.WithTestCluster(ts))
+ _, reg2, _ := newMockZkRegistry(regurl, zookeeper.WithTestCluster(ts))
reg2.Register(url)
- listener, _ := reg2.DoSubscribe(&url)
+ listener, _ := reg2.DoSubscribe(url)
serviceEvent, _ := listener.Next()
assert.NoError(t, err)
@@ -102,7 +102,7 @@
func Test_UnSubscribe(t *testing.T) {
regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
- ts, reg, _ := newMockZkRegistry(®url)
+ ts, reg, _ := newMockZkRegistry(regurl)
//provider register
err := reg.Register(url)
@@ -114,10 +114,10 @@
//consumer register
regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER))
- _, reg2, _ := newMockZkRegistry(®url, zookeeper.WithTestCluster(ts))
+ _, reg2, _ := newMockZkRegistry(regurl, zookeeper.WithTestCluster(ts))
reg2.Register(url)
- listener, _ := reg2.DoSubscribe(&url)
+ listener, _ := reg2.DoSubscribe(url)
serviceEvent, _ := listener.Next()
assert.NoError(t, err)
@@ -126,7 +126,7 @@
}
assert.Regexp(t, ".*ServiceEvent{Action{add}.*", serviceEvent.String())
- reg2.UnSubscribe(&url, nil)
+ reg2.UnSubscribe(url, nil)
assert.Nil(t, reg2.listener)
defer ts.Stop()
@@ -136,13 +136,13 @@
regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER)))
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
- ts, reg, err := newMockZkRegistry(®url)
+ ts, reg, err := newMockZkRegistry(regurl)
defer ts.Stop()
assert.NoError(t, err)
err = reg.Register(url)
assert.NoError(t, err)
- _, err = reg.DoSubscribe(&url)
+ _, err = reg.DoSubscribe(url)
assert.NoError(t, err)
//listener.Close()
@@ -156,7 +156,7 @@
regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
- ts, reg, err := newMockZkRegistry(®url)
+ ts, reg, err := newMockZkRegistry(regurl)
defer ts.Stop()
assert.NoError(t, err)
diff --git a/registry/zookeeper/service_discovery.go b/registry/zookeeper/service_discovery.go
index 5ad83ef..6d9582f 100644
--- a/registry/zookeeper/service_discovery.go
+++ b/registry/zookeeper/service_discovery.go
@@ -154,8 +154,8 @@
}
// nolint
-func (zksd *zookeeperServiceDiscovery) GetUrl() common.URL {
- return *zksd.url
+func (zksd *zookeeperServiceDiscovery) GetUrl() *common.URL {
+ return zksd.url
}
// nolint
diff --git a/remoting/etcdv3/listener.go b/remoting/etcdv3/listener.go
index 4f80a89..c66928a 100644
--- a/remoting/etcdv3/listener.go
+++ b/remoting/etcdv3/listener.go
@@ -129,8 +129,6 @@
default:
return false
}
-
- panic("unreachable")
}
// ListenServiceNodeEventWithPrefix listens on a set of key with spec prefix
diff --git a/remoting/exchange_client.go b/remoting/exchange_client.go
index 26fa5d5..b3423eb 100644
--- a/remoting/exchange_client.go
+++ b/remoting/exchange_client.go
@@ -42,7 +42,7 @@
// responseHandler is used to deal with msg
SetResponseHandler(responseHandler ResponseHandler)
// connect url
- Connect(url common.URL) error
+ Connect(url *common.URL) error
// close
Close()
// send request to server.
@@ -69,7 +69,7 @@
}
// create ExchangeClient
-func NewExchangeClient(url common.URL, client Client, connectTimeout time.Duration, lazyInit bool) *ExchangeClient {
+func NewExchangeClient(url *common.URL, client Client, connectTimeout time.Duration, lazyInit bool) *ExchangeClient {
exchangeClient := &ExchangeClient{
ConnectTimeout: connectTimeout,
address: url.Location,
@@ -86,7 +86,7 @@
return exchangeClient
}
-func (cl *ExchangeClient) doInit(url common.URL) error {
+func (cl *ExchangeClient) doInit(url *common.URL) error {
if cl.init {
return nil
}
@@ -104,7 +104,7 @@
}
// two way request
-func (client *ExchangeClient) Request(invocation *protocol.Invocation, url common.URL, timeout time.Duration,
+func (client *ExchangeClient) Request(invocation *protocol.Invocation, url *common.URL, timeout time.Duration,
result *protocol.RPCResult) error {
if er := client.doInit(url); er != nil {
return er
@@ -134,7 +134,7 @@
}
// async two way request
-func (client *ExchangeClient) AsyncRequest(invocation *protocol.Invocation, url common.URL, timeout time.Duration,
+func (client *ExchangeClient) AsyncRequest(invocation *protocol.Invocation, url *common.URL, timeout time.Duration,
callback common.AsyncCallback, result *protocol.RPCResult) error {
if er := client.doInit(url); er != nil {
return er
@@ -160,7 +160,7 @@
}
// oneway request
-func (client *ExchangeClient) Send(invocation *protocol.Invocation, url common.URL, timeout time.Duration) error {
+func (client *ExchangeClient) Send(invocation *protocol.Invocation, url *common.URL, timeout time.Duration) error {
if er := client.doInit(url); er != nil {
return er
}
@@ -204,7 +204,7 @@
if pendingResponse.Callback == nil {
pendingResponse.Err = pendingResponse.response.Error
- pendingResponse.Done <- struct{}{}
+ close(pendingResponse.Done)
} else {
pendingResponse.Callback(pendingResponse.GetCallResponse())
}
diff --git a/remoting/exchange_server.go b/remoting/exchange_server.go
index a31e994..a8d7c73 100644
--- a/remoting/exchange_server.go
+++ b/remoting/exchange_server.go
@@ -32,11 +32,11 @@
// This is abstraction level. it is like facade.
type ExchangeServer struct {
Server Server
- Url common.URL
+ Url *common.URL
}
// Create ExchangeServer
-func NewExchangeServer(url common.URL, server Server) *ExchangeServer {
+func NewExchangeServer(url *common.URL, server Server) *ExchangeServer {
exchangServer := &ExchangeServer{
Server: server,
Url: url,
diff --git a/remoting/getty/dubbo_codec_for_test.go b/remoting/getty/dubbo_codec_for_test.go
index b91fc9f..fca5da8 100644
--- a/remoting/getty/dubbo_codec_for_test.go
+++ b/remoting/getty/dubbo_codec_for_test.go
@@ -55,15 +55,15 @@
if !ok {
return nil, perrors.Errorf("encode request failed for parameter type :%+v", request)
}
- invocation := *invoc
+ tmpInvocation := invoc
svc := impl.Service{}
- svc.Path = invocation.AttachmentsByKey(constant.PATH_KEY, "")
- svc.Interface = invocation.AttachmentsByKey(constant.INTERFACE_KEY, "")
- svc.Version = invocation.AttachmentsByKey(constant.VERSION_KEY, "")
- svc.Group = invocation.AttachmentsByKey(constant.GROUP_KEY, "")
- svc.Method = invocation.MethodName()
- timeout, err := strconv.Atoi(invocation.AttachmentsByKey(constant.TIMEOUT_KEY, strconv.Itoa(constant.DEFAULT_REMOTING_TIMEOUT)))
+ svc.Path = tmpInvocation.AttachmentsByKey(constant.PATH_KEY, "")
+ svc.Interface = tmpInvocation.AttachmentsByKey(constant.INTERFACE_KEY, "")
+ svc.Version = tmpInvocation.AttachmentsByKey(constant.VERSION_KEY, "")
+ svc.Group = tmpInvocation.AttachmentsByKey(constant.GROUP_KEY, "")
+ svc.Method = tmpInvocation.MethodName()
+ timeout, err := strconv.Atoi(tmpInvocation.AttachmentsByKey(constant.TIMEOUT_KEY, strconv.Itoa(constant.DEFAULT_REMOTING_TIMEOUT)))
if err != nil {
// it will be wrapped in readwrite.Write .
return nil, perrors.WithStack(err)
@@ -71,7 +71,7 @@
svc.Timeout = time.Duration(timeout)
header := impl.DubboHeader{}
- serialization := invocation.AttachmentsByKey(constant.SERIALIZATION_KEY, constant.HESSIAN2_SERIALIZATION)
+ serialization := tmpInvocation.AttachmentsByKey(constant.SERIALIZATION_KEY, constant.HESSIAN2_SERIALIZATION)
if serialization == constant.PROTOBUF_SERIALIZATION {
header.SerialID = constant.S_Proto
} else {
@@ -87,7 +87,7 @@
pkg := &impl.DubboPackage{
Header: header,
Service: svc,
- Body: impl.NewRequestPayload(invocation.Arguments(), invocation.Attachments()),
+ Body: impl.NewRequestPayload(tmpInvocation.Arguments(), tmpInvocation.Attachments()),
Err: nil,
Codec: impl.NewDubboCodec(nil),
}
diff --git a/remoting/getty/getty_client.go b/remoting/getty/getty_client.go
index 7edc1cf..d4d20d9 100644
--- a/remoting/getty/getty_client.go
+++ b/remoting/getty/getty_client.go
@@ -151,7 +151,7 @@
}
// init client and try to connection.
-func (c *Client) Connect(url common.URL) error {
+func (c *Client) Connect(url *common.URL) error {
initClient(url.Protocol)
c.conf = *clientConf
// new client
diff --git a/remoting/getty/getty_client_test.go b/remoting/getty/getty_client_test.go
index 41ca310..6b8e3ec 100644
--- a/remoting/getty/getty_client_test.go
+++ b/remoting/getty/getty_client_test.go
@@ -51,7 +51,7 @@
svr.Stop()
}
-func testRequestOneWay(t *testing.T, svr *Server, url common.URL, client *Client) {
+func testRequestOneWay(t *testing.T, svr *Server, url *common.URL, client *Client) {
request := remoting.NewRequest("2.0.2")
up := &UserProvider{}
@@ -80,7 +80,7 @@
}
}
-func getClient(url common.URL) *Client {
+func getClient(url *common.URL) *Client {
client := NewClient(Options{
ConnectTimeout: config.GetConsumerConfig().ConnectTimeout,
})
@@ -92,7 +92,7 @@
return client
}
-func testClient_Call(t *testing.T, svr *Server, url common.URL, c *Client) {
+func testClient_Call(t *testing.T, svr *Server, url *common.URL, c *Client) {
c.pool = newGettyRPCClientConnPool(c, clientConf.PoolSize, time.Duration(int(time.Second)*clientConf.PoolTTL))
testGetBigPkg(t, c)
@@ -309,7 +309,7 @@
assert.Equal(t, User{Id: "1", Name: ""}, *user)
}
-func testClient_AsyncCall(t *testing.T, svr *Server, url common.URL, client *Client) {
+func testClient_AsyncCall(t *testing.T, svr *Server, url *common.URL, client *Client) {
user := &User{}
lock := sync.Mutex{}
request := remoting.NewRequest("2.0.2")
@@ -337,7 +337,7 @@
time.Sleep(1 * time.Second)
}
-func InitTest(t *testing.T) (*Server, common.URL) {
+func InitTest(t *testing.T) (*Server, *common.URL) {
hessian.RegisterPOJO(&User{})
remoting.RegistryCodec("dubbo", &DubboTestCodec{})
diff --git a/remoting/getty/getty_server.go b/remoting/getty/getty_server.go
index 7c8fa29..ab574ec 100644
--- a/remoting/getty/getty_server.go
+++ b/remoting/getty/getty_server.go
@@ -117,7 +117,7 @@
}
// NewServer create a new Server
-func NewServer(url common.URL, handlers func(*invocation.RPCInvocation) protocol.RPCResult) *Server {
+func NewServer(url *common.URL, handlers func(*invocation.RPCInvocation) protocol.RPCResult) *Server {
//init
initServer(url.Protocol)
diff --git a/remoting/getty/listener.go b/remoting/getty/listener.go
index 196aa20..d4819a1 100644
--- a/remoting/getty/listener.go
+++ b/remoting/getty/listener.go
@@ -153,7 +153,9 @@
return
}
- h.conn.pool.rpcClient.heartbeat(session)
+ if err := h.conn.pool.rpcClient.heartbeat(session); err != nil {
+ logger.Warnf("failed to send heartbeat, error: %v", err)
+ }
}
// //////////////////////////////////////////
@@ -272,7 +274,6 @@
invoc, ok := req.Data.(*invocation.RPCInvocation)
if !ok {
panic("create invocation occur some exception for the type is not suitable one.")
- return
}
attachments := invoc.Attachments()
attachments[constant.LOCAL_ADDR] = session.LocalAddr()
diff --git a/remoting/kubernetes/client.go b/remoting/kubernetes/client.go
index 0a05489..fce9e80 100644
--- a/remoting/kubernetes/client.go
+++ b/remoting/kubernetes/client.go
@@ -47,7 +47,7 @@
}
// newClient returns Client instance for registry
-func newClient(url common.URL) (*Client, error) {
+func newClient(url *common.URL) (*Client, error) {
ctx, cancel := context.WithCancel(context.Background())
diff --git a/remoting/kubernetes/facade_test.go b/remoting/kubernetes/facade_test.go
index 65c5d71..00e2e11 100644
--- a/remoting/kubernetes/facade_test.go
+++ b/remoting/kubernetes/facade_test.go
@@ -43,8 +43,8 @@
r.client = client
}
-func (r *mockFacade) GetUrl() common.URL {
- return *r.URL
+func (r *mockFacade) GetUrl() *common.URL {
+ return r.URL
}
func (r *mockFacade) Destroy() {
@@ -68,7 +68,7 @@
mockClient := getTestClient(t)
m := &mockFacade{
- URL: ®Url,
+ URL: regUrl,
client: mockClient,
}
diff --git a/remoting/zookeeper/facade.go b/remoting/zookeeper/facade.go
index 2a03439..4dc0a54 100644
--- a/remoting/zookeeper/facade.go
+++ b/remoting/zookeeper/facade.go
@@ -37,7 +37,7 @@
WaitGroup() *sync.WaitGroup // for wait group control, zk client listener & zk client container
Done() chan struct{} // for zk client control
RestartCallBack() bool
- GetUrl() common.URL
+ GetUrl() *common.URL
}
// HandleClientRestart keeps the connection between client and server
diff --git a/remoting/zookeeper/facade_test.go b/remoting/zookeeper/facade_test.go
index 1cd8f06..3d5798c 100644
--- a/remoting/zookeeper/facade_test.go
+++ b/remoting/zookeeper/facade_test.go
@@ -68,8 +68,8 @@
return r.done
}
-func (r *mockFacade) GetUrl() common.URL {
- return *r.URL
+func (r *mockFacade) GetUrl() *common.URL {
+ return r.URL
}
func (r *mockFacade) Destroy() {
@@ -90,7 +90,7 @@
assert.NoError(t, err)
defer ts.Stop()
url, _ := common.NewURL("mock://127.0.0.1")
- mock := newMockFacade(z, &url)
+ mock := newMockFacade(z, url)
go HandleClientRestart(mock)
states := []zk.State{zk.StateConnecting, zk.StateConnected, zk.StateHasSession}
verifyEventStateOrder(t, event, states, "event channel")