You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dubbo.apache.org by al...@apache.org on 2021/11/06 05:55:55 UTC
[dubbo-go] branch 3.0 updated: style(common): rename constants in
camel-case style (#1563)
This is an automated email from the ASF dual-hosted git repository.
alexstocks pushed a commit to branch 3.0
in repository https://gitbox.apache.org/repos/asf/dubbo-go.git
The following commit(s) were added to refs/heads/3.0 by this push:
new 27aaaa9 style(common): rename constants in camel-case style (#1563)
27aaaa9 is described below
commit 27aaaa9faa33d0b232604d108675cd5e2beec7b1
Author: Xuewei Niu <a...@nxw.name>
AuthorDate: Sat Nov 6 13:55:51 2021 +0800
style(common): rename constants in camel-case style (#1563)
* style(common): rename constants in camel-case style
* style(common): rename Ttl to TTL
---
cluster/cluster/available/cluster_invoker_test.go | 2 +-
cluster/cluster/base/cluster_invoker.go | 8 +-
cluster/cluster/broadcast/cluster_invoker_test.go | 2 +-
cluster/cluster/failback/cluster_invoker.go | 12 +-
cluster/cluster/failback/cluster_test.go | 2 +-
cluster/cluster/failfast/cluster_test.go | 2 +-
cluster/cluster/failover/cluster_invoker.go | 8 +-
cluster/cluster/failover/cluster_test.go | 6 +-
cluster/cluster/failsafe/cluster_invoker.go | 4 +-
cluster/cluster/failsafe/cluster_test.go | 2 +-
cluster/cluster/forking/cluster_invoker.go | 4 +-
cluster/cluster/forking/cluster_test.go | 10 +-
cluster/cluster/zoneaware/cluster_interceptor.go | 2 +-
cluster/cluster/zoneaware/cluster_invoker.go | 6 +-
cluster/cluster/zoneaware/cluster_invoker_test.go | 30 +-
cluster/directory/base/directory.go | 6 +-
cluster/directory/base/directory_test.go | 34 +--
.../loadbalance/consistenthashing/loadbalance.go | 2 +-
.../loadbalance/leastactive/loadbalance_test.go | 2 +-
cluster/loadbalance/random/loadbalance_test.go | 4 +-
cluster/loadbalance/roundrobin/loadbalance_test.go | 2 +-
cluster/loadbalance/util.go | 10 +-
common/constant/default.go | 97 +++---
common/constant/env.go | 8 +-
common/constant/key.go | 338 ++++++++++-----------
common/constant/serialization.go | 10 +-
common/extension/metadata_service.go | 2 +-
common/extension/metadata_service_exporter.go | 2 +-
common/extension/metadata_service_proxy_factory.go | 2 +-
common/metadata_info.go | 32 +-
common/proxy/proxy_factory/default.go | 2 +-
common/proxy/proxy_factory/pass_through.go | 4 +-
common/proxy/proxy_test.go | 4 +-
common/url.go | 54 ++--
common/url_test.go | 46 +--
config/config_center_config.go | 14 +-
config/config_loader.go | 8 +-
config/config_loader_options.go | 2 +-
config/config_utils.go | 6 +-
config/graceful_shutdown.go | 2 +-
config/metadata_report_config.go | 10 +-
config/method_config.go | 4 +-
config/reference_config.go | 78 ++---
config/registry_config.go | 34 +--
config/remote_config.go | 6 +-
config/root_config.go | 8 +-
config/service_config.go | 90 +++---
config_center/apollo/impl.go | 12 +-
config_center/configurator/mock.go | 6 +-
config_center/configurator/override.go | 46 +--
config_center/configurator/override_test.go | 8 +-
config_center/file/factory.go | 2 +-
config_center/nacos/impl.go | 2 +-
config_center/parser/configuration_parser.go | 18 +-
config_center/zookeeper/impl.go | 2 +-
filter/accesslog/filter.go | 48 +--
filter/accesslog/filter_test.go | 4 +-
filter/auth/accesskey_storage.go | 6 +-
filter/auth/accesskey_storage_test.go | 4 +-
filter/auth/consumer_sign_filter_test.go | 6 +-
filter/auth/default_authenticator.go | 30 +-
filter/auth/default_authenticator_test.go | 54 ++--
filter/auth/provider_auth_filter_test.go | 14 +-
filter/echo/filter.go | 2 +-
filter/execlmt/filter.go | 8 +-
filter/execlmt/filter_test.go | 10 +-
filter/generic/filter.go | 8 +-
filter/generic/filter_test.go | 14 +-
filter/generic/service_filter.go | 4 +-
filter/generic/service_filter_test.go | 30 +-
filter/generic/util.go | 10 +-
filter/gshutdown/filter.go | 2 +-
filter/gshutdown/filter_test.go | 2 +-
.../handler/rejected_execution_handler_only_log.go | 2 +-
.../rejected_execution_handler_only_log_test.go | 2 +-
filter/hystrix/filter_test.go | 8 +-
filter/sentinel/filter.go | 4 +-
filter/token/filter.go | 4 +-
filter/token/filter_test.go | 12 +-
filter/tps/filter.go | 4 +-
filter/tps/filter_test.go | 12 +-
filter/tps/limiter/method_service.go | 18 +-
filter/tps/limiter/method_service_test.go | 36 +--
filter/tps/strategy/fix_window.go | 2 +-
filter/tracing/filter.go | 2 +-
filter/tracing/filter_test.go | 2 +-
metadata/definition/definition.go | 4 +-
metadata/identifier/base_metadata_identifier.go | 22 +-
metadata/identifier/service_metadata_identifier.go | 10 +-
.../identifier/subscribe_metadata_identifier.go | 2 +-
metadata/mapping/metadata/service_name_mapping.go | 6 +-
metadata/report/delegate/delegate_report.go | 8 +-
metadata/report/delegate/delegate_report_test.go | 4 +-
metadata/report/etcd/report.go | 20 +-
metadata/report/etcd/report_test.go | 8 +-
metadata/report/nacos/report.go | 4 +-
metadata/report/nacos/report_test.go | 4 +-
metadata/report/zookeeper/report.go | 18 +-
metadata/service/exporter/configurable/exporter.go | 16 +-
.../local/metadata_service_proxy_factory.go | 16 +-
.../local/metadata_service_proxy_factory_test.go | 2 +-
metadata/service/local/service.go | 18 +-
metadata/service/local/service_proxy.go | 6 +-
metadata/service/local/service_proxy_test.go | 8 +-
metadata/service/local_service.go | 4 +-
metadata/service/remote/service.go | 20 +-
metrics/prometheus/reporter.go | 16 +-
protocol/dubbo/dubbo_codec.go | 24 +-
protocol/dubbo/dubbo_exporter.go | 2 +-
protocol/dubbo/dubbo_invoker.go | 22 +-
protocol/dubbo/dubbo_protocol.go | 2 +-
protocol/dubbo/impl/codec.go | 2 +-
protocol/dubbo/impl/codec_test.go | 6 +-
protocol/dubbo/impl/hessian.go | 14 +-
protocol/dubbo/impl/serialization.go | 4 +-
protocol/dubbo/impl/serialize.go | 2 +-
protocol/dubbo3/dubbo3_exporter.go | 4 +-
protocol/dubbo3/dubbo3_invoker.go | 18 +-
protocol/dubbo3/dubbo3_protocol.go | 8 +-
protocol/grpc/client.go | 4 +-
protocol/grpc/grpc_exporter.go | 2 +-
protocol/grpc/grpc_protocol.go | 2 +-
protocol/invocation/rpcinvocation.go | 4 +-
protocol/invocation/rpcinvocation_test.go | 16 +-
protocol/jsonrpc/http.go | 6 +-
protocol/jsonrpc/jsonrpc_exporter.go | 2 +-
protocol/jsonrpc/jsonrpc_invoker.go | 2 +-
protocol/jsonrpc/server.go | 6 +-
.../protocolwrapper/protocol_filter_wrapper.go | 4 +-
.../protocol_filter_wrapper_test.go | 6 +-
protocol/rest/client/client_impl/resty_client.go | 2 +-
protocol/rest/config/reader/rest_config_reader.go | 4 +-
protocol/rest/rest_exporter.go | 2 +-
protocol/rest/rest_protocol.go | 6 +-
.../rest/server/server_impl/go_restful_server.go | 2 +-
protocol/rpc_status.go | 2 +-
registry/base_configuration_listener.go | 6 +-
registry/base_registry.go | 12 +-
registry/directory/directory.go | 16 +-
registry/directory/directory_test.go | 40 +--
registry/etcdv3/registry.go | 4 +-
registry/etcdv3/registry_test.go | 14 +-
registry/etcdv3/service_discovery.go | 6 +-
registry/event/base_configuration_listener.go | 6 +-
.../metadata_service_url_params_customizer.go | 18 +-
.../event/protocol_ports_metadata_customizer.go | 2 +-
.../service_instances_changed_listener_impl.go | 12 +-
registry/event/service_revision_customizer.go | 10 +-
registry/file/service_discovery.go | 8 +-
registry/kubernetes/registry.go | 2 +-
registry/kubernetes/registry_test.go | 12 +-
registry/nacos/listener.go | 8 +-
registry/nacos/registry.go | 30 +-
registry/nacos/registry_test.go | 66 ++--
registry/nacos/service_discovery.go | 6 +-
registry/protocol/protocol.go | 68 ++---
registry/protocol/protocol_test.go | 26 +-
registry/service_instance.go | 2 +-
.../servicediscovery/service_discovery_registry.go | 18 +-
.../rest/rest_subscribed_urls_synthesizer.go | 8 +-
.../rest/rest_subscribed_urls_synthesizer_test.go | 12 +-
registry/zookeeper/registry.go | 8 +-
registry/zookeeper/service_discovery.go | 8 +-
remoting/getty/dubbo_codec_for_test.go | 24 +-
remoting/getty/getty_client.go | 2 +-
remoting/getty/getty_client_test.go | 24 +-
remoting/getty/getty_server.go | 2 +-
remoting/getty/listener.go | 4 +-
remoting/getty/listener_test.go | 10 +-
remoting/getty/readwriter_test.go | 6 +-
remoting/kubernetes/client.go | 2 +-
remoting/kubernetes/facade_test.go | 2 +-
remoting/nacos/builder.go | 32 +-
remoting/nacos/builder_test.go | 22 +-
remoting/zookeeper/client.go | 2 +-
.../curator_discovery/service_discovery.go | 4 +-
remoting/zookeeper/listener.go | 8 +-
177 files changed, 1224 insertions(+), 1227 deletions(-)
diff --git a/cluster/cluster/available/cluster_invoker_test.go b/cluster/cluster/available/cluster_invoker_test.go
index 22d6981..ca60a8d 100644
--- a/cluster/cluster/available/cluster_invoker_test.go
+++ b/cluster/cluster/available/cluster_invoker_test.go
@@ -43,7 +43,7 @@ import (
)
var availableUrl, _ = common.NewURL(fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider",
- constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ constant.LocalHostValue, constant.DefaultPort))
func registerAvailable(invoker *mock.MockInvoker) protocol.Invoker {
extension.SetLoadbalance("random", random.NewLoadBalance)
diff --git a/cluster/cluster/base/cluster_invoker.go b/cluster/cluster/base/cluster_invoker.go
index e4265e5..cb7de4f 100644
--- a/cluster/cluster/base/cluster_invoker.go
+++ b/cluster/cluster/base/cluster_invoker.go
@@ -94,9 +94,9 @@ func (invoker *ClusterInvoker) DoSelect(lb loadbalance.LoadBalance, invocation p
}
url := invokers[0].GetURL()
- sticky := url.GetParamBool(constant.STICKY_KEY, false)
+ sticky := url.GetParamBool(constant.StickyKey, false)
// Get the service method sticky config if have
- sticky = url.GetMethodParamBool(invocation.MethodName(), constant.STICKY_KEY, sticky)
+ sticky = url.GetMethodParamBool(invocation.MethodName(), constant.StickyKey, sticky)
if invoker.StickyInvoker != nil && !isInvoked(invoker.StickyInvoker, invokers) {
invoker.StickyInvoker = nil
@@ -174,10 +174,10 @@ func GetLoadBalance(invoker protocol.Invoker, invocation protocol.Invocation) lo
methodName := invocation.MethodName()
// Get the service loadbalance config
- lb := url.GetParam(constant.LOADBALANCE_KEY, constant.DEFAULT_LOADBALANCE)
+ lb := url.GetParam(constant.LoadbalanceKey, constant.DefaultLoadbalance)
// Get the service method loadbalance config if have
- if v := url.GetMethodParam(methodName, constant.LOADBALANCE_KEY, ""); len(v) > 0 {
+ if v := url.GetMethodParam(methodName, constant.LoadbalanceKey, ""); len(v) > 0 {
lb = v
}
return extension.GetLoadbalance(lb)
diff --git a/cluster/cluster/broadcast/cluster_invoker_test.go b/cluster/cluster/broadcast/cluster_invoker_test.go
index 356151d..0339c9f 100644
--- a/cluster/cluster/broadcast/cluster_invoker_test.go
+++ b/cluster/cluster/broadcast/cluster_invoker_test.go
@@ -43,7 +43,7 @@ import (
)
var broadcastUrl, _ = common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LocalHostValue, constant.DefaultPort))
func registerBroadcast(mockInvokers ...*mock.MockInvoker) protocol.Invoker {
extension.SetLoadbalance("random", random.NewLoadBalance)
diff --git a/cluster/cluster/failback/cluster_invoker.go b/cluster/cluster/failback/cluster_invoker.go
index 4e677fa..6d55ae4 100644
--- a/cluster/cluster/failback/cluster_invoker.go
+++ b/cluster/cluster/failback/cluster_invoker.go
@@ -58,16 +58,16 @@ func newClusterInvoker(directory directory.Directory) protocol.Invoker {
invoker := &clusterInvoker{
ClusterInvoker: base.NewClusterInvoker(directory),
}
- retriesConfig := invoker.GetURL().GetParam(constant.RETRIES_KEY, constant.DEFAULT_FAILBACK_TIMES)
+ retriesConfig := invoker.GetURL().GetParam(constant.RetriesKey, constant.DefaultFailbackTimes)
retries, err := strconv.Atoi(retriesConfig)
if err != nil || retries < 0 {
logger.Error("Your retries config is invalid,pls do a check. And will use the default fail back times configuration instead.")
- retries = constant.DEFAULT_FAILBACK_TIMES_INT
+ retries = constant.DefaultFailbackTimesInt
}
- failbackTasksConfig := invoker.GetURL().GetParamInt(constant.FAIL_BACK_TASKS_KEY, constant.DEFAULT_FAILBACK_TASKS)
+ failbackTasksConfig := invoker.GetURL().GetParamInt(constant.FailBackTasksKey, constant.DefaultFailbackTasks)
if failbackTasksConfig <= 0 {
- failbackTasksConfig = constant.DEFAULT_FAILBACK_TASKS
+ failbackTasksConfig = constant.DefaultFailbackTasks
}
invoker.maxRetries = int64(retries)
invoker.failbackTasks = failbackTasksConfig
@@ -141,10 +141,10 @@ func (invoker *clusterInvoker) Invoke(ctx context.Context, invocation protocol.I
// Get the service loadbalance config
url := invokers[0].GetURL()
- lb := url.GetParam(constant.LOADBALANCE_KEY, constant.DEFAULT_LOADBALANCE)
+ lb := url.GetParam(constant.LoadbalanceKey, constant.DefaultLoadbalance)
// Get the service method loadbalance config if have
methodName := invocation.MethodName()
- if v := url.GetMethodParam(methodName, constant.LOADBALANCE_KEY, ""); v != "" {
+ if v := url.GetMethodParam(methodName, constant.LoadbalanceKey, ""); v != "" {
lb = v
}
diff --git a/cluster/cluster/failback/cluster_test.go b/cluster/cluster/failback/cluster_test.go
index b43d196..45d02d7 100644
--- a/cluster/cluster/failback/cluster_test.go
+++ b/cluster/cluster/failback/cluster_test.go
@@ -46,7 +46,7 @@ import (
)
var failbackUrl, _ = common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LocalHostValue, constant.DefaultPort))
// registerFailback register failbackCluster to cluster extension.
func registerFailback(invoker *mock.MockInvoker) protocol.Invoker {
diff --git a/cluster/cluster/failfast/cluster_test.go b/cluster/cluster/failfast/cluster_test.go
index a739dac..b19ca47 100644
--- a/cluster/cluster/failfast/cluster_test.go
+++ b/cluster/cluster/failfast/cluster_test.go
@@ -44,7 +44,7 @@ import (
)
var failfastUrl, _ = common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LocalHostValue, constant.DefaultPort))
// registerFailfast register failfastCluster to cluster extension.
func registerFailfast(invoker *mock.MockInvoker) protocol.Invoker {
diff --git a/cluster/cluster/failover/cluster_invoker.go b/cluster/cluster/failover/cluster_invoker.go
index 6440627..b3a2821 100644
--- a/cluster/cluster/failover/cluster_invoker.go
+++ b/cluster/cluster/failover/cluster_invoker.go
@@ -111,21 +111,21 @@ func (invoker *clusterInvoker) Invoke(ctx context.Context, invocation protocol.I
func getRetries(invokers []protocol.Invoker, methodName string) int {
if len(invokers) <= 0 {
- return constant.DEFAULT_RETRIES_INT
+ return constant.DefaultRetriesInt
}
url := invokers[0].GetURL()
// get reties
- retriesConfig := url.GetParam(constant.RETRIES_KEY, constant.DEFAULT_RETRIES)
+ retriesConfig := url.GetParam(constant.RetriesKey, constant.DefaultRetries)
// Get the service method loadbalance config if have
- if v := url.GetMethodParam(methodName, constant.RETRIES_KEY, ""); len(v) != 0 {
+ if v := url.GetMethodParam(methodName, constant.RetriesKey, ""); len(v) != 0 {
retriesConfig = v
}
retries, err := strconv.Atoi(retriesConfig)
if err != nil || retries < 0 {
logger.Error("Your retries config is invalid,pls do a check. And will use the default retries configuration instead.")
- retries = constant.DEFAULT_RETRIES_INT
+ retries = constant.DefaultRetriesInt
}
if retries > len(invokers) {
diff --git a/cluster/cluster/failover/cluster_test.go b/cluster/cluster/failover/cluster_test.go
index ad0aae3..53ef324 100644
--- a/cluster/cluster/failover/cluster_test.go
+++ b/cluster/cluster/failover/cluster_test.go
@@ -77,7 +77,7 @@ func TestFailoverInvokeFail(t *testing.T) {
// nolint
func TestFailoverInvoke1(t *testing.T) {
urlParams := url.Values{}
- urlParams.Set(constant.RETRIES_KEY, "3")
+ urlParams.Set(constant.RetriesKey, "3")
result := normalInvoke(4, urlParams)
assert.NoError(t, result.Error())
clusterpkg.Count = 0
@@ -86,8 +86,8 @@ func TestFailoverInvoke1(t *testing.T) {
// nolint
func TestFailoverInvoke2(t *testing.T) {
urlParams := url.Values{}
- urlParams.Set(constant.RETRIES_KEY, "2")
- urlParams.Set("methods.test."+constant.RETRIES_KEY, "3")
+ urlParams.Set(constant.RetriesKey, "2")
+ urlParams.Set("methods.test."+constant.RetriesKey, "3")
ivc := invocation.NewRPCInvocationWithOptions(invocation.WithMethodName("test"))
result := normalInvoke(4, urlParams, ivc)
diff --git a/cluster/cluster/failsafe/cluster_invoker.go b/cluster/cluster/failsafe/cluster_invoker.go
index b9ba62f..c129e43 100644
--- a/cluster/cluster/failsafe/cluster_invoker.go
+++ b/cluster/cluster/failsafe/cluster_invoker.go
@@ -58,9 +58,9 @@ func (invoker *clusterInvoker) Invoke(ctx context.Context, invocation protocol.I
url := invokers[0].GetURL()
methodName := invocation.MethodName()
// Get the service loadbalance config
- lb := url.GetParam(constant.LOADBALANCE_KEY, constant.DEFAULT_LOADBALANCE)
+ lb := url.GetParam(constant.LoadbalanceKey, constant.DefaultLoadbalance)
// Get the service method loadbalance config if have
- if v := url.GetMethodParam(methodName, constant.LOADBALANCE_KEY, ""); v != "" {
+ if v := url.GetMethodParam(methodName, constant.LoadbalanceKey, ""); v != "" {
lb = v
}
loadbalance := extension.GetLoadbalance(lb)
diff --git a/cluster/cluster/failsafe/cluster_test.go b/cluster/cluster/failsafe/cluster_test.go
index 275995a..7ad4f9f 100644
--- a/cluster/cluster/failsafe/cluster_test.go
+++ b/cluster/cluster/failsafe/cluster_test.go
@@ -44,7 +44,7 @@ import (
)
var failsafeUrl, _ = common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LocalHostValue, constant.DefaultPort))
// registerFailsafe register failsafeCluster to cluster extension.
func registerFailsafe(invoker *mock.MockInvoker) protocol.Invoker {
diff --git a/cluster/cluster/forking/cluster_invoker.go b/cluster/cluster/forking/cluster_invoker.go
index 0b76ffb..0c06db2 100644
--- a/cluster/cluster/forking/cluster_invoker.go
+++ b/cluster/cluster/forking/cluster_invoker.go
@@ -56,8 +56,8 @@ func (invoker *clusterInvoker) Invoke(ctx context.Context, invocation protocol.I
}
var selected []protocol.Invoker
- forks := invoker.GetURL().GetParamByIntValue(constant.FORKS_KEY, constant.DEFAULT_FORKS)
- timeouts := invoker.GetURL().GetParamInt(constant.TIMEOUT_KEY, constant.DEFAULT_TIMEOUT)
+ forks := invoker.GetURL().GetParamByIntValue(constant.ForksKey, constant.DefaultForks)
+ timeouts := invoker.GetURL().GetParamInt(constant.TimeoutKey, constant.DefaultTimeout)
if forks < 0 || forks > len(invokers) {
selected = invokers
} else {
diff --git a/cluster/cluster/forking/cluster_test.go b/cluster/cluster/forking/cluster_test.go
index c92bade..f85c287 100644
--- a/cluster/cluster/forking/cluster_test.go
+++ b/cluster/cluster/forking/cluster_test.go
@@ -45,7 +45,7 @@ import (
)
var forkingUrl, _ = common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LocalHostValue, constant.DefaultPort))
func registerForking(mockInvokers ...*mock.MockInvoker) protocol.Invoker {
extension.SetLoadbalance(constant.LoadBalanceKeyRoundRobin, roundrobin.NewLoadBalance)
@@ -71,8 +71,8 @@ func TestForkingInvokeSuccess(t *testing.T) {
invokers := make([]*mock.MockInvoker, 0)
mockResult := &protocol.RPCResult{Rest: clusterpkg.Rest{Tried: 0, Success: true}}
- forkingUrl.AddParam(constant.FORKS_KEY, strconv.Itoa(3))
- // forkingUrl.AddParam(constant.TIMEOUT_KEY, strconv.Itoa(constant.DEFAULT_TIMEOUT))
+ forkingUrl.AddParam(constant.ForksKey, strconv.Itoa(3))
+ // forkingUrl.AddParam(constant.TimeoutKey, strconv.Itoa(constant.DefaultTimeout))
var wg sync.WaitGroup
wg.Add(2)
@@ -101,7 +101,7 @@ func TestForkingInvokeTimeout(t *testing.T) {
invokers := make([]*mock.MockInvoker, 0)
mockResult := &protocol.RPCResult{Rest: clusterpkg.Rest{Tried: 0, Success: true}}
- forkingUrl.AddParam(constant.FORKS_KEY, strconv.Itoa(3))
+ forkingUrl.AddParam(constant.ForksKey, strconv.Itoa(3))
var wg sync.WaitGroup
wg.Add(2)
@@ -132,7 +132,7 @@ func TestForkingInvokeHalfTimeout(t *testing.T) {
invokers := make([]*mock.MockInvoker, 0)
mockResult := &protocol.RPCResult{Rest: clusterpkg.Rest{Tried: 0, Success: true}}
- forkingUrl.AddParam(constant.FORKS_KEY, strconv.Itoa(3))
+ forkingUrl.AddParam(constant.ForksKey, strconv.Itoa(3))
var wg sync.WaitGroup
wg.Add(2)
diff --git a/cluster/cluster/zoneaware/cluster_interceptor.go b/cluster/cluster/zoneaware/cluster_interceptor.go
index eabe4e5..d71f2ec 100644
--- a/cluster/cluster/zoneaware/cluster_interceptor.go
+++ b/cluster/cluster/zoneaware/cluster_interceptor.go
@@ -31,7 +31,7 @@ type interceptor struct {
}
func (z *interceptor) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
- key := constant.REGISTRY_KEY + "." + constant.ZONE_FORCE_KEY
+ key := constant.RegistryKey + "." + constant.ZoneForceKey
force := ctx.Value(key)
if force != nil {
diff --git a/cluster/cluster/zoneaware/cluster_invoker.go b/cluster/cluster/zoneaware/cluster_invoker.go
index d6a72d1..420aaa7 100644
--- a/cluster/cluster/zoneaware/cluster_invoker.go
+++ b/cluster/cluster/zoneaware/cluster_invoker.go
@@ -57,14 +57,14 @@ func (invoker *clusterInvoker) Invoke(ctx context.Context, invocation protocol.I
// First, pick the invoker (XXXClusterInvoker) that comes from the local registry, distinguish by a 'preferred' key.
for _, invoker := range invokers {
- key := constant.REGISTRY_KEY + "." + constant.PREFERRED_KEY
+ key := constant.RegistryKey + "." + constant.PreferredKey
if invoker.IsAvailable() && matchParam("true", key, "false", invoker) {
return invoker.Invoke(ctx, invocation)
}
}
// providers in the registry with the same zone
- key := constant.REGISTRY_KEY + "." + constant.ZONE_KEY
+ key := constant.RegistryKey + "." + constant.ZoneKey
zone := invocation.AttachmentsByKey(key, "")
if "" != zone {
for _, invoker := range invokers {
@@ -73,7 +73,7 @@ func (invoker *clusterInvoker) Invoke(ctx context.Context, invocation protocol.I
}
}
- force := invocation.AttachmentsByKey(constant.REGISTRY_KEY+"."+constant.ZONE_FORCE_KEY, "")
+ force := invocation.AttachmentsByKey(constant.RegistryKey+"."+constant.ZoneForceKey, "")
if "true" == force {
return &protocol.RPCResult{
Err: fmt.Errorf("no registry instance in zone or "+
diff --git a/cluster/cluster/zoneaware/cluster_invoker_test.go b/cluster/cluster/zoneaware/cluster_invoker_test.go
index 084035b..edc9af0 100644
--- a/cluster/cluster/zoneaware/cluster_invoker_test.go
+++ b/cluster/cluster/zoneaware/cluster_invoker_test.go
@@ -48,7 +48,7 @@ func TestZoneWareInvokerWithPreferredSuccess(t *testing.T) {
// defer ctrl.Finish()
mockResult := &protocol.RPCResult{
- Attrs: map[string]interface{}{constant.PREFERRED_KEY: "true"},
+ Attrs: map[string]interface{}{constant.PreferredKey: "true"},
Rest: clusterpkg.Rest{Tried: 0, Success: true},
}
@@ -59,7 +59,7 @@ func TestZoneWareInvokerWithPreferredSuccess(t *testing.T) {
invoker.EXPECT().IsAvailable().Return(true).AnyTimes()
invoker.EXPECT().GetUrl().Return(url).AnyTimes()
if 0 == i {
- url.SetParam(constant.REGISTRY_KEY+"."+constant.PREFERRED_KEY, "true")
+ url.SetParam(constant.RegistryKey+"."+constant.PreferredKey, "true")
invoker.EXPECT().Invoke(gomock.Any()).DoAndReturn(
func(invocation protocol.Invocation) protocol.Result {
return mockResult
@@ -100,22 +100,22 @@ func TestZoneWareInvokerWithWeightSuccess(t *testing.T) {
invoker := mock.NewMockInvoker(ctrl)
invoker.EXPECT().IsAvailable().Return(true).AnyTimes()
invoker.EXPECT().GetUrl().Return(url).AnyTimes()
- url.SetParam(constant.REGISTRY_KEY+"."+constant.REGISTRY_LABEL_KEY, "true")
+ url.SetParam(constant.RegistryKey+"."+constant.RegistryLabelKey, "true")
if 1 == i {
- url.SetParam(constant.REGISTRY_KEY+"."+constant.WEIGHT_KEY, w1)
+ url.SetParam(constant.RegistryKey+"."+constant.WeightKey, w1)
invoker.EXPECT().Invoke(gomock.Any()).DoAndReturn(
func(invocation protocol.Invocation) protocol.Result {
return &protocol.RPCResult{
- Attrs: map[string]interface{}{constant.WEIGHT_KEY: w1},
+ Attrs: map[string]interface{}{constant.WeightKey: w1},
Rest: clusterpkg.Rest{Tried: 0, Success: true},
}
}).MaxTimes(100)
} else {
- url.SetParam(constant.REGISTRY_KEY+"."+constant.WEIGHT_KEY, w2)
+ url.SetParam(constant.RegistryKey+"."+constant.WeightKey, w2)
invoker.EXPECT().Invoke(gomock.Any()).DoAndReturn(
func(invocation protocol.Invocation) protocol.Result {
return &protocol.RPCResult{
- Attrs: map[string]interface{}{constant.WEIGHT_KEY: w2},
+ Attrs: map[string]interface{}{constant.WeightKey: w2},
Rest: clusterpkg.Rest{Tried: 0, Success: true},
}
}).MaxTimes(100)
@@ -131,10 +131,10 @@ func TestZoneWareInvokerWithWeightSuccess(t *testing.T) {
loop := 50
for i := 0; i < loop; i++ {
result := clusterInvoker.Invoke(context.Background(), &invocation.RPCInvocation{})
- if w2 == result.Attachment(constant.WEIGHT_KEY, "0") {
+ if w2 == result.Attachment(constant.WeightKey, "0") {
w2Count++
}
- if w1 == result.Attachment(constant.WEIGHT_KEY, "0") {
+ if w1 == result.Attachment(constant.WeightKey, "0") {
w1Count++
}
assert.NoError(t, result.Error())
@@ -155,7 +155,7 @@ func TestZoneWareInvokerWithZoneSuccess(t *testing.T) {
for i := 0; i < 2; i++ {
zoneValue := zoneArray[i]
url, _ := common.NewURL(fmt.Sprintf("dubbo://192.168.1.%v:20000/com.ikurento.user.UserProvider", i))
- url.SetParam(constant.REGISTRY_KEY+"."+constant.ZONE_KEY, zoneValue)
+ url.SetParam(constant.RegistryKey+"."+constant.ZoneKey, zoneValue)
invoker := mock.NewMockInvoker(ctrl)
invoker.EXPECT().IsAvailable().Return(true).AnyTimes()
@@ -163,7 +163,7 @@ func TestZoneWareInvokerWithZoneSuccess(t *testing.T) {
invoker.EXPECT().Invoke(gomock.Any()).DoAndReturn(
func(invocation protocol.Invocation) protocol.Result {
return &protocol.RPCResult{
- Attrs: map[string]interface{}{constant.ZONE_KEY: zoneValue},
+ Attrs: map[string]interface{}{constant.ZoneKey: zoneValue},
Rest: clusterpkg.Rest{Tried: 0, Success: true},
}
})
@@ -177,11 +177,11 @@ func TestZoneWareInvokerWithZoneSuccess(t *testing.T) {
inv := &invocation.RPCInvocation{}
// zone hangzhou
hz := zoneArray[0]
- inv.SetAttachments(constant.REGISTRY_KEY+"."+constant.ZONE_KEY, hz)
+ inv.SetAttachments(constant.RegistryKey+"."+constant.ZoneKey, hz)
result := clusterInvoker.Invoke(context.Background(), inv)
- assert.Equal(t, hz, result.Attachment(constant.ZONE_KEY, ""))
+ assert.Equal(t, hz, result.Attachment(constant.ZoneKey, ""))
}
func TestZoneWareInvokerWithZoneForceFail(t *testing.T) {
@@ -206,9 +206,9 @@ func TestZoneWareInvokerWithZoneForceFail(t *testing.T) {
inv := &invocation.RPCInvocation{}
// zone hangzhou
- inv.SetAttachments(constant.REGISTRY_KEY+"."+constant.ZONE_KEY, "hangzhou")
+ inv.SetAttachments(constant.RegistryKey+"."+constant.ZoneKey, "hangzhou")
// zone force
- inv.SetAttachments(constant.REGISTRY_KEY+"."+constant.ZONE_FORCE_KEY, "true")
+ inv.SetAttachments(constant.RegistryKey+"."+constant.ZoneForceKey, "true")
result := clusterInvoker.Invoke(context.Background(), inv)
diff --git a/cluster/directory/base/directory.go b/cluster/directory/base/directory.go
index 52445fc..93dfcb6 100644
--- a/cluster/directory/base/directory.go
+++ b/cluster/directory/base/directory.go
@@ -73,10 +73,10 @@ func (dir *Directory) GetDirectoryUrl() *common.URL {
}
func (dir *Directory) isProperRouter(url *common.URL) bool {
- app := url.GetParam(constant.APPLICATION_KEY, "")
- dirApp := dir.GetURL().GetParam(constant.APPLICATION_KEY, "")
+ app := url.GetParam(constant.ApplicationKey, "")
+ dirApp := dir.GetURL().GetParam(constant.ApplicationKey, "")
if len(dirApp) == 0 && dir.GetURL().SubURL != nil {
- dirApp = dir.GetURL().SubURL.GetParam(constant.APPLICATION_KEY, "")
+ dirApp = dir.GetURL().SubURL.GetParam(constant.ApplicationKey, "")
}
serviceKey := dir.GetURL().ServiceKey()
if len(serviceKey) == 0 {
diff --git a/cluster/directory/base/directory_test.go b/cluster/directory/base/directory_test.go
index 3e8c5c9..b4feb44 100644
--- a/cluster/directory/base/directory_test.go
+++ b/cluster/directory/base/directory_test.go
@@ -35,8 +35,8 @@ import (
var (
url, _ = common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
- anyURL, _ = common.NewURL(fmt.Sprintf("condition://%s/com.foo.BarService", constant.ANYHOST_VALUE))
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LocalHostValue, constant.DefaultPort))
+ anyURL, _ = common.NewURL(fmt.Sprintf("condition://%s/com.foo.BarService", constant.AnyhostValue))
)
func TestNewBaseDirectory(t *testing.T) {
@@ -47,7 +47,7 @@ func TestNewBaseDirectory(t *testing.T) {
func TestBuildRouterChain(t *testing.T) {
regURL := url
- regURL.AddParam(constant.INTERFACE_KEY, "mock-app")
+ regURL.AddParam(constant.InterfaceKey, "mock-app")
directory := NewDirectory(regURL)
var err error
directory.routerChain, err = chain.NewRouterChain()
@@ -58,49 +58,49 @@ 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")
+ ru.AddParam(constant.RouterKey, "router")
return ru
}
func TestIsProperRouter(t *testing.T) {
regURL := url
- regURL.AddParam(constant.APPLICATION_KEY, "mock-app")
+ regURL.AddParam(constant.ApplicationKey, "mock-app")
d := NewDirectory(regURL)
localIP := common.GetLocalIp()
rule := base64.URLEncoding.EncodeToString([]byte("true => " + " host = " + localIP))
routeURL := getRouteURL(rule, anyURL)
- routeURL.AddParam(constant.APPLICATION_KEY, "mock-app")
+ routeURL.AddParam(constant.ApplicationKey, "mock-app")
rst := d.isProperRouter(routeURL)
assert.True(t, rst)
- regURL.AddParam(constant.APPLICATION_KEY, "")
- regURL.AddParam(constant.INTERFACE_KEY, "com.foo.BarService")
+ regURL.AddParam(constant.ApplicationKey, "")
+ regURL.AddParam(constant.InterfaceKey, "com.foo.BarService")
d = NewDirectory(regURL)
routeURL = getRouteURL(rule, anyURL)
- routeURL.AddParam(constant.INTERFACE_KEY, "com.foo.BarService")
+ routeURL.AddParam(constant.InterfaceKey, "com.foo.BarService")
rst = d.isProperRouter(routeURL)
assert.True(t, rst)
- regURL.AddParam(constant.APPLICATION_KEY, "")
- regURL.AddParam(constant.INTERFACE_KEY, "")
+ regURL.AddParam(constant.ApplicationKey, "")
+ regURL.AddParam(constant.InterfaceKey, "")
d = NewDirectory(regURL)
routeURL = getRouteURL(rule, anyURL)
rst = d.isProperRouter(routeURL)
assert.True(t, rst)
- regURL.SetParam(constant.APPLICATION_KEY, "")
- regURL.SetParam(constant.INTERFACE_KEY, "")
+ regURL.SetParam(constant.ApplicationKey, "")
+ regURL.SetParam(constant.InterfaceKey, "")
d = NewDirectory(regURL)
routeURL = getRouteURL(rule, anyURL)
- routeURL.AddParam(constant.APPLICATION_KEY, "mock-service")
+ routeURL.AddParam(constant.ApplicationKey, "mock-service")
rst = d.isProperRouter(routeURL)
assert.False(t, rst)
- regURL.SetParam(constant.APPLICATION_KEY, "")
- regURL.SetParam(constant.INTERFACE_KEY, "")
+ regURL.SetParam(constant.ApplicationKey, "")
+ regURL.SetParam(constant.InterfaceKey, "")
d = NewDirectory(regURL)
routeURL = getRouteURL(rule, anyURL)
- routeURL.AddParam(constant.INTERFACE_KEY, "mock-service")
+ routeURL.AddParam(constant.InterfaceKey, "mock-service")
rst = d.isProperRouter(routeURL)
assert.False(t, rst)
}
diff --git a/cluster/loadbalance/consistenthashing/loadbalance.go b/cluster/loadbalance/consistenthashing/loadbalance.go
index 965f55d..ece1d15 100644
--- a/cluster/loadbalance/consistenthashing/loadbalance.go
+++ b/cluster/loadbalance/consistenthashing/loadbalance.go
@@ -39,7 +39,7 @@ const (
var (
selectors = make(map[string]*selector)
- re = regexp.MustCompile(constant.COMMA_SPLIT_PATTERN)
+ re = regexp.MustCompile(constant.CommaSplitPattern)
)
func init() {
diff --git a/cluster/loadbalance/leastactive/loadbalance_test.go b/cluster/loadbalance/leastactive/loadbalance_test.go
index 223692b..ede1c5d 100644
--- a/cluster/loadbalance/leastactive/loadbalance_test.go
+++ b/cluster/loadbalance/leastactive/loadbalance_test.go
@@ -38,7 +38,7 @@ func TestLeastActiveSelect(t *testing.T) {
var invokers []protocol.Invoker
- url, _ := common.NewURL(fmt.Sprintf("dubbo://%s:%d/org.apache.demo.HelloService", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ url, _ := common.NewURL(fmt.Sprintf("dubbo://%s:%d/org.apache.demo.HelloService", constant.LocalHostValue, constant.DefaultPort))
invokers = append(invokers, protocol.NewBaseInvoker(url))
i := loadBalance.Select(invokers, &invocation.RPCInvocation{})
assert.True(t, i.GetURL().URLEqual(url))
diff --git a/cluster/loadbalance/random/loadbalance_test.go b/cluster/loadbalance/random/loadbalance_test.go
index 37ad264..79ecbc1 100644
--- a/cluster/loadbalance/random/loadbalance_test.go
+++ b/cluster/loadbalance/random/loadbalance_test.go
@@ -69,7 +69,7 @@ func TestRandomlbSelectWeight(t *testing.T) {
}
urlParams := url.Values{}
- urlParams.Set("methods.test."+constant.WEIGHT_KEY, "10000000000000")
+ urlParams.Set("methods.test."+constant.WeightKey, "10000000000000")
urll, _ := common.NewURL(tmpUrl, common.WithParams(urlParams))
invokers = append(invokers, protocol.NewBaseInvoker(urll))
ivc := invocation.NewRPCInvocationWithOptions(invocation.WithMethodName("test"))
@@ -101,7 +101,7 @@ func TestRandomlbSelectWarmup(t *testing.T) {
}
urlParams := url.Values{}
- urlParams.Set(constant.REMOTE_TIMESTAMP_KEY, strconv.FormatInt(time.Now().Add(time.Minute*(-9)).Unix(), 10))
+ urlParams.Set(constant.RemoteTimestampKey, strconv.FormatInt(time.Now().Add(time.Minute*(-9)).Unix(), 10))
urll, _ := common.NewURL(tmpUrl, common.WithParams(urlParams))
invokers = append(invokers, protocol.NewBaseInvoker(urll))
ivc := invocation.NewRPCInvocationWithOptions(invocation.WithMethodName("test"))
diff --git a/cluster/loadbalance/roundrobin/loadbalance_test.go b/cluster/loadbalance/roundrobin/loadbalance_test.go
index fea5485..00fd592 100644
--- a/cluster/loadbalance/roundrobin/loadbalance_test.go
+++ b/cluster/loadbalance/roundrobin/loadbalance_test.go
@@ -40,7 +40,7 @@ func TestRoundRobinSelect(t *testing.T) {
var invokers []protocol.Invoker
url, _ := common.NewURL(fmt.Sprintf("dubbo://%s:%d/org.apache.demo.HelloService",
- constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ constant.LocalHostValue, constant.DefaultPort))
invokers = append(invokers, protocol.NewBaseInvoker(url))
i := loadBalance.Select(invokers, &invocation.RPCInvocation{})
assert.True(t, i.GetURL().URLEqual(url))
diff --git a/cluster/loadbalance/util.go b/cluster/loadbalance/util.go
index 3cc49e1..4726c8d 100644
--- a/cluster/loadbalance/util.go
+++ b/cluster/loadbalance/util.go
@@ -31,18 +31,18 @@ func GetWeight(invoker protocol.Invoker, invocation protocol.Invocation) int64 {
var weight int64
url := invoker.GetURL()
// Multiple registry scenario, load balance among multiple registries.
- isRegIvk := url.GetParamBool(constant.REGISTRY_KEY+"."+constant.REGISTRY_LABEL_KEY, false)
+ isRegIvk := url.GetParamBool(constant.RegistryKey+"."+constant.RegistryLabelKey, false)
if isRegIvk {
- weight = url.GetParamInt(constant.REGISTRY_KEY+"."+constant.WEIGHT_KEY, constant.DEFAULT_WEIGHT)
+ weight = url.GetParamInt(constant.RegistryKey+"."+constant.WeightKey, constant.DefaultWeight)
} else {
- weight = url.GetMethodParamInt64(invocation.MethodName(), constant.WEIGHT_KEY, constant.DEFAULT_WEIGHT)
+ weight = url.GetMethodParamInt64(invocation.MethodName(), constant.WeightKey, constant.DefaultWeight)
if weight > 0 {
// get service register time an do warm up time
now := time.Now().Unix()
- timestamp := url.GetParamInt(constant.REMOTE_TIMESTAMP_KEY, now)
+ timestamp := url.GetParamInt(constant.RemoteTimestampKey, now)
if uptime := now - timestamp; uptime > 0 {
- warmup := url.GetParamInt(constant.WARMUP_KEY, constant.DEFAULT_WARMUP)
+ warmup := url.GetParamInt(constant.WarmupKey, constant.DefaultWarmup)
if uptime < warmup {
if ww := float64(uptime) / float64(warmup) / float64(weight); ww < 1 {
weight = 1
diff --git a/common/constant/default.go b/common/constant/default.go
index 91c6742..58784e7 100644
--- a/common/constant/default.go
+++ b/common/constant/default.go
@@ -18,80 +18,79 @@
package constant
const (
- DUBBO = "dubbo"
- PROVIDER_PROTOCOL = "provider"
- // compatible with 2.6.x
- OVERRIDE_PROTOCOL = "override"
- EMPTY_PROTOCOL = "empty"
- ROUTER_PROTOCOL = "router"
+ Dubbo = "dubbo"
+ ProviderProtocol = "provider"
+ // OverrideProtocol is compatible with 2.6.x
+ OverrideProtocol = "override"
+ EmptyProtocol = "empty"
+ RouterProtocol = "router"
)
const (
- DEFAULT_WEIGHT = 100 //
- DEFAULT_WARMUP = 10 * 60 // in java here is 10*60*1000 because of System.currentTimeMillis() is measured in milliseconds & in go time.Unix() is second
+ DefaultWeight = 100 //
+ DefaultWarmup = 10 * 60 // in java here is 10*60*1000 because of System.currentTimeMillis() is measured in milliseconds & in go time.Unix() is second
)
const (
- DEFAULT_LOADBALANCE = "random"
- DEFAULT_RETRIES = "2"
- DEFAULT_RETRIES_INT = 2
- DEFAULT_PROTOCOL = "dubbo"
- DEFAULT_REG_TIMEOUT = "10s"
- DEFAULT_REG_TTL = "15m"
- DEFAULT_CLUSTER = "failover"
- DEFAULT_FAILBACK_TIMES = "3"
- DEFAULT_FAILBACK_TIMES_INT = 3
- DEFAULT_FAILBACK_TASKS = 100
- DEFAULT_REST_CLIENT = "resty"
- DEFAULT_REST_SERVER = "go-restful"
- DEFAULT_PORT = 20000
- DEFAULT_METADATAPORT = 20005
- DEFAULT_SERIALIZATION = HESSIAN2_SERIALIZATION
+ DefaultLoadbalance = "random"
+ DefaultRetries = "2"
+ DefaultRetriesInt = 2
+ DefaultProtocol = "dubbo"
+ DefaultRegTimeout = "10s"
+ DefaultRegTTL = "15m"
+ DefaultCluster = "failover"
+ DefaultFailbackTimes = "3"
+ DefaultFailbackTimesInt = 3
+ DefaultFailbackTasks = 100
+ DefaultRestClient = "resty"
+ DefaultRestServer = "go-restful"
+ DefaultPort = 20000
+ DefaultMetadataport = 20005
)
const (
- DEFAULT_KEY = "default"
- PREFIX_DEFAULT_KEY = "default."
- DEFAULT_SERVICE_FILTERS = EchoFilterKey + "," + MetricsFilterKey + "," + TokenFilterKey + "," + AccessLogFilterKey + "," + TpsLimitFilterKey + "," + GenericServiceFilterKey + "," + ExecuteLimitFilterKey + "," + GracefulShutdownProviderFilterKey
- DEFAULT_REFERENCE_FILTERS = GracefulShutdownConsumerFilterKey
- GENERIC_REFERENCE_FILTERS = GenericFilterKey
- GENERIC = "$invoke"
- ECHO = "$echo"
+ DefaultKey = "default"
+ PrefixDefaultKey = "default."
+ DefaultServiceFilters = EchoFilterKey + "," + MetricsFilterKey + "," + TokenFilterKey + "," + AccessLogFilterKey + "," + TpsLimitFilterKey + "," + GenericServiceFilterKey + "," + ExecuteLimitFilterKey + "," + GracefulShutdownProviderFilterKey
+ DefaultReferenceFilters = GracefulShutdownConsumerFilterKey
+ GenericReferenceFilters = GenericFilterKey
+ Generic = "$invoke"
+ Echo = "$echo"
)
const (
- ANY_VALUE = "*"
- ANYHOST_VALUE = "0.0.0.0"
- LOCAL_HOST_VALUE = "192.168.1.1"
- REMOVE_VALUE_PREFIX = "-"
+ AnyValue = "*"
+ AnyhostValue = "0.0.0.0"
+ LocalHostValue = "192.168.1.1"
+ RemoveValuePrefix = "-"
)
const (
- CONFIGURATORS_CATEGORY = "configurators"
- ROUTER_CATEGORY = "category"
- DEFAULT_CATEGORY = PROVIDER_CATEGORY
- DYNAMIC_CONFIGURATORS_CATEGORY = "dynamicconfigurators"
- APP_DYNAMIC_CONFIGURATORS_CATEGORY = "appdynamicconfigurators"
- PROVIDER_CATEGORY = "providers"
- CONSUMER_CATEGORY = "consumers"
+ ConfiguratorsCategory = "configurators"
+ RouterCategory = "category"
+ DefaultCategory = ProviderCategory
+ DynamicConfiguratorsCategory = "dynamicconfigurators"
+ AppDynamicConfiguratorsCategory = "appdynamicconfigurators"
+ ProviderCategory = "providers"
+ ConsumerCategory = "consumers"
)
const (
- COMMA_SPLIT_PATTERN = "\\s*[,]+\\s*"
+ CommaSplitPattern = "\\s*[,]+\\s*"
)
const (
- SIMPLE_METADATA_SERVICE_NAME = "MetadataService"
- DEFAULT_REVISION = "N/A"
+ SimpleMetadataServiceName = "MetadataService"
+ DefaultRevision = "N/A"
)
const (
- SERVICE_DISCOVERY_DEFAULT_GROUP = "DEFAULT_GROUP"
+ ServiceDiscoveryDefaultGroup = "DEFAULT_GROUP"
)
const (
- DEFAULT_PROVIDER_CONF_FILE_PATH = "../profiles/dev/server.yml"
- DEFAULT_CONSUMER_CONF_FILE_PATH = "../profiles/dev/client.yml"
- DEFAULT_LOG_CONF_FILE_PATH = "../profiles/dev/log.yml"
- DEFAULT_ROUTER_CONF_FILE_PATH = "../profiles/dev/router.yml"
+ DefaultProviderConfFilePath = "../profiles/dev/server.yml"
+ DefaultConsumerConfFilePath = "../profiles/dev/client.yml"
+ DefaultLogConfFilePath = "../profiles/dev/log.yml"
+ DefaultRouterConfFilePath = "../profiles/dev/router.yml"
)
diff --git a/common/constant/env.go b/common/constant/env.go
index c2fb18b..9e20a6d 100644
--- a/common/constant/env.go
+++ b/common/constant/env.go
@@ -19,8 +19,8 @@ package constant
// nolint
const (
- // CONFIG_FILE_ENV_KEY is key of environment variable dubbogo configure file path
- CONFIG_FILE_ENV_KEY = "DUBBO_GO_CONFIG_PATH"
- // APP_LOG_CONF_FILE ...
- APP_LOG_CONF_FILE = "APP_LOG_CONF_FILE"
+ // ConfigFileEnvKey is key of environment variable dubbogo configure file path
+ ConfigFileEnvKey = "DUBBO_GO_CONFIG_PATH"
+ // AppLogConfFile ...
+ AppLogConfFile = "AppLogConfFile"
)
diff --git a/common/constant/key.go b/common/constant/key.go
index d44542d..8d3c2e8 100644
--- a/common/constant/key.go
+++ b/common/constant/key.go
@@ -20,47 +20,45 @@ package constant
type DubboCtxKey string
const (
- ASYNC_KEY = "async" // it's value should be "true" or "false" of string type
+ AsyncKey = "async" // it's value should be "true" or "false" of string type
)
const (
- GROUP_KEY = "group"
- VERSION_KEY = "version"
- INTERFACE_KEY = "interface"
- MESSAGE_SIZE_KEY = "message_size"
- PATH_KEY = "path"
- SERVICE_KEY = "service"
- METHODS_KEY = "methods"
- TIMEOUT_KEY = "timeout"
- CATEGORY_KEY = "category"
- CHECK_KEY = "check"
- ENABLED_KEY = "enabled"
- SIDE_KEY = "side"
- OVERRIDE_PROVIDERS_KEY = "providerAddresses"
- BEAN_NAME_KEY = "bean.name"
- GENERIC_KEY = "generic"
- CLASSIFIER_KEY = "classifier"
- TOKEN_KEY = "token"
- LOCAL_ADDR = "local-addr"
- REMOTE_ADDR = "remote-addr"
- DEFAULT_REMOTING_TIMEOUT = 3000
- RELEASE_KEY = "release"
- ANYHOST_KEY = "anyhost"
- PORT_KEY = "port"
- PROTOCOL_KEY = "protocol"
- PATH_SEPARATOR = "/"
- COMMA_SEPARATOR = ","
- // DUBBO_KEY = "dubbo"
- SSL_ENABLED_KEY = "ssl-enabled"
- // PARAMS_TYPE_Key key used in pass through invoker factory, to define param type
- PARAMS_TYPE_Key = "parameter-type-names"
- DEFAULT_Key = "default"
- METADATATYPE_KEY = "metadata-type"
+ GroupKey = "group"
+ VersionKey = "version"
+ InterfaceKey = "interface"
+ MessageSizeKey = "message_size"
+ PathKey = "path"
+ ServiceKey = "service"
+ MethodsKey = "methods"
+ TimeoutKey = "timeout"
+ CategoryKey = "category"
+ CheckKey = "check"
+ EnabledKey = "enabled"
+ SideKey = "side"
+ OverrideProvidersKey = "providerAddresses"
+ BeanNameKey = "bean.name"
+ GenericKey = "generic"
+ ClassifierKey = "classifier"
+ TokenKey = "token"
+ LocalAddr = "local-addr"
+ RemoteAddr = "remote-addr"
+ DefaultRemotingTimeout = 3000
+ ReleaseKey = "release"
+ AnyhostKey = "anyhost"
+ PortKey = "port"
+ ProtocolKey = "protocol"
+ PathSeparator = "/"
+ CommaSeparator = ","
+ SslEnabledKey = "ssl-enabled"
+ // ParamsTypeKey key used in pass through invoker factory, to define param type
+ ParamsTypeKey = "parameter-type-names"
+ MetadataTypeKey = "metadata-type"
)
const (
- SERVICE_FILTER_KEY = "service.filter"
- REFERENCE_FILTER_KEY = "reference.filter"
+ ServiceFilterKey = "service.filter"
+ ReferenceFilterKey = "reference.filter"
)
// Filter Keys
@@ -88,95 +86,95 @@ const (
)
const (
- TIMESTAMP_KEY = "timestamp"
- REMOTE_TIMESTAMP_KEY = "remote.timestamp"
- CLUSTER_KEY = "cluster"
- LOADBALANCE_KEY = "loadbalance"
- WEIGHT_KEY = "weight"
- WARMUP_KEY = "warmup"
- RETRIES_KEY = "retries"
- STICKY_KEY = "sticky"
- BEAN_NAME = "bean.name"
- FAIL_BACK_TASKS_KEY = "failbacktasks"
- FORKS_KEY = "forks"
- DEFAULT_FORKS = 2
- DEFAULT_TIMEOUT = 1000
- TPS_LIMITER_KEY = "tps.limiter"
- TPS_REJECTED_EXECUTION_HANDLER_KEY = "tps.limit.rejected.handler"
- TPS_LIMIT_RATE_KEY = "tps.limit.rate"
- DEFAULT_TPS_LIMIT_RATE = "-1"
- TPS_LIMIT_INTERVAL_KEY = "tps.limit.interval"
- DEFAULT_TPS_LIMIT_INTERVAL = "60000"
- TPS_LIMIT_STRATEGY_KEY = "tps.limit.strategy"
- EXECUTE_LIMIT_KEY = "execute.limit"
- DEFAULT_EXECUTE_LIMIT = "-1"
- EXECUTE_REJECTED_EXECUTION_HANDLER_KEY = "execute.limit.rejected.handler"
- SERIALIZATION_KEY = "serialization"
- PID_KEY = "pid"
- SYNC_REPORT_KEY = "sync.report"
- RETRY_PERIOD_KEY = "retry.period"
- RETRY_TIMES_KEY = "retry.times"
- CYCLE_REPORT_KEY = "cycle.report"
- DEFAULT_BLACK_LIST_RECOVER_BLOCK = 16
+ TimestampKey = "timestamp"
+ RemoteTimestampKey = "remote.timestamp"
+ ClusterKey = "cluster"
+ LoadbalanceKey = "loadbalance"
+ WeightKey = "weight"
+ WarmupKey = "warmup"
+ RetriesKey = "retries"
+ StickyKey = "sticky"
+ BeanName = "bean.name"
+ FailBackTasksKey = "failbacktasks"
+ ForksKey = "forks"
+ DefaultForks = 2
+ DefaultTimeout = 1000
+ TPSLimiterKey = "tps.limiter"
+ TPSRejectedExecutionHandlerKey = "tps.limit.rejected.handler"
+ TPSLimitRateKey = "tps.limit.rate"
+ DefaultTPSLimitRate = "-1"
+ TPSLimitIntervalKey = "tps.limit.interval"
+ DefaultTPSLimitInterval = "60000"
+ TPSLimitStrategyKey = "tps.limit.strategy"
+ ExecuteLimitKey = "execute.limit"
+ DefaultExecuteLimit = "-1"
+ ExecuteRejectedExecutionHandlerKey = "execute.limit.rejected.handler"
+ SerializationKey = "serialization"
+ PIDKey = "pid"
+ SyncReportKey = "sync.report"
+ RetryPeriodKey = "retry.period"
+ RetryTimesKey = "retry.times"
+ CycleReportKey = "cycle.report"
+ DefaultBlackListRecoverBlock = 16
)
const (
- DUBBOGO_CTX_KEY = DubboCtxKey("dubbogo-ctx")
+ DubboGoCtxKey = DubboCtxKey("dubbogo-ctx")
)
const (
- REGISTRY_KEY = "registry"
- REGISTRY_PROTOCOL = "registry"
- SERVICE_REGISTRY_PROTOCOL = "service-discovery-registry"
- ROLE_KEY = "registry.role"
- REGISTRY_DEFAULT_KEY = "registry.default"
- REGISTRY_TIMEOUT_KEY = "registry.timeout"
- REGISTRY_LABEL_KEY = "label"
- PREFERRED_KEY = "preferred"
- ZONE_KEY = "zone"
- ZONE_FORCE_KEY = "zone.force"
- REGISTRY_TTL_KEY = "registry.ttl"
- SIMPLIFIED_KEY = "simplified"
- NAMESPACE_KEY = "namespace"
- REGISTRY_GROUP_KEY = "registry.group"
+ RegistryKey = "registry"
+ RegistryProtocol = "registry"
+ ServiceRegistryProtocol = "service-discovery-registry"
+ RoleKey = "registry.role"
+ RegistryDefaultKey = "registry.default"
+ RegistryTimeoutKey = "registry.timeout"
+ RegistryLabelKey = "label"
+ PreferredKey = "preferred"
+ ZoneKey = "zone"
+ ZoneForceKey = "zone.force"
+ RegistryTTLKey = "registry.ttl"
+ SimplifiedKey = "simplified"
+ NamespaceKey = "namespace"
+ RegistryGroupKey = "registry.group"
)
const (
- APPLICATION_KEY = "application"
- ORGANIZATION_KEY = "organization"
- NAME_KEY = "name"
- MODULE_KEY = "module"
- APP_VERSION_KEY = "app.version"
- OWNER_KEY = "owner"
- ENVIRONMENT_KEY = "environment"
- METHOD_KEY = "method"
- METHOD_KEYS = "methods"
- RULE_KEY = "rule"
- RUNTIME_KEY = "runtime"
- BACKUP_KEY = "backup"
- ROUTERS_CATEGORY = "routers"
- ROUTE_PROTOCOL = "route"
- CONDITION_ROUTE_PROTOCOL = "condition"
- TAG_ROUTE_PROTOCOL = "tag"
- PROVIDERS_CATEGORY = "providers"
- ROUTER_KEY = "router"
- EXPORT_KEY = "export"
+ ApplicationKey = "application"
+ OrganizationKey = "organization"
+ NameKey = "name"
+ ModuleKey = "module"
+ AppVersionKey = "app.version"
+ OwnerKey = "owner"
+ EnvironmentKey = "environment"
+ MethodKey = "method"
+ MethodKeys = "methods"
+ RuleKey = "rule"
+ RuntimeKey = "runtime"
+ BackupKey = "backup"
+ RoutersCategory = "routers"
+ RouteProtocol = "route"
+ ConditionRouteProtocol = "condition"
+ TagRouteProtocol = "tag"
+ ProvidersCategory = "providers"
+ RouterKey = "router"
+ ExportKey = "export"
)
const (
- CONFIG_NAMESPACE_KEY = "namespace"
- CONFIG_GROUP_KEY = "group"
- CONFIG_APP_ID_KEY = "appId"
- CONFIG_CLUSTER_KEY = "cluster"
- CONFIG_TIMEOUT_KEY = "timeout"
- CONFIG_USERNAME_KEY = "username"
- CONFIG_PASSWORD_KEY = "password"
- CONFIG_LOG_DIR_KEY = "logDir"
- CONFIG_VERSION_KEY = "configVersion"
- COMPATIBLE_CONFIG_KEY = "compatible_config"
- CONFIG_SECRET_KEY = "secret"
- CONFIG_BACKUP_CONFIG_KEY = "isBackupConfig"
- CONFIG_BACKUP_CONFIG_PATH_KEY = "backupConfigPath"
+ ConfigNamespaceKey = "namespace"
+ ConfigGroupKey = "group"
+ ConfigAppIDKey = "appId"
+ ConfigClusterKey = "cluster"
+ ConfigTimeoutKey = "timeout"
+ ConfigUsernameKey = "username"
+ ConfigPasswordKey = "password"
+ ConfigLogDirKey = "logDir"
+ ConfigVersionKey = "configVersion"
+ CompatibleConfigKey = "compatible_config"
+ ConfigSecretKey = "secret"
+ ConfigBackupConfigKey = "isBackupConfig"
+ ConfigBackupConfigPathKey = "backupConfigPath"
)
const (
@@ -203,39 +201,39 @@ const (
)
const (
- NACOS_KEY = "nacos"
- NACOS_DEFAULT_ROLETYPE = 3
- NACOS_CACHE_DIR_KEY = "cacheDir"
- NACOS_LOG_DIR_KEY = "logDir"
- NACOS_BEAT_INTERVAL_KEY = "beatInterval"
- NACOS_ENDPOINT = "endpoint"
- NACOS_SERVICE_NAME_SEPARATOR = ":"
- NACOS_CATEGORY_KEY = "category"
- NACOS_PROTOCOL_KEY = "protocol"
- NACOS_PATH_KEY = "path"
- NACOS_NAMESPACE_ID = "namespaceId"
- NACOS_PASSWORD = "password"
- NACOS_USERNAME = "username"
- NACOS_NOT_LOAD_LOCAL_CACHE = "nacos.not.load.cache"
- NACOS_APP_NAME_KEY = "appName"
- NACOS_REGION_ID_KEY = "regionId"
- NACOS_ACCESS_KEY = "access"
- NACOS_SECRET_KEY = "secret"
- NACOS_OPEN_KMS_KEY = "kms"
- NACOS_UPDATE_THREAD_NUM_KEY = "updateThreadNum"
- NACOS_LOG_LEVEL_KEY = "logLevel"
+ NacosKey = "nacos"
+ NacosDefaultRoleType = 3
+ NacosCacheDirKey = "cacheDir"
+ NacosLogDirKey = "logDir"
+ NacosBeatIntervalKey = "beatInterval"
+ NacosEndpoint = "endpoint"
+ NacosServiceNameSeparator = ":"
+ NacosCategoryKey = "category"
+ NacosProtocolKey = "protocol"
+ NacosPathKey = "path"
+ NacosNamespaceID = "namespaceId"
+ NacosPassword = "password"
+ NacosUsername = "username"
+ NacosNotLoadLocalCache = "nacos.not.load.cache"
+ NacosAppNameKey = "appName"
+ NacosRegionIDKey = "regionId"
+ NacosAccessKey = "access"
+ NacosSecretKey = "secret"
+ NacosOpenKmsKey = "kms"
+ NacosUpdateThreadNumKey = "updateThreadNum"
+ NacosLogLevelKey = "logLevel"
)
const (
- FILE_KEY = "file"
+ FileKey = "file"
)
const (
- ZOOKEEPER_KEY = "zookeeper"
+ ZookeeperKey = "zookeeper"
)
const (
- ETCDV3_KEY = "etcdv3"
+ EtcdV3Key = "etcdv3"
)
const (
@@ -244,7 +242,7 @@ const (
)
const (
- TRACING_REMOTE_SPAN_CTX = DubboCtxKey("tracing.remote.span.ctx")
+ TracingRemoteSpanCtx = DubboCtxKey("tracing.remote.span.ctx")
)
// Use for router module
@@ -265,63 +263,63 @@ const (
// Auth filter
const (
// name of service filter
- SERVICE_AUTH_KEY = "auth"
+ ServiceAuthKey = "auth"
// key of authenticator
- AUTHENTICATOR_KEY = "authenticator"
+ AuthenticatorKey = "authenticator"
// name of default authenticator
- DEFAULT_AUTHENTICATOR = "accesskeys"
+ DefaultAuthenticator = "accesskeys"
// name of default url storage
- DEFAULT_ACCESS_KEY_STORAGE = "urlstorage"
+ DefaultAccessKeyStorage = "urlstorage"
// key of storage
- ACCESS_KEY_STORAGE_KEY = "accessKey.storage"
+ AccessKeyStorageKey = "accessKey.storage"
// key of request timestamp
- REQUEST_TIMESTAMP_KEY = "timestamp"
+ RequestTimestampKey = "timestamp"
// key of request signature
- REQUEST_SIGNATURE_KEY = "signature"
+ RequestSignatureKey = "signature"
// AK key
- AK_KEY = "ak"
+ AKKey = "ak"
// signature format
- SIGNATURE_STRING_FORMAT = "%s#%s#%s#%s"
+ SignatureStringFormat = "%s#%s#%s#%s"
// key whether enable signature
- PARAMETER_SIGNATURE_ENABLE_KEY = "param.sign"
+ ParameterSignatureEnableKey = "param.sign"
// consumer
- CONSUMER = "consumer"
+ Consumer = "consumer"
// key of access key id
- ACCESS_KEY_ID_KEY = ".accessKeyId"
+ AccessKeyIDKey = ".accessKeyId"
// key of secret access key
- SECRET_ACCESS_KEY_KEY = ".secretAccessKey"
+ SecretAccessKeyKey = ".secretAccessKey"
)
// metadata report
const (
- METACONFIG_REMOTE = "remote"
- METACONFIG_LOCAL = "local"
- KEY_SEPARATOR = ":"
- DEFAULT_PATH_TAG = "metadata"
- KEY_REVISON_PREFIX = "revision"
+ MetaConfigRemote = "remote"
+ MetaConfigLocal = "local"
+ KeySeparator = ":"
+ DefaultPathTag = "metadata"
+ KeyRevisionPrefix = "revision"
// metadata service
- METADATA_SERVICE_NAME = "org.apache.dubbo.metadata.MetadataService"
+ MetadataServiceName = "org.apache.dubbo.metadata.MetadataService"
)
// service discovery
const (
- SUBSCRIBED_SERVICE_NAMES_KEY = "subscribed-services"
- PROVIDED_BY = "provided-by"
- EXPORTED_SERVICES_REVISION_PROPERTY_NAME = "dubbo.metadata.revision"
- SUBSCRIBED_SERVICES_REVISION_PROPERTY_NAME = "dubbo.subscribed-services.revision"
- SERVICE_INSTANCE_SELECTOR = "service-instance-selector"
- METADATA_STORAGE_TYPE_PROPERTY_NAME = "dubbo.metadata.storage-type"
- DEFAULT_METADATA_STORAGE_TYPE = "local"
- REMOTE_METADATA_STORAGE_TYPE = "remote"
- SERVICE_INSTANCE_ENDPOINTS = "dubbo.endpoints"
- METADATA_SERVICE_PREFIX = "dubbo.metadata-service."
- METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME = METADATA_SERVICE_PREFIX + "url-params"
- METADATA_SERVICE_URLS_PROPERTY_NAME = METADATA_SERVICE_PREFIX + "urls"
+ SubscribedServiceNamesKey = "subscribed-services"
+ ProvidedBy = "provided-by"
+ ExportedServicesRevisionPropertyName = "dubbo.metadata.revision"
+ SubscribedServicesRevisionPropertyName = "dubbo.subscribed-services.revision"
+ ServiceInstanceSelector = "service-instance-selector"
+ MetadataStorageTypePropertyName = "dubbo.metadata.storage-type"
+ DefaultMetadataStorageType = "local"
+ RemoteMetadataStorageType = "remote"
+ ServiceInstanceEndpoints = "dubbo.endpoints"
+ MetadataServicePrefix = "dubbo.metadata-service."
+ MetadataServiceURLParamsPropertyName = MetadataServicePrefix + "url-params"
+ MetadataServiceURLsPropertyName = MetadataServicePrefix + "urls"
- // SERVICE_DISCOVERY_KEY indicate which service discovery instance will be used
- SERVICE_DISCOVERY_KEY = "service_discovery"
+ // ServiceDiscoveryKey indicate which service discovery instance will be used
+ ServiceDiscoveryKey = "service_discovery"
)
// Generic Filter
diff --git a/common/constant/serialization.go b/common/constant/serialization.go
index 60c51df..620037d 100644
--- a/common/constant/serialization.go
+++ b/common/constant/serialization.go
@@ -18,12 +18,12 @@
package constant
const (
- S_Hessian2 byte = 2
- S_Proto byte = 21
+ SHessian2 byte = 2
+ SProto byte = 21
)
const (
- HESSIAN2_SERIALIZATION = "hessian2"
- PROTOBUF_SERIALIZATION = "protobuf"
- MSGPACK_SERIALIZATION = "msgpack"
+ Hessian2Serialization = "hessian2"
+ ProtobufSerialization = "protobuf"
+ MsgpackSerialization = "msgpack"
)
diff --git a/common/extension/metadata_service.go b/common/extension/metadata_service.go
index 780ad37..486f051 100644
--- a/common/extension/metadata_service.go
+++ b/common/extension/metadata_service.go
@@ -44,7 +44,7 @@ func SetLocalMetadataService(key string, creator localMetadataServiceCreator) {
// GetMetadataService will create a local MetadataService instance
func GetLocalMetadataService(key string) (service.MetadataService, error) {
if key == "" {
- key = constant.DEFAULT_KEY
+ key = constant.DefaultKey
}
if creator, ok := localMetadataServiceInsMap[key]; ok {
return creator()
diff --git a/common/extension/metadata_service_exporter.go b/common/extension/metadata_service_exporter.go
index 45e71e2..ab8cff8 100644
--- a/common/extension/metadata_service_exporter.go
+++ b/common/extension/metadata_service_exporter.go
@@ -37,7 +37,7 @@ func SetMetadataServiceExporter(key string, creator MetadataServiceExporterCreat
// GetMetadataServiceExporter will create a MetadataServiceExporter instance
func GetMetadataServiceExporter(key string, s service.MetadataService) exporter.MetadataServiceExporter {
if key == "" {
- key = constant.DEFAULT_KEY
+ key = constant.DefaultKey
}
if creator, ok := metadataServiceExporterInsMap[key]; ok {
return creator(s)
diff --git a/common/extension/metadata_service_proxy_factory.go b/common/extension/metadata_service_proxy_factory.go
index 113b4ba..ecb8fb4 100644
--- a/common/extension/metadata_service_proxy_factory.go
+++ b/common/extension/metadata_service_proxy_factory.go
@@ -39,7 +39,7 @@ func SetMetadataServiceProxyFactory(name string, creator MetadataServiceProxyFac
// it will panic if the factory with name not found
func GetMetadataServiceProxyFactory(name string) service.MetadataServiceProxyFactory {
if name == "" {
- name = constant.DEFAULT_KEY
+ name = constant.DefaultKey
}
if f, ok := metadataServiceProxyFactoryMap[name]; ok {
return f()
diff --git a/common/metadata_info.go b/common/metadata_info.go
index 9c43f69..73670cf 100644
--- a/common/metadata_info.go
+++ b/common/metadata_info.go
@@ -34,19 +34,19 @@ import (
)
var IncludeKeys = gxset.NewSet(
- constant.APPLICATION_KEY,
- constant.GROUP_KEY,
- constant.TIMESTAMP_KEY,
- constant.SERIALIZATION_KEY,
- constant.CLUSTER_KEY,
- constant.LOADBALANCE_KEY,
- constant.PATH_KEY,
- constant.TIMEOUT_KEY,
- constant.TOKEN_KEY,
- constant.VERSION_KEY,
- constant.WARMUP_KEY,
- constant.WEIGHT_KEY,
- constant.RELEASE_KEY)
+ constant.ApplicationKey,
+ constant.GroupKey,
+ constant.TimestampKey,
+ constant.SerializationKey,
+ constant.ClusterKey,
+ constant.LoadbalanceKey,
+ constant.PathKey,
+ constant.TimeoutKey,
+ constant.TokenKey,
+ constant.VersionKey,
+ constant.WarmupKey,
+ constant.WeightKey,
+ constant.ReleaseKey)
// MetadataInfo the metadata information of instance
type MetadataInfo struct {
@@ -97,7 +97,7 @@ func (mi *MetadataInfo) CalAndGetRevision() string {
} else {
for _, m := range ms {
// methods are part of candidates
- candidates = append(candidates, sk+constant.KEY_SEPARATOR+m)
+ candidates = append(candidates, sk+constant.KeySeparator+m)
}
}
@@ -201,8 +201,8 @@ func (si *ServiceInfo) JavaClassName() string {
// nolint
func (si *ServiceInfo) GetMethods() []string {
- if si.Params[constant.METHODS_KEY] != "" {
- s := si.Params[constant.METHODS_KEY]
+ if si.Params[constant.MethodsKey] != "" {
+ s := si.Params[constant.MethodsKey]
return strings.Split(s, ",")
}
methods := make([]string, 8)
diff --git a/common/proxy/proxy_factory/default.go b/common/proxy/proxy_factory/default.go
index f76bc38..2e1816b 100644
--- a/common/proxy/proxy_factory/default.go
+++ b/common/proxy/proxy_factory/default.go
@@ -66,7 +66,7 @@ func (factory *DefaultProxyFactory) GetProxy(invoker protocol.Invoker, url *comm
func (factory *DefaultProxyFactory) GetAsyncProxy(invoker protocol.Invoker, callBack interface{}, url *common.URL) *proxy.Proxy {
// create proxy
attachments := map[string]string{}
- attachments[constant.ASYNC_KEY] = url.GetParam(constant.ASYNC_KEY, "false")
+ attachments[constant.AsyncKey] = url.GetParam(constant.AsyncKey, "false")
return proxy.NewProxy(invoker, callBack, attachments)
}
diff --git a/common/proxy/proxy_factory/pass_through.go b/common/proxy/proxy_factory/pass_through.go
index d237d99..6ad28dc 100644
--- a/common/proxy/proxy_factory/pass_through.go
+++ b/common/proxy/proxy_factory/pass_through.go
@@ -56,7 +56,7 @@ func (factory *PassThroughProxyFactory) GetProxy(invoker protocol.Invoker, url *
func (factory *PassThroughProxyFactory) GetAsyncProxy(invoker protocol.Invoker, callBack interface{}, url *common.URL) *proxy.Proxy {
//create proxy
attachments := map[string]string{}
- attachments[constant.ASYNC_KEY] = url.GetParam(constant.ASYNC_KEY, "false")
+ attachments[constant.AsyncKey] = url.GetParam(constant.AsyncKey, "false")
return proxy.NewProxy(invoker, callBack, attachments)
}
@@ -102,7 +102,7 @@ func (pi *PassThroughProxyInvoker) Invoke(ctx context.Context, invocation protoc
in := make([]reflect.Value, 5)
in = append(in, srv.Rcvr())
in = append(in, reflect.ValueOf(invocation.MethodName()))
- in = append(in, reflect.ValueOf(invocation.Attachment(constant.PARAMS_TYPE_Key)))
+ in = append(in, reflect.ValueOf(invocation.Attachment(constant.ParamsTypeKey)))
in = append(in, reflect.ValueOf(args))
in = append(in, reflect.ValueOf(invocation.Attachments()))
diff --git a/common/proxy/proxy_test.go b/common/proxy/proxy_test.go
index e9bacd6..835e421 100644
--- a/common/proxy/proxy_test.go
+++ b/common/proxy/proxy_test.go
@@ -60,7 +60,7 @@ func (s *TestServiceInt) Reference() string {
func TestProxyImplement(t *testing.T) {
invoker := protocol.NewBaseInvoker(&common.URL{})
- p := NewProxy(invoker, nil, map[string]string{constant.ASYNC_KEY: "false"})
+ p := NewProxy(invoker, nil, map[string]string{constant.AsyncKey: "false"})
s := &TestService{}
p.Implement(s)
@@ -128,7 +128,7 @@ func TestProxyImplementForContext(t *testing.T) {
invoker := &TestProxyInvoker{
BaseInvoker: *protocol.NewBaseInvoker(&common.URL{}),
}
- p := NewProxy(invoker, nil, map[string]string{constant.ASYNC_KEY: "false"})
+ p := NewProxy(invoker, nil, map[string]string{constant.AsyncKey: "false"})
s := &TestService{}
p.Implement(s)
attachments1 := make(map[string]interface{}, 4)
diff --git a/common/url.go b/common/url.go
index fc618ea..e65c749 100644
--- a/common/url.go
+++ b/common/url.go
@@ -213,7 +213,7 @@ func WithToken(token string) Option {
u, _ := uuid.NewV4()
value = u.String()
}
- url.SetParam(constant.TOKEN_KEY, value)
+ url.SetParam(constant.TokenKey, value)
}
}
}
@@ -287,12 +287,12 @@ func MatchKey(serviceKey string, protocol string) string {
// Group get group
func (c *URL) Group() string {
- return c.GetParam(constant.GROUP_KEY, "")
+ return c.GetParam(constant.GroupKey, "")
}
// Version get group
func (c *URL) Version() string {
- return c.GetParam(constant.VERSION_KEY, "")
+ return c.GetParam(constant.VersionKey, "")
}
// URLEqual judge @URL and @c is equal or not.
@@ -305,14 +305,14 @@ func (c *URL) URLEqual(url *URL) bool {
tmpURL.Ip = ""
tmpURL.Port = ""
- cGroup := tmpC.GetParam(constant.GROUP_KEY, "")
- urlGroup := tmpURL.GetParam(constant.GROUP_KEY, "")
+ cGroup := tmpC.GetParam(constant.GroupKey, "")
+ urlGroup := tmpURL.GetParam(constant.GroupKey, "")
cKey := tmpC.Key()
urlKey := tmpURL.Key()
- if cGroup == constant.ANY_VALUE {
+ if cGroup == constant.AnyValue {
cKey = strings.Replace(cKey, "group=*", "group="+urlGroup, 1)
- } else if urlGroup == constant.ANY_VALUE {
+ } else if urlGroup == constant.AnyValue {
urlKey = strings.Replace(urlKey, "group=*", "group="+cGroup, 1)
}
@@ -322,21 +322,21 @@ func (c *URL) URLEqual(url *URL) bool {
}
// 2. if URL contains enabled key, should be true, or *
- if tmpURL.GetParam(constant.ENABLED_KEY, "true") != "true" && tmpURL.GetParam(constant.ENABLED_KEY, "") != constant.ANY_VALUE {
+ if tmpURL.GetParam(constant.EnabledKey, "true") != "true" && tmpURL.GetParam(constant.EnabledKey, "") != constant.AnyValue {
return false
}
// TODO :may need add interface key any value condition
- return isMatchCategory(tmpURL.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY), tmpC.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY))
+ return isMatchCategory(tmpURL.GetParam(constant.CategoryKey, constant.DefaultCategory), tmpC.GetParam(constant.CategoryKey, constant.DefaultCategory))
}
func isMatchCategory(category1 string, category2 string) bool {
if len(category2) == 0 {
- return category1 == constant.DEFAULT_CATEGORY
- } else if strings.Contains(category2, constant.ANY_VALUE) {
+ return category1 == constant.DefaultCategory
+ } else if strings.Contains(category2, constant.AnyValue) {
return true
- } else if strings.Contains(category2, constant.REMOVE_VALUE_PREFIX) {
- return !strings.Contains(category2, constant.REMOVE_VALUE_PREFIX+category1)
+ } else if strings.Contains(category2, constant.RemoveValuePrefix) {
+ return !strings.Contains(category2, constant.RemoveValuePrefix+category1)
} else {
return strings.Contains(category2, category1)
}
@@ -358,7 +358,7 @@ func (c *URL) String() string {
// Key gets key
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, ""))
+ c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Service(), c.GetParam(constant.GroupKey, ""), c.GetParam(constant.VersionKey, ""))
return buildString
}
@@ -367,15 +367,15 @@ func (c *URL) GetCacheInvokerMapKey() string {
urlNew, _ := NewURL(c.PrimitiveURL)
buildString := fmt.Sprintf("%s://%s:%s@%s:%s/?interface=%s&group=%s&version=%s×tamp=%s",
- c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Service(), c.GetParam(constant.GROUP_KEY, ""),
- c.GetParam(constant.VERSION_KEY, ""), urlNew.GetParam(constant.TIMESTAMP_KEY, ""))
+ c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Service(), c.GetParam(constant.GroupKey, ""),
+ c.GetParam(constant.VersionKey, ""), urlNew.GetParam(constant.TimestampKey, ""))
return buildString
}
// ServiceKey gets a unique key of a service.
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, ""))
+ return ServiceKey(c.GetParam(constant.InterfaceKey, strings.TrimPrefix(c.Path, "/")),
+ c.GetParam(constant.GroupKey, ""), c.GetParam(constant.VersionKey, ""))
}
func ServiceKey(intf string, group string, version string) string {
@@ -401,18 +401,18 @@ func ServiceKey(intf string, group string, version string) string {
// ColonSeparatedKey
// The format is "{interface}:[version]:[group]"
func (c *URL) ColonSeparatedKey() string {
- intf := c.GetParam(constant.INTERFACE_KEY, strings.TrimPrefix(c.Path, "/"))
+ intf := c.GetParam(constant.InterfaceKey, strings.TrimPrefix(c.Path, "/"))
if intf == "" {
return ""
}
var buf strings.Builder
buf.WriteString(intf)
buf.WriteString(":")
- version := c.GetParam(constant.VERSION_KEY, "")
+ version := c.GetParam(constant.VersionKey, "")
if version != "" && version != "0.0.0" {
buf.WriteString(version)
}
- group := c.GetParam(constant.GROUP_KEY, "")
+ group := c.GetParam(constant.GroupKey, "")
buf.WriteString(":")
if group != "" {
buf.WriteString(group)
@@ -428,11 +428,11 @@ func (c *URL) EncodedServiceKey() string {
// Service gets service
func (c *URL) Service() string {
- service := c.GetParam(constant.INTERFACE_KEY, strings.TrimPrefix(c.Path, "/"))
+ service := c.GetParam(constant.InterfaceKey, strings.TrimPrefix(c.Path, "/"))
if service != "" {
return service
} else if c.SubURL != nil {
- service = c.SubURL.GetParam(constant.INTERFACE_KEY, strings.TrimPrefix(c.Path, "/"))
+ service = c.SubURL.GetParam(constant.InterfaceKey, strings.TrimPrefix(c.Path, "/"))
if service != "" { // if URL.path is "" then return suburl's path, special for registry URL
return service
}
@@ -701,12 +701,12 @@ func MergeURL(serviceURL *URL, referenceURL *URL) *URL {
}
// loadBalance,cluster,retries strategy config
- methodConfigMergeFcn := mergeNormalParam(params, referenceURL, []string{constant.LOADBALANCE_KEY, constant.CLUSTER_KEY, constant.RETRIES_KEY, constant.TIMEOUT_KEY})
+ methodConfigMergeFcn := mergeNormalParam(params, referenceURL, []string{constant.LoadbalanceKey, constant.ClusterKey, constant.RetriesKey, constant.TimeoutKey})
// remote timestamp
- if v := serviceURL.GetParam(constant.TIMESTAMP_KEY, ""); len(v) > 0 {
- params[constant.REMOTE_TIMESTAMP_KEY] = []string{v}
- params[constant.TIMESTAMP_KEY] = []string{referenceURL.GetParam(constant.TIMESTAMP_KEY, "")}
+ if v := serviceURL.GetParam(constant.TimestampKey, ""); len(v) > 0 {
+ params[constant.RemoteTimestampKey] = []string{v}
+ params[constant.TimestampKey] = []string{referenceURL.GetParam(constant.TimestampKey, "")}
}
// finally execute methodConfigMergeFcn
diff --git a/common/url_test.go b/common/url_test.go
index ba5092a..66f0003 100644
--- a/common/url_test.go
+++ b/common/url_test.go
@@ -306,24 +306,24 @@ func TestURLGetMethodParamBool(t *testing.T) {
func TestMergeUrl(t *testing.T) {
referenceUrlParams := url.Values{}
- referenceUrlParams.Set(constant.CLUSTER_KEY, "random")
- referenceUrlParams.Set(constant.RETRIES_KEY, "1")
+ referenceUrlParams.Set(constant.ClusterKey, "random")
+ referenceUrlParams.Set(constant.RetriesKey, "1")
referenceUrlParams.Set("test3", "1")
- referenceUrlParams.Set("methods.testMethod."+constant.RETRIES_KEY, "1")
+ referenceUrlParams.Set("methods.testMethod."+constant.RetriesKey, "1")
serviceUrlParams := url.Values{}
serviceUrlParams.Set("test2", "1")
- serviceUrlParams.Set(constant.CLUSTER_KEY, "roundrobin")
- serviceUrlParams.Set(constant.RETRIES_KEY, "2")
- serviceUrlParams.Set(constant.METHOD_KEYS+".testMethod."+constant.RETRIES_KEY, "2")
+ serviceUrlParams.Set(constant.ClusterKey, "roundrobin")
+ serviceUrlParams.Set(constant.RetriesKey, "2")
+ serviceUrlParams.Set(constant.MethodKeys+".testMethod."+constant.RetriesKey, "2")
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)
- assert.Equal(t, "random", mergedUrl.GetParam(constant.CLUSTER_KEY, ""))
+ assert.Equal(t, "random", mergedUrl.GetParam(constant.ClusterKey, ""))
assert.Equal(t, "1", mergedUrl.GetParam("test2", ""))
assert.Equal(t, "1", mergedUrl.GetParam("test3", ""))
- assert.Equal(t, "1", mergedUrl.GetParam(constant.RETRIES_KEY, ""))
- assert.Equal(t, "2", mergedUrl.GetParam(constant.METHOD_KEYS+".testMethod."+constant.RETRIES_KEY, ""))
+ assert.Equal(t, "1", mergedUrl.GetParam(constant.RetriesKey, ""))
+ assert.Equal(t, "2", mergedUrl.GetParam(constant.MethodKeys+".testMethod."+constant.RetriesKey, ""))
}
func TestURLSetParams(t *testing.T) {
@@ -359,15 +359,15 @@ func TestClone(t *testing.T) {
func TestColonSeparatedKey(t *testing.T) {
u1, _ := NewURL("dubbo://127.0.0.1:20000")
- u1.AddParam(constant.INTERFACE_KEY, "com.ikurento.user.UserProvider")
-
- assert.Equal(t, u1.ColonSeparatedKey(), u1.GetParam(constant.INTERFACE_KEY, "")+"::")
- u1.AddParam(constant.VERSION_KEY, "version1")
- assert.Equal(t, u1.ColonSeparatedKey(), u1.GetParam(constant.INTERFACE_KEY, "")+":version1:")
- u1.AddParam(constant.GROUP_KEY, "group1")
- assert.Equal(t, u1.ColonSeparatedKey(), u1.GetParam(constant.INTERFACE_KEY, "")+":version1:group1")
- u1.SetParam(constant.VERSION_KEY, "")
- assert.Equal(t, u1.ColonSeparatedKey(), u1.GetParam(constant.INTERFACE_KEY, "")+"::group1")
+ u1.AddParam(constant.InterfaceKey, "com.ikurento.user.UserProvider")
+
+ assert.Equal(t, u1.ColonSeparatedKey(), u1.GetParam(constant.InterfaceKey, "")+"::")
+ u1.AddParam(constant.VersionKey, "version1")
+ assert.Equal(t, u1.ColonSeparatedKey(), u1.GetParam(constant.InterfaceKey, "")+":version1:")
+ u1.AddParam(constant.GroupKey, "group1")
+ assert.Equal(t, u1.ColonSeparatedKey(), u1.GetParam(constant.InterfaceKey, "")+":version1:group1")
+ u1.SetParam(constant.VersionKey, "")
+ assert.Equal(t, u1.ColonSeparatedKey(), u1.GetParam(constant.InterfaceKey, "")+"::group1")
}
func TestCompareURLEqualFunc(t *testing.T) {
@@ -383,7 +383,7 @@ func TestCompareURLEqualFunc(t *testing.T) {
"module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&" +
"side=provider&timeout=3000×tamp=155650979798")
assert.False(t, GetCompareURLEqualFunc()(url1, url2))
- assert.True(t, GetCompareURLEqualFunc()(url1, url2, constant.TIMESTAMP_KEY, constant.REMOTE_TIMESTAMP_KEY))
+ assert.True(t, GetCompareURLEqualFunc()(url1, url2, constant.TimestampKey, constant.RemoteTimestampKey))
// test custom
url1, _ = NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&" +
@@ -396,10 +396,10 @@ func TestCompareURLEqualFunc(t *testing.T) {
"environment=dev&interface=com.ikurento.user.UserProvider&ip=192.168.56.1&methods=GetUser%2C&" +
"module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&" +
"side=provider&timeout=3000×tamp=155650979798")
- assert.True(t, GetCompareURLEqualFunc()(url1, url2, constant.TIMESTAMP_KEY, constant.REMOTE_TIMESTAMP_KEY))
+ assert.True(t, GetCompareURLEqualFunc()(url1, url2, constant.TimestampKey, constant.RemoteTimestampKey))
SetCompareURLEqualFunc(CustomCompareURLEqual)
assert.False(t, GetCompareURLEqualFunc()(url1, url2))
- assert.False(t, GetCompareURLEqualFunc()(url1, url2, constant.TIMESTAMP_KEY, constant.REMOTE_TIMESTAMP_KEY))
+ assert.False(t, GetCompareURLEqualFunc()(url1, url2, constant.TimestampKey, constant.RemoteTimestampKey))
url1, _ = NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&" +
"application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&" +
@@ -412,10 +412,10 @@ func TestCompareURLEqualFunc(t *testing.T) {
"module=dubbogo+user-info+server&org=ikurento.com&owner=ZX&pid=1447&revision=0.0.1&" +
"side=provider&timeout=3000")
assert.True(t, GetCompareURLEqualFunc()(url1, url2))
- assert.True(t, GetCompareURLEqualFunc()(url1, url2, constant.TIMESTAMP_KEY, constant.REMOTE_TIMESTAMP_KEY))
+ assert.True(t, GetCompareURLEqualFunc()(url1, url2, constant.TimestampKey, constant.RemoteTimestampKey))
SetCompareURLEqualFunc(CustomCompareURLEqual)
assert.True(t, GetCompareURLEqualFunc()(url1, url2))
- assert.True(t, GetCompareURLEqualFunc()(url1, url2, constant.TIMESTAMP_KEY, constant.REMOTE_TIMESTAMP_KEY))
+ assert.True(t, GetCompareURLEqualFunc()(url1, url2, constant.TimestampKey, constant.RemoteTimestampKey))
}
func CustomCompareURLEqual(l *URL, r *URL, execludeParam ...string) bool {
diff --git a/config/config_center_config.go b/config/config_center_config.go
index 28a83cd..b97ae3e 100644
--- a/config/config_center_config.go
+++ b/config/config_center_config.go
@@ -89,13 +89,13 @@ func (c *CenterConfig) Init(rc *RootConfig) error {
// GetUrlMap gets url map from ConfigCenterConfig
func (c *CenterConfig) GetUrlMap() url.Values {
urlMap := url.Values{}
- urlMap.Set(constant.CONFIG_NAMESPACE_KEY, c.Namespace)
- urlMap.Set(constant.CONFIG_GROUP_KEY, c.Group)
- urlMap.Set(constant.CONFIG_CLUSTER_KEY, c.Cluster)
- urlMap.Set(constant.CONFIG_APP_ID_KEY, c.AppID)
- urlMap.Set(constant.CONFIG_USERNAME_KEY, c.Username)
- urlMap.Set(constant.CONFIG_PASSWORD_KEY, c.Password)
- urlMap.Set(constant.CONFIG_TIMEOUT_KEY, c.Timeout)
+ urlMap.Set(constant.ConfigNamespaceKey, c.Namespace)
+ urlMap.Set(constant.ConfigGroupKey, c.Group)
+ urlMap.Set(constant.ConfigClusterKey, c.Cluster)
+ urlMap.Set(constant.ConfigAppIDKey, c.AppID)
+ urlMap.Set(constant.ConfigUsernameKey, c.Username)
+ urlMap.Set(constant.ConfigPasswordKey, c.Password)
+ urlMap.Set(constant.ConfigTimeoutKey, c.Timeout)
for key, val := range c.Params {
urlMap.Set(key, val)
diff --git a/config/config_loader.go b/config/config_loader.go
index a4ca685..8b47ceb 100644
--- a/config/config_loader.go
+++ b/config/config_loader.go
@@ -71,7 +71,7 @@ func registerServiceInstance() {
if err != nil {
panic(err)
}
- p := extension.GetProtocol(constant.REGISTRY_KEY)
+ p := extension.GetProtocol(constant.RegistryKey)
var rp registry.RegistryFactory
var ok bool
if rp, ok = p.(registry.RegistryFactory); !ok {
@@ -90,7 +90,7 @@ func registerServiceInstance() {
}
}
// publish metadata to remote
- if GetApplicationConfig().MetadataType == constant.REMOTE_METADATA_STORAGE_TYPE {
+ if GetApplicationConfig().MetadataType == constant.RemoteMetadataStorageType {
if remoteMetadataService, err := extension.GetRemoteMetadataService(); err == nil {
remoteMetadataService.PublishMetadata(GetApplicationConfig().Name)
}
@@ -113,13 +113,13 @@ func createInstance(url *common.URL) (registry.ServiceInstance, error) {
// usually we will add more metadata
metadata := make(map[string]string, 8)
- metadata[constant.METADATA_STORAGE_TYPE_PROPERTY_NAME] = appConfig.MetadataType
+ metadata[constant.MetadataStorageTypePropertyName] = appConfig.MetadataType
instance := ®istry.DefaultServiceInstance{
ServiceName: appConfig.Name,
Host: host,
Port: int(port),
- ID: host + constant.KEY_SEPARATOR + url.Port,
+ ID: host + constant.KeySeparator + url.Port,
Enable: true,
Healthy: true,
Metadata: metadata,
diff --git a/config/config_loader_options.go b/config/config_loader_options.go
index f98c8a5..598a478 100644
--- a/config/config_loader_options.go
+++ b/config/config_loader_options.go
@@ -48,7 +48,7 @@ type loaderConf struct {
func NewLoaderConf(opts ...LoaderConfOption) *loaderConf {
configFilePath := "../conf/dubbogo.yaml"
- if configFilePathFromEnv := os.Getenv(constant.CONFIG_FILE_ENV_KEY); configFilePathFromEnv != "" {
+ if configFilePathFromEnv := os.Getenv(constant.ConfigFileEnvKey); configFilePathFromEnv != "" {
configFilePath = configFilePathFromEnv
}
genre := strings.Split(configFilePath, ".")
diff --git a/config/config_utils.go b/config/config_utils.go
index 82e2859..2ba76ab 100644
--- a/config/config_utils.go
+++ b/config/config_utils.go
@@ -46,11 +46,11 @@ func mergeValue(str1, str2, def string) string {
s1 := strings.Split(str1, ",")
s2 := strings.Split(str2, ",")
str := "," + strings.Join(append(s1, s2...), ",")
- defKey := strings.Contains(str, ","+constant.DEFAULT_KEY)
+ defKey := strings.Contains(str, ","+constant.DefaultKey)
if !defKey {
- str = "," + constant.DEFAULT_KEY + str
+ str = "," + constant.DefaultKey + str
}
- str = strings.TrimPrefix(strings.Replace(str, ","+constant.DEFAULT_KEY, ","+def, -1), ",")
+ str = strings.TrimPrefix(strings.Replace(str, ","+constant.DefaultKey, ","+def, -1), ",")
return removeMinus(strings.Split(str, ","))
}
diff --git a/config/graceful_shutdown.go b/config/graceful_shutdown.go
index 7626413..dfcc79e 100644
--- a/config/graceful_shutdown.go
+++ b/config/graceful_shutdown.go
@@ -107,7 +107,7 @@ func BeforeShutdown() {
func destroyAllRegistries() {
logger.Info("Graceful shutdown --- Destroy all registriesConfig. ")
- registryProtocol := extension.GetProtocol(constant.REGISTRY_KEY)
+ registryProtocol := extension.GetProtocol(constant.RegistryKey)
registryProtocol.Destroy()
}
diff --git a/config/metadata_report_config.go b/config/metadata_report_config.go
index 6373871..86bb034 100644
--- a/config/metadata_report_config.go
+++ b/config/metadata_report_config.go
@@ -60,7 +60,7 @@ func (mc *MetadataReportConfig) ToUrl() (*common.URL, error) {
common.WithPassword(mc.Password),
common.WithLocation(mc.Address),
common.WithProtocol(mc.Protocol),
- common.WithParamsValue(constant.METADATATYPE_KEY, mc.metadataType),
+ common.WithParamsValue(constant.MetadataTypeKey, mc.metadataType),
)
if err != nil || len(res.Protocol) == 0 {
return nil, perrors.New("Invalid MetadataReport Config.")
@@ -87,13 +87,13 @@ func (mc *MetadataReportConfig) StartMetadataReport() error {
}
func publishServiceDefinition(url *common.URL) {
- localService, err := extension.GetLocalMetadataService(constant.DEFAULT_Key)
+ localService, err := extension.GetLocalMetadataService(constant.DefaultKey)
if err != nil {
logger.Warnf("get local metadata service failed, please check if you have imported _ \"dubbo.apache.org/dubbo-go/v3/metadata/service/local\"")
return
}
localService.PublishServiceDefinition(url)
- if url.GetParam(constant.METADATATYPE_KEY, "") != constant.REMOTE_METADATA_STORAGE_TYPE {
+ if url.GetParam(constant.MetadataTypeKey, "") != constant.RemoteMetadataStorageType {
return
}
if remoteMetadataService, err := extension.GetRemoteMetadataService(); err == nil && remoteMetadataService != nil {
@@ -105,12 +105,12 @@ func publishServiceDefinition(url *common.URL) {
// selectMetadataServiceExportedURL get already be exported url
func selectMetadataServiceExportedURL() *common.URL {
var selectedUrl *common.URL
- metaDataService, err := extension.GetLocalMetadataService(constant.DEFAULT_Key)
+ metaDataService, err := extension.GetLocalMetadataService(constant.DefaultKey)
if err != nil {
logger.Warnf("get metadata service exporter failed, pls check if you import _ \"dubbo.apache.org/dubbo-go/v3/metadata/service/local\"")
return nil
}
- urlList, err := metaDataService.GetExportedURLs(constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE)
+ urlList, err := metaDataService.GetExportedURLs(constant.AnyValue, constant.AnyValue, constant.AnyValue, constant.AnyValue)
if err != nil {
panic(err)
}
diff --git a/config/method_config.go b/config/method_config.go
index 7c5ba9a..4e45987 100644
--- a/config/method_config.go
+++ b/config/method_config.go
@@ -45,10 +45,10 @@ type MethodConfig struct {
// nolint
func (mc *MethodConfig) Prefix() string {
if len(mc.InterfaceId) != 0 {
- return constant.DUBBO + "." + mc.InterfaceName + "." + mc.InterfaceId + "." + mc.Name + "."
+ return constant.Dubbo + "." + mc.InterfaceName + "." + mc.InterfaceId + "." + mc.Name + "."
}
- return constant.DUBBO + "." + mc.InterfaceName + "." + mc.Name + "."
+ return constant.Dubbo + "." + mc.InterfaceName + "." + mc.Name + "."
}
func (mc *MethodConfig) Init() error {
diff --git a/config/reference_config.go b/config/reference_config.go
index dea00fc..85a3bca 100644
--- a/config/reference_config.go
+++ b/config/reference_config.go
@@ -106,8 +106,8 @@ func (rc *ReferenceConfig) Refer(srv interface{}) {
common.WithPath(rc.InterfaceName),
common.WithProtocol(rc.Protocol),
common.WithParams(rc.getURLMap()),
- common.WithParamsValue(constant.BEAN_NAME_KEY, rc.id),
- common.WithParamsValue(constant.METADATATYPE_KEY, rc.metaDataType),
+ common.WithParamsValue(constant.BeanNameKey, rc.id),
+ common.WithParamsValue(constant.MetadataTypeKey, rc.metaDataType),
)
SetConsumerServiceByInterfaceName(rc.InterfaceName, srv)
if rc.ForceTag {
@@ -129,7 +129,7 @@ func (rc *ReferenceConfig) Refer(srv interface{}) {
if err != nil {
panic(fmt.Sprintf("url configuration error, please check your configuration, user specified URL %v refer error, error message is %v ", urlStr, err.Error()))
}
- if serviceURL.Protocol == constant.REGISTRY_PROTOCOL { // URL stands for a registry protocol
+ if serviceURL.Protocol == constant.RegistryProtocol { // URL stands for a registry protocol
serviceURL.SubURL = cfgURL
rc.urls = append(rc.urls, serviceURL)
} else { // URL stands for a direct address
@@ -156,18 +156,18 @@ func (rc *ReferenceConfig) Refer(srv interface{}) {
)
invokers := make([]protocol.Invoker, len(rc.urls))
for i, u := range rc.urls {
- if u.Protocol == constant.SERVICE_REGISTRY_PROTOCOL {
+ if u.Protocol == constant.ServiceRegistryProtocol {
invoker = extension.GetProtocol("registry").Refer(u)
} else {
invoker = extension.GetProtocol(u.Protocol).Refer(u)
}
if rc.URL != "" {
- invoker = protocolwrapper.BuildInvokerChain(invoker, constant.REFERENCE_FILTER_KEY)
+ invoker = protocolwrapper.BuildInvokerChain(invoker, constant.ReferenceFilterKey)
}
invokers[i] = invoker
- if u.Protocol == constant.REGISTRY_PROTOCOL {
+ if u.Protocol == constant.RegistryProtocol {
regURL = u
}
}
@@ -178,7 +178,7 @@ func (rc *ReferenceConfig) Refer(srv interface{}) {
if rc.URL != "" {
hitClu := constant.ClusterKeyFailover
if u := rc.invoker.GetURL(); u != nil {
- hitClu = u.GetParam(constant.CLUSTER_KEY, constant.ClusterKeyZoneAware)
+ hitClu = u.GetParam(constant.ClusterKey, constant.ClusterKeyZoneAware)
}
rc.invoker = extension.GetCluster(hitClu).Join(static.NewDirectory(invokers))
}
@@ -191,7 +191,7 @@ func (rc *ReferenceConfig) Refer(srv interface{}) {
// not a registry url, must be direct invoke.
hitClu = constant.ClusterKeyFailover
if u := invokers[0].GetURL(); u != nil {
- hitClu = u.GetParam(constant.CLUSTER_KEY, constant.ClusterKeyZoneAware)
+ hitClu = u.GetParam(constant.ClusterKey, constant.ClusterKeyZoneAware)
}
}
rc.invoker = extension.GetCluster(hitClu).Join(static.NewDirectory(invokers))
@@ -230,50 +230,50 @@ func (rc *ReferenceConfig) getURLMap() url.Values {
for k, v := range rc.Params {
urlMap.Set(k, v)
}
- urlMap.Set(constant.INTERFACE_KEY, rc.InterfaceName)
- urlMap.Set(constant.TIMESTAMP_KEY, strconv.FormatInt(time.Now().Unix(), 10))
- urlMap.Set(constant.CLUSTER_KEY, rc.Cluster)
- urlMap.Set(constant.LOADBALANCE_KEY, rc.Loadbalance)
- urlMap.Set(constant.RETRIES_KEY, rc.Retries)
- urlMap.Set(constant.GROUP_KEY, rc.Group)
- urlMap.Set(constant.VERSION_KEY, rc.Version)
- urlMap.Set(constant.GENERIC_KEY, rc.Generic)
- urlMap.Set(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER))
- urlMap.Set(constant.PROVIDED_BY, rc.ProvidedBy)
- urlMap.Set(constant.SERIALIZATION_KEY, rc.Serialization)
-
- urlMap.Set(constant.RELEASE_KEY, "dubbo-golang-"+constant.Version)
- urlMap.Set(constant.SIDE_KEY, (common.RoleType(common.CONSUMER)).Role())
+ urlMap.Set(constant.InterfaceKey, rc.InterfaceName)
+ urlMap.Set(constant.TimestampKey, strconv.FormatInt(time.Now().Unix(), 10))
+ urlMap.Set(constant.ClusterKey, rc.Cluster)
+ urlMap.Set(constant.LoadbalanceKey, rc.Loadbalance)
+ urlMap.Set(constant.RetriesKey, rc.Retries)
+ urlMap.Set(constant.GroupKey, rc.Group)
+ urlMap.Set(constant.VersionKey, rc.Version)
+ urlMap.Set(constant.GenericKey, rc.Generic)
+ urlMap.Set(constant.RoleKey, strconv.Itoa(common.CONSUMER))
+ urlMap.Set(constant.ProvidedBy, rc.ProvidedBy)
+ urlMap.Set(constant.SerializationKey, rc.Serialization)
+
+ urlMap.Set(constant.ReleaseKey, "dubbo-golang-"+constant.Version)
+ urlMap.Set(constant.SideKey, (common.RoleType(common.CONSUMER)).Role())
if len(rc.RequestTimeout) != 0 {
- urlMap.Set(constant.TIMEOUT_KEY, rc.RequestTimeout)
+ urlMap.Set(constant.TimeoutKey, rc.RequestTimeout)
}
// getty invoke async or sync
- urlMap.Set(constant.ASYNC_KEY, strconv.FormatBool(rc.Async))
- urlMap.Set(constant.STICKY_KEY, strconv.FormatBool(rc.Sticky))
+ urlMap.Set(constant.AsyncKey, strconv.FormatBool(rc.Async))
+ urlMap.Set(constant.StickyKey, strconv.FormatBool(rc.Sticky))
// applicationConfig info
- urlMap.Set(constant.APPLICATION_KEY, rc.rootConfig.Application.Name)
- urlMap.Set(constant.ORGANIZATION_KEY, rc.rootConfig.Application.Organization)
- urlMap.Set(constant.NAME_KEY, rc.rootConfig.Application.Name)
- urlMap.Set(constant.MODULE_KEY, rc.rootConfig.Application.Module)
- urlMap.Set(constant.APP_VERSION_KEY, rc.rootConfig.Application.Version)
- urlMap.Set(constant.OWNER_KEY, rc.rootConfig.Application.Owner)
- urlMap.Set(constant.ENVIRONMENT_KEY, rc.rootConfig.Application.Environment)
+ urlMap.Set(constant.ApplicationKey, rc.rootConfig.Application.Name)
+ urlMap.Set(constant.OrganizationKey, rc.rootConfig.Application.Organization)
+ urlMap.Set(constant.NameKey, rc.rootConfig.Application.Name)
+ urlMap.Set(constant.ModuleKey, rc.rootConfig.Application.Module)
+ urlMap.Set(constant.AppVersionKey, rc.rootConfig.Application.Version)
+ urlMap.Set(constant.OwnerKey, rc.rootConfig.Application.Owner)
+ urlMap.Set(constant.EnvironmentKey, rc.rootConfig.Application.Environment)
// filter
- defaultReferenceFilter := constant.DEFAULT_REFERENCE_FILTERS
+ defaultReferenceFilter := constant.DefaultReferenceFilters
if rc.Generic != "" {
- defaultReferenceFilter = constant.GENERIC_REFERENCE_FILTERS + "," + defaultReferenceFilter
+ defaultReferenceFilter = constant.GenericReferenceFilters + "," + defaultReferenceFilter
}
- urlMap.Set(constant.REFERENCE_FILTER_KEY, mergeValue(rc.rootConfig.Consumer.Filter, "", defaultReferenceFilter))
+ urlMap.Set(constant.ReferenceFilterKey, mergeValue(rc.rootConfig.Consumer.Filter, "", defaultReferenceFilter))
for _, v := range rc.Methods {
- urlMap.Set("methods."+v.Name+"."+constant.LOADBALANCE_KEY, v.LoadBalance)
- urlMap.Set("methods."+v.Name+"."+constant.RETRIES_KEY, v.Retries)
- urlMap.Set("methods."+v.Name+"."+constant.STICKY_KEY, strconv.FormatBool(v.Sticky))
+ urlMap.Set("methods."+v.Name+"."+constant.LoadbalanceKey, v.LoadBalance)
+ urlMap.Set("methods."+v.Name+"."+constant.RetriesKey, v.Retries)
+ urlMap.Set("methods."+v.Name+"."+constant.StickyKey, strconv.FormatBool(v.Sticky))
if len(v.RequestTimeout) != 0 {
- urlMap.Set("methods."+v.Name+"."+constant.TIMEOUT_KEY, v.RequestTimeout)
+ urlMap.Set("methods."+v.Name+"."+constant.TimeoutKey, v.RequestTimeout)
}
}
diff --git a/config/registry_config.go b/config/registry_config.go
index 51e3539..17b0d2f 100644
--- a/config/registry_config.go
+++ b/config/registry_config.go
@@ -73,16 +73,16 @@ func (c *RegistryConfig) Init() error {
func (c *RegistryConfig) getUrlMap(roleType common.RoleType) url.Values {
urlMap := url.Values{}
- urlMap.Set(constant.GROUP_KEY, c.Group)
- urlMap.Set(constant.ROLE_KEY, strconv.Itoa(int(roleType)))
- urlMap.Set(constant.REGISTRY_KEY, c.Protocol)
- urlMap.Set(constant.REGISTRY_TIMEOUT_KEY, c.Timeout)
+ urlMap.Set(constant.GroupKey, c.Group)
+ urlMap.Set(constant.RoleKey, strconv.Itoa(int(roleType)))
+ urlMap.Set(constant.RegistryKey, c.Protocol)
+ urlMap.Set(constant.RegistryTimeoutKey, c.Timeout)
// multi registry invoker weight label for load balance
- urlMap.Set(constant.REGISTRY_KEY+"."+constant.REGISTRY_LABEL_KEY, strconv.FormatBool(true))
- urlMap.Set(constant.REGISTRY_KEY+"."+constant.PREFERRED_KEY, strconv.FormatBool(c.Preferred))
- urlMap.Set(constant.REGISTRY_KEY+"."+constant.ZONE_KEY, c.Zone)
- urlMap.Set(constant.REGISTRY_KEY+"."+constant.WEIGHT_KEY, strconv.FormatInt(c.Weight, 10))
- urlMap.Set(constant.REGISTRY_TTL_KEY, c.TTL)
+ urlMap.Set(constant.RegistryKey+"."+constant.RegistryLabelKey, strconv.FormatBool(true))
+ urlMap.Set(constant.RegistryKey+"."+constant.PreferredKey, strconv.FormatBool(c.Preferred))
+ urlMap.Set(constant.RegistryKey+"."+constant.ZoneKey, c.Zone)
+ urlMap.Set(constant.RegistryKey+"."+constant.WeightKey, strconv.FormatInt(c.Weight, 10))
+ urlMap.Set(constant.RegistryTTLKey, c.TTL)
for k, v := range c.Params {
urlMap.Set(k, v)
}
@@ -110,8 +110,8 @@ func (c *RegistryConfig) GetInstance(roleType common.RoleType) (registry.Registr
return nil, err
}
// if the protocol == registry, set protocol the registry value in url.params
- if u.Protocol == constant.REGISTRY_PROTOCOL {
- u.Protocol = u.GetParam(constant.REGISTRY_KEY, "")
+ if u.Protocol == constant.RegistryProtocol {
+ u.Protocol = u.GetParam(constant.RegistryKey, "")
}
return extension.GetRegistry(u.Protocol, u)
}
@@ -121,16 +121,16 @@ func (c *RegistryConfig) toURL(roleType common.RoleType) (*common.URL, error) {
var registryURLProtocol string
if c.RegistryType == "service" {
// service discovery protocol
- registryURLProtocol = constant.SERVICE_REGISTRY_PROTOCOL
+ registryURLProtocol = constant.ServiceRegistryProtocol
} else {
- registryURLProtocol = constant.REGISTRY_PROTOCOL
+ registryURLProtocol = constant.RegistryProtocol
}
return common.NewURL(registryURLProtocol+"://"+address,
common.WithParams(c.getUrlMap(roleType)),
- common.WithParamsValue(constant.SIMPLIFIED_KEY, strconv.FormatBool(c.Simplified)),
- common.WithParamsValue(constant.REGISTRY_KEY, c.Protocol),
- common.WithParamsValue(constant.GROUP_KEY, c.Group),
- common.WithParamsValue(constant.NAMESPACE_KEY, c.Namespace),
+ common.WithParamsValue(constant.SimplifiedKey, strconv.FormatBool(c.Simplified)),
+ common.WithParamsValue(constant.RegistryKey, c.Protocol),
+ common.WithParamsValue(constant.GroupKey, c.Group),
+ common.WithParamsValue(constant.NamespaceKey, c.Namespace),
common.WithUsername(c.Username),
common.WithPassword(c.Password),
common.WithLocation(c.Address),
diff --git a/config/remote_config.go b/config/remote_config.go
index 444db6e..a570bec 100644
--- a/config/remote_config.go
+++ b/config/remote_config.go
@@ -90,9 +90,9 @@ func (rc *RemoteConfig) ToURL() (*common.URL, error) {
// getUrlMap get url map
func (rc *RemoteConfig) getUrlMap() url.Values {
urlMap := url.Values{}
- urlMap.Set(constant.CONFIG_USERNAME_KEY, rc.Username)
- urlMap.Set(constant.CONFIG_PASSWORD_KEY, rc.Password)
- urlMap.Set(constant.CONFIG_TIMEOUT_KEY, rc.Timeout)
+ urlMap.Set(constant.ConfigUsernameKey, rc.Username)
+ urlMap.Set(constant.ConfigPasswordKey, rc.Password)
+ urlMap.Set(constant.ConfigTimeoutKey, rc.Timeout)
for key, val := range rc.Params {
urlMap.Set(key, val)
diff --git a/config/root_config.go b/config/root_config.go
index c1f185c..114d44f 100644
--- a/config/root_config.go
+++ b/config/root_config.go
@@ -86,7 +86,7 @@ func SetRootConfig(r RootConfig) {
// Prefix dubbo
func (RootConfig) Prefix() string {
- return constant.DUBBO
+ return constant.Dubbo
}
func GetRootConfig() *RootConfig {
@@ -153,7 +153,7 @@ func (rc *RootConfig) Init() error {
if len(protocols) <= 0 {
protocol := &ProtocolConfig{}
protocols = make(map[string]*ProtocolConfig, 1)
- protocols[constant.DUBBO] = protocol
+ protocols[constant.Dubbo] = protocol
rc.Protocols = protocols
}
for _, protocol := range protocols {
@@ -308,7 +308,7 @@ func (rb *RootConfigBuilder) Build() *RootConfig {
}
func exportMetadataService() {
- ms, err := extension.GetLocalMetadataService(constant.DEFAULT_Key)
+ ms, err := extension.GetLocalMetadataService(constant.DefaultKey)
if err != nil {
logger.Warnf("could not init metadata service", err)
return
@@ -325,7 +325,7 @@ func exportMetadataService() {
// So using sync.Once will result in dead lock
exporting.Store(true)
- expt := extension.GetMetadataServiceExporter(constant.DEFAULT_Key, ms)
+ expt := extension.GetMetadataServiceExporter(constant.DefaultKey, ms)
if expt == nil {
logger.Warnf("get metadata service exporter failed, pls check if you import _ \"dubbo.apache.org/dubbo-go/v3/metadata/service/exporter/configurable\"")
return
diff --git a/config/service_config.go b/config/service_config.go
index da08a2a..fac86ca 100644
--- a/config/service_config.go
+++ b/config/service_config.go
@@ -192,11 +192,11 @@ func (svc *ServiceConfig) Export() error {
common.WithIp(proto.Ip),
common.WithPort(port),
common.WithParams(urlMap),
- common.WithParamsValue(constant.BEAN_NAME_KEY, svc.id),
- //common.WithParamsValue(constant.SSL_ENABLED_KEY, strconv.FormatBool(config.GetSslEnabled())),
+ common.WithParamsValue(constant.BeanNameKey, svc.id),
+ //common.WithParamsValue(constant.SslEnabledKey, strconv.FormatBool(config.GetSslEnabled())),
common.WithMethods(strings.Split(methods, ",")),
common.WithToken(svc.Token),
- common.WithParamsValue(constant.METADATATYPE_KEY, svc.metadataType),
+ common.WithParamsValue(constant.MetadataTypeKey, svc.metadataType),
)
if len(svc.Tag) > 0 {
ivkURL.AddParam(constant.Tagkey, svc.Tag)
@@ -205,7 +205,7 @@ func (svc *ServiceConfig) Export() error {
// post process the URL to be exported
svc.postProcessConfig(ivkURL)
// config post processor may set "export" to false
- if !ivkURL.GetParamBool(constant.EXPORT_KEY, true) {
+ if !ivkURL.GetParamBool(constant.ExportKey, true) {
return nil
}
@@ -227,7 +227,7 @@ func (svc *ServiceConfig) Export() error {
svc.exporters = append(svc.exporters, exporter)
}
} else {
- if ivkURL.GetParam(constant.INTERFACE_KEY, "") == constant.METADATA_SERVICE_NAME {
+ if ivkURL.GetParam(constant.InterfaceKey, "") == constant.MetadataServiceName {
ms, err := extension.GetLocalMetadataService("")
if err != nil {
logger.Warnf("export org.apache.dubbo.metadata.MetadataService failed beacause of %s ! pls check if you import _ \"dubbo.apache.org/dubbo-go/v3/metadata/service/local\"", err)
@@ -331,69 +331,69 @@ func (svc *ServiceConfig) getUrlMap() url.Values {
for k, v := range svc.Params {
urlMap.Set(k, v)
}
- urlMap.Set(constant.INTERFACE_KEY, svc.Interface)
- urlMap.Set(constant.TIMESTAMP_KEY, strconv.FormatInt(time.Now().Unix(), 10))
- urlMap.Set(constant.CLUSTER_KEY, svc.Cluster)
- urlMap.Set(constant.LOADBALANCE_KEY, svc.Loadbalance)
- urlMap.Set(constant.WARMUP_KEY, svc.Warmup)
- urlMap.Set(constant.RETRIES_KEY, svc.Retries)
- urlMap.Set(constant.GROUP_KEY, svc.Group)
- urlMap.Set(constant.VERSION_KEY, svc.Version)
- urlMap.Set(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))
- urlMap.Set(constant.RELEASE_KEY, "dubbo-golang-"+constant.Version)
- urlMap.Set(constant.SIDE_KEY, (common.RoleType(common.PROVIDER)).Role())
- urlMap.Set(constant.MESSAGE_SIZE_KEY, strconv.Itoa(svc.GrpcMaxMessageSize))
+ urlMap.Set(constant.InterfaceKey, svc.Interface)
+ urlMap.Set(constant.TimestampKey, strconv.FormatInt(time.Now().Unix(), 10))
+ urlMap.Set(constant.ClusterKey, svc.Cluster)
+ urlMap.Set(constant.LoadbalanceKey, svc.Loadbalance)
+ urlMap.Set(constant.WarmupKey, svc.Warmup)
+ urlMap.Set(constant.RetriesKey, svc.Retries)
+ urlMap.Set(constant.GroupKey, svc.Group)
+ urlMap.Set(constant.VersionKey, svc.Version)
+ urlMap.Set(constant.RoleKey, strconv.Itoa(common.PROVIDER))
+ urlMap.Set(constant.ReleaseKey, "dubbo-golang-"+constant.Version)
+ urlMap.Set(constant.SideKey, (common.RoleType(common.PROVIDER)).Role())
+ urlMap.Set(constant.MessageSizeKey, strconv.Itoa(svc.GrpcMaxMessageSize))
// todo: move
- urlMap.Set(constant.SERIALIZATION_KEY, svc.Serialization)
+ urlMap.Set(constant.SerializationKey, svc.Serialization)
// application config info
ac := GetApplicationConfig()
- urlMap.Set(constant.APPLICATION_KEY, ac.Name)
- urlMap.Set(constant.ORGANIZATION_KEY, ac.Organization)
- urlMap.Set(constant.NAME_KEY, ac.Name)
- urlMap.Set(constant.MODULE_KEY, ac.Module)
- urlMap.Set(constant.APP_VERSION_KEY, ac.Version)
- urlMap.Set(constant.OWNER_KEY, ac.Owner)
- urlMap.Set(constant.ENVIRONMENT_KEY, ac.Environment)
+ urlMap.Set(constant.ApplicationKey, ac.Name)
+ urlMap.Set(constant.OrganizationKey, ac.Organization)
+ urlMap.Set(constant.NameKey, ac.Name)
+ urlMap.Set(constant.ModuleKey, ac.Module)
+ urlMap.Set(constant.AppVersionKey, ac.Version)
+ urlMap.Set(constant.OwnerKey, ac.Owner)
+ urlMap.Set(constant.EnvironmentKey, ac.Environment)
// filter
if svc.Filter == "" {
- urlMap.Set(constant.SERVICE_FILTER_KEY, constant.DEFAULT_SERVICE_FILTERS)
+ urlMap.Set(constant.ServiceFilterKey, constant.DefaultServiceFilters)
} else {
- urlMap.Set(constant.SERVICE_FILTER_KEY, svc.Filter)
+ urlMap.Set(constant.ServiceFilterKey, svc.Filter)
}
// filter special config
urlMap.Set(constant.AccessLogFilterKey, svc.AccessLog)
// tps limiter
- urlMap.Set(constant.TPS_LIMIT_STRATEGY_KEY, svc.TpsLimitStrategy)
- urlMap.Set(constant.TPS_LIMIT_INTERVAL_KEY, svc.TpsLimitInterval)
- urlMap.Set(constant.TPS_LIMIT_RATE_KEY, svc.TpsLimitRate)
- urlMap.Set(constant.TPS_LIMITER_KEY, svc.TpsLimiter)
- urlMap.Set(constant.TPS_REJECTED_EXECUTION_HANDLER_KEY, svc.TpsLimitRejectedHandler)
+ urlMap.Set(constant.TPSLimitStrategyKey, svc.TpsLimitStrategy)
+ urlMap.Set(constant.TPSLimitIntervalKey, svc.TpsLimitInterval)
+ urlMap.Set(constant.TPSLimitRateKey, svc.TpsLimitRate)
+ urlMap.Set(constant.TPSLimiterKey, svc.TpsLimiter)
+ urlMap.Set(constant.TPSRejectedExecutionHandlerKey, svc.TpsLimitRejectedHandler)
// execute limit filter
- urlMap.Set(constant.EXECUTE_LIMIT_KEY, svc.ExecuteLimit)
- urlMap.Set(constant.EXECUTE_REJECTED_EXECUTION_HANDLER_KEY, svc.ExecuteLimitRejectedHandler)
+ urlMap.Set(constant.ExecuteLimitKey, svc.ExecuteLimit)
+ urlMap.Set(constant.ExecuteRejectedExecutionHandlerKey, svc.ExecuteLimitRejectedHandler)
// auth filter
- urlMap.Set(constant.SERVICE_AUTH_KEY, svc.Auth)
- urlMap.Set(constant.PARAMETER_SIGNATURE_ENABLE_KEY, svc.ParamSign)
+ urlMap.Set(constant.ServiceAuthKey, svc.Auth)
+ urlMap.Set(constant.ParameterSignatureEnableKey, svc.ParamSign)
// whether to export or not
- urlMap.Set(constant.EXPORT_KEY, strconv.FormatBool(svc.export))
+ urlMap.Set(constant.ExportKey, strconv.FormatBool(svc.export))
for _, v := range svc.Methods {
prefix := "methods." + v.Name + "."
- urlMap.Set(prefix+constant.LOADBALANCE_KEY, v.LoadBalance)
- urlMap.Set(prefix+constant.RETRIES_KEY, v.Retries)
- urlMap.Set(prefix+constant.WEIGHT_KEY, strconv.FormatInt(v.Weight, 10))
+ urlMap.Set(prefix+constant.LoadbalanceKey, v.LoadBalance)
+ urlMap.Set(prefix+constant.RetriesKey, v.Retries)
+ urlMap.Set(prefix+constant.WeightKey, strconv.FormatInt(v.Weight, 10))
- urlMap.Set(prefix+constant.TPS_LIMIT_STRATEGY_KEY, v.TpsLimitStrategy)
- urlMap.Set(prefix+constant.TPS_LIMIT_INTERVAL_KEY, v.TpsLimitInterval)
- urlMap.Set(prefix+constant.TPS_LIMIT_RATE_KEY, v.TpsLimitRate)
+ urlMap.Set(prefix+constant.TPSLimitStrategyKey, v.TpsLimitStrategy)
+ urlMap.Set(prefix+constant.TPSLimitIntervalKey, v.TpsLimitInterval)
+ urlMap.Set(prefix+constant.TPSLimitRateKey, v.TpsLimitRate)
- urlMap.Set(constant.EXECUTE_LIMIT_KEY, v.ExecuteLimit)
- urlMap.Set(constant.EXECUTE_REJECTED_EXECUTION_HANDLER_KEY, v.ExecuteLimitRejectedHandler)
+ urlMap.Set(constant.ExecuteLimitKey, v.ExecuteLimit)
+ urlMap.Set(constant.ExecuteRejectedExecutionHandlerKey, v.ExecuteLimitRejectedHandler)
}
return urlMap
diff --git a/config_center/apollo/impl.go b/config_center/apollo/impl.go
index d6b32c3..d6ca2c3 100644
--- a/config_center/apollo/impl.go
+++ b/config_center/apollo/impl.go
@@ -58,13 +58,13 @@ func newApolloConfiguration(url *common.URL) (*apolloConfiguration, error) {
url: url,
}
c.appConf = &config.AppConfig{
- AppID: url.GetParam(constant.CONFIG_APP_ID_KEY, ""),
- Cluster: url.GetParam(constant.CONFIG_CLUSTER_KEY, ""),
- NamespaceName: url.GetParam(constant.CONFIG_NAMESPACE_KEY, cc.DefaultGroup),
+ AppID: url.GetParam(constant.ConfigAppIDKey, ""),
+ Cluster: url.GetParam(constant.ConfigClusterKey, ""),
+ NamespaceName: url.GetParam(constant.ConfigNamespaceKey, cc.DefaultGroup),
IP: c.getAddressWithProtocolPrefix(url),
- Secret: url.GetParam(constant.CONFIG_SECRET_KEY, ""),
- IsBackupConfig: url.GetParamBool(constant.CONFIG_BACKUP_CONFIG_KEY, true),
- BackupConfigPath: url.GetParam(constant.CONFIG_BACKUP_CONFIG_PATH_KEY, ""),
+ Secret: url.GetParam(constant.ConfigSecretKey, ""),
+ IsBackupConfig: url.GetParamBool(constant.ConfigBackupConfigKey, true),
+ BackupConfigPath: url.GetParam(constant.ConfigBackupConfigPathKey, ""),
}
agollo.InitCustomConfig(func() (*config.AppConfig, error) {
return c.appConf, nil
diff --git a/config_center/configurator/mock.go b/config_center/configurator/mock.go
index 711ec4c..b5e0629 100644
--- a/config_center/configurator/mock.go
+++ b/config_center/configurator/mock.go
@@ -37,9 +37,9 @@ func (c *mockConfigurator) GetUrl() *common.URL {
return c.configuratorUrl
}
-// Configure sets up param CLUSTER_KEY and cluster for url
+// Configure sets up param ClusterKey and cluster for url
func (c *mockConfigurator) Configure(url *common.URL) {
- if cluster := c.GetUrl().GetParam(constant.CLUSTER_KEY, ""); cluster != "" {
- url.SetParam(constant.CLUSTER_KEY, cluster)
+ if cluster := c.GetUrl().GetParam(constant.ClusterKey, ""); cluster != "" {
+ url.SetParam(constant.ClusterKey, cluster)
}
}
diff --git a/config_center/configurator/override.go b/config_center/configurator/override.go
index d8e97c8..8c73b66 100644
--- a/config_center/configurator/override.go
+++ b/config_center/configurator/override.go
@@ -50,15 +50,15 @@ func (c *overrideConfigurator) GetUrl() *common.URL {
func (c *overrideConfigurator) Configure(url *common.URL) {
// remove configuratorUrl some param that can not be configured
- if c.configuratorUrl.GetParam(constant.ENABLED_KEY, "true") == "false" || len(c.configuratorUrl.Location) == 0 {
+ if c.configuratorUrl.GetParam(constant.EnabledKey, "true") == "false" || len(c.configuratorUrl.Location) == 0 {
return
}
// branch for version 2.7.x
- apiVersion := c.configuratorUrl.GetParam(constant.CONFIG_VERSION_KEY, "")
+ apiVersion := c.configuratorUrl.GetParam(constant.ConfigVersionKey, "")
if len(apiVersion) != 0 {
- currentSide := url.GetParam(constant.SIDE_KEY, "")
- configuratorSide := c.configuratorUrl.GetParam(constant.SIDE_KEY, "")
+ currentSide := url.GetParam(constant.SideKey, "")
+ configuratorSide := c.configuratorUrl.GetParam(constant.SideKey, "")
if currentSide == configuratorSide && common.DubboRole[common.CONSUMER] == currentSide && c.configuratorUrl.Port == "0" {
localIP := common.GetLocalIp()
c.configureIfMatch(localIP, url)
@@ -72,25 +72,25 @@ func (c *overrideConfigurator) Configure(url *common.URL) {
}
func (c *overrideConfigurator) configureIfMatchInternal(url *common.URL) {
- configApp := c.configuratorUrl.GetParam(constant.APPLICATION_KEY, c.configuratorUrl.Username)
- currentApp := url.GetParam(constant.APPLICATION_KEY, url.Username)
- if len(configApp) == 0 || constant.ANY_VALUE == configApp || configApp == currentApp {
+ configApp := c.configuratorUrl.GetParam(constant.ApplicationKey, c.configuratorUrl.Username)
+ currentApp := url.GetParam(constant.ApplicationKey, url.Username)
+ if len(configApp) == 0 || constant.AnyValue == configApp || configApp == currentApp {
conditionKeys := gxset.NewSet()
- conditionKeys.Add(constant.CATEGORY_KEY)
- conditionKeys.Add(constant.CHECK_KEY)
- conditionKeys.Add(constant.ENABLED_KEY)
- conditionKeys.Add(constant.GROUP_KEY)
- conditionKeys.Add(constant.VERSION_KEY)
- conditionKeys.Add(constant.APPLICATION_KEY)
- conditionKeys.Add(constant.SIDE_KEY)
- conditionKeys.Add(constant.CONFIG_VERSION_KEY)
- conditionKeys.Add(constant.COMPATIBLE_CONFIG_KEY)
+ conditionKeys.Add(constant.CategoryKey)
+ conditionKeys.Add(constant.CheckKey)
+ conditionKeys.Add(constant.EnabledKey)
+ conditionKeys.Add(constant.GroupKey)
+ conditionKeys.Add(constant.VersionKey)
+ conditionKeys.Add(constant.ApplicationKey)
+ conditionKeys.Add(constant.SideKey)
+ conditionKeys.Add(constant.ConfigVersionKey)
+ conditionKeys.Add(constant.CompatibleConfigKey)
returnUrl := false
c.configuratorUrl.RangeParams(func(k, _ string) bool {
value := c.configuratorUrl.GetParam(k, "")
- if strings.HasPrefix(k, "~") || k == constant.APPLICATION_KEY || k == constant.SIDE_KEY {
+ if strings.HasPrefix(k, "~") || k == constant.ApplicationKey || k == constant.SideKey {
conditionKeys.Add(k)
- if len(value) != 0 && value != constant.ANY_VALUE && value != url.GetParam(strings.TrimPrefix(k, "~"), "") {
+ if len(value) != 0 && value != constant.AnyValue && value != url.GetParam(strings.TrimPrefix(k, "~"), "") {
returnUrl = true
return false
}
@@ -107,9 +107,9 @@ func (c *overrideConfigurator) configureIfMatchInternal(url *common.URL) {
// configureIfMatch translate from java, compatible rules in java
func (c *overrideConfigurator) configureIfMatch(host string, url *common.URL) {
- if constant.ANYHOST_VALUE == c.configuratorUrl.Ip || host == c.configuratorUrl.Ip {
- providers := c.configuratorUrl.GetParam(constant.OVERRIDE_PROVIDERS_KEY, "")
- if len(providers) == 0 || strings.Contains(providers, url.Location) || strings.Contains(providers, constant.ANYHOST_VALUE) {
+ if constant.AnyhostValue == c.configuratorUrl.Ip || host == c.configuratorUrl.Ip {
+ providers := c.configuratorUrl.GetParam(constant.OverrideProvidersKey, "")
+ if len(providers) == 0 || strings.Contains(providers, url.Location) || strings.Contains(providers, constant.AnyhostValue) {
c.configureIfMatchInternal(url)
}
}
@@ -125,11 +125,11 @@ func (c *overrideConfigurator) configureDeprecated(url *common.URL) {
// override url don't have a port, means the ip override url specify is a consumer address or 0.0.0.0
// 1.If it is a consumer ip address, the intention is to control a specific consumer instance, it must takes effect at the consumer side, any provider received this override url should ignore;
// 2.If the ip is 0.0.0.0, this override url can be used on consumer, and also can be used on provider
- if url.GetParam(constant.SIDE_KEY, "") == common.DubboRole[common.CONSUMER] {
+ if url.GetParam(constant.SideKey, "") == common.DubboRole[common.CONSUMER] {
localIP := common.GetLocalIp()
c.configureIfMatch(localIP, url)
} else {
- c.configureIfMatch(constant.ANYHOST_VALUE, url)
+ c.configureIfMatch(constant.AnyhostValue, url)
}
}
}
diff --git a/config_center/configurator/override_test.go b/config_center/configurator/override_test.go
index 1175985..0537752 100644
--- a/config_center/configurator/override_test.go
+++ b/config_center/configurator/override_test.go
@@ -46,7 +46,7 @@ func TestConfigureVersion2p6(t *testing.T) {
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=642 [...]
assert.NoError(t, err)
configurator.Configure(providerUrl)
- assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, ""))
+ assert.Equal(t, failfast, providerUrl.GetParam(constant.ClusterKey, ""))
}
func TestConfigureVersionOverrideAddr(t *testing.T) {
@@ -58,7 +58,7 @@ func TestConfigureVersionOverrideAddr(t *testing.T) {
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=642 [...]
assert.NoError(t, err)
configurator.Configure(providerUrl)
- assert.Equal(t, failover, providerUrl.GetParam(constant.CLUSTER_KEY, ""))
+ assert.Equal(t, failover, providerUrl.GetParam(constant.ClusterKey, ""))
}
func TestConfigureVersion2p6WithIp(t *testing.T) {
@@ -70,7 +70,7 @@ func TestConfigureVersion2p6WithIp(t *testing.T) {
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=642 [...]
assert.NoError(t, err)
configurator.Configure(providerUrl)
- assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, ""))
+ assert.Equal(t, failfast, providerUrl.GetParam(constant.ClusterKey, ""))
}
func TestConfigureVersion2p7(t *testing.T) {
@@ -81,5 +81,5 @@ func TestConfigureVersion2p7(t *testing.T) {
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=642 [...]
assert.NoError(t, err)
configurator.Configure(providerUrl)
- assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, ""))
+ assert.Equal(t, failfast, providerUrl.GetParam(constant.ClusterKey, ""))
}
diff --git a/config_center/file/factory.go b/config_center/file/factory.go
index 2fc48b2..57744be 100644
--- a/config_center/file/factory.go
+++ b/config_center/file/factory.go
@@ -30,7 +30,7 @@ import (
)
func init() {
- extension.SetConfigCenterFactory(constant.FILE_KEY, func() config_center.DynamicConfigurationFactory {
+ extension.SetConfigCenterFactory(constant.FileKey, func() config_center.DynamicConfigurationFactory {
return &fileDynamicConfigurationFactory{}
})
}
diff --git a/config_center/nacos/impl.go b/config_center/nacos/impl.go
index 06e1a16..fdc8b6e 100644
--- a/config_center/nacos/impl.go
+++ b/config_center/nacos/impl.go
@@ -63,7 +63,7 @@ type nacosDynamicConfiguration struct {
func newNacosDynamicConfiguration(url *common.URL) (*nacosDynamicConfiguration, error) {
c := &nacosDynamicConfiguration{
- rootPath: "/" + url.GetParam(constant.CONFIG_NAMESPACE_KEY, config_center.DefaultGroup) + "/config",
+ rootPath: "/" + url.GetParam(constant.ConfigNamespaceKey, config_center.DefaultGroup) + "/config",
url: url,
done: make(chan struct{}),
}
diff --git a/config_center/parser/configuration_parser.go b/config_center/parser/configuration_parser.go
index 5e07f43..1f3f317 100644
--- a/config_center/parser/configuration_parser.go
+++ b/config_center/parser/configuration_parser.go
@@ -116,11 +116,11 @@ func (parser *DefaultConfigurationParser) ParseToUrls(content string) ([]*common
func serviceItemToUrls(item ConfigItem, config ConfiguratorConfig) ([]*common.URL, error) {
addresses := item.Addresses
if len(addresses) == 0 {
- addresses = append(addresses, constant.ANYHOST_VALUE)
+ addresses = append(addresses, constant.AnyhostValue)
}
var urls []*common.URL
for _, v := range addresses {
- urlStr := constant.OVERRIDE_PROTOCOL + "://" + v + "/"
+ urlStr := constant.OverrideProtocol + "://" + v + "/"
serviceStr, err := getServiceString(config.Key)
if err != nil {
return nil, perrors.WithStack(err)
@@ -133,7 +133,7 @@ func serviceItemToUrls(item ConfigItem, config ConfiguratorConfig) ([]*common.UR
urlStr = urlStr + paramStr
urlStr = urlStr + getEnabledString(item, config)
urlStr = urlStr + "&category="
- urlStr = urlStr + constant.DYNAMIC_CONFIGURATORS_CATEGORY
+ urlStr = urlStr + constant.DynamicConfiguratorsCategory
urlStr = urlStr + "&configVersion="
urlStr = urlStr + config.ConfigVersion
apps := item.Applications
@@ -163,14 +163,14 @@ func serviceItemToUrls(item ConfigItem, config ConfiguratorConfig) ([]*common.UR
func appItemToUrls(item ConfigItem, config ConfiguratorConfig) ([]*common.URL, error) {
addresses := item.Addresses
if len(addresses) == 0 {
- addresses = append(addresses, constant.ANYHOST_VALUE)
+ addresses = append(addresses, constant.AnyhostValue)
}
var urls []*common.URL
for _, v := range addresses {
- urlStr := constant.OVERRIDE_PROTOCOL + "://" + v + "/"
+ urlStr := constant.OverrideProtocol + "://" + v + "/"
services := item.Services
if len(services) == 0 {
- services = append(services, constant.ANY_VALUE)
+ services = append(services, constant.AnyValue)
}
for _, vs := range services {
serviceStr, err := getServiceString(vs)
@@ -187,7 +187,7 @@ func appItemToUrls(item ConfigItem, config ConfiguratorConfig) ([]*common.URL, e
urlStr = urlStr + config.Key
urlStr = urlStr + getEnabledString(item, config)
urlStr = urlStr + "&category="
- urlStr = urlStr + constant.APP_DYNAMIC_CONFIGURATORS_CATEGORY
+ urlStr = urlStr + constant.AppDynamicConfiguratorsCategory
urlStr = urlStr + "&configVersion="
urlStr = urlStr + config.ConfigVersion
url, err := common.NewURL(urlStr)
@@ -228,7 +228,7 @@ func getServiceString(service string) (string, error) {
func getParamString(item ConfigItem) (string, error) {
var retStr string
retStr = retStr + "category="
- retStr = retStr + constant.DYNAMIC_CONFIGURATORS_CATEGORY
+ retStr = retStr + constant.DynamicConfiguratorsCategory
if len(item.Side) > 0 {
retStr = retStr + "&side="
retStr = retStr + item.Side
@@ -242,7 +242,7 @@ func getParamString(item ConfigItem) (string, error) {
retStr += "&" + k + "=" + v
}
- retStr += "&" + constant.OVERRIDE_PROVIDERS_KEY + "=" + strings.Join(item.ProviderAddresses, ",")
+ retStr += "&" + constant.OverrideProvidersKey + "=" + strings.Join(item.ProviderAddresses, ",")
return retStr, nil
}
diff --git a/config_center/zookeeper/impl.go b/config_center/zookeeper/impl.go
index 2c03ec6..44d752c 100644
--- a/config_center/zookeeper/impl.go
+++ b/config_center/zookeeper/impl.go
@@ -65,7 +65,7 @@ type zookeeperDynamicConfiguration struct {
func newZookeeperDynamicConfiguration(url *common.URL) (*zookeeperDynamicConfiguration, error) {
c := &zookeeperDynamicConfiguration{
url: url,
- rootPath: "/" + url.GetParam(constant.CONFIG_NAMESPACE_KEY, config_center.DefaultGroup) + "/config",
+ rootPath: "/" + url.GetParam(constant.ConfigNamespaceKey, config_center.DefaultGroup) + "/config",
}
if v, ok := config.GetRootConfig().ConfigCenter.Params["base64"]; ok {
base64Enabled, err := strconv.ParseBool(v)
diff --git a/filter/accesslog/filter.go b/filter/accesslog/filter.go
index 981f24c..21d2a80 100644
--- a/filter/accesslog/filter.go
+++ b/filter/accesslog/filter.go
@@ -104,30 +104,30 @@ func (f *Filter) logIntoChannel(accessLogData Data) {
func (f *Filter) buildAccessLogData(_ protocol.Invoker, invocation protocol.Invocation) map[string]string {
dataMap := make(map[string]string, 16)
attachments := invocation.Attachments()
- itf := attachments[constant.INTERFACE_KEY]
+ itf := attachments[constant.InterfaceKey]
if itf == nil || len(itf.(string)) == 0 {
- itf = attachments[constant.PATH_KEY]
+ itf = attachments[constant.PathKey]
}
if itf != nil {
- dataMap[constant.INTERFACE_KEY] = itf.(string)
+ dataMap[constant.InterfaceKey] = itf.(string)
}
- if v, ok := attachments[constant.METHOD_KEY]; ok && v != nil {
- dataMap[constant.METHOD_KEY] = v.(string)
+ if v, ok := attachments[constant.MethodKey]; ok && v != nil {
+ dataMap[constant.MethodKey] = v.(string)
}
- if v, ok := attachments[constant.VERSION_KEY]; ok && v != nil {
- dataMap[constant.VERSION_KEY] = v.(string)
+ if v, ok := attachments[constant.VersionKey]; ok && v != nil {
+ dataMap[constant.VersionKey] = v.(string)
}
- if v, ok := attachments[constant.GROUP_KEY]; ok && v != nil {
- dataMap[constant.GROUP_KEY] = v.(string)
+ if v, ok := attachments[constant.GroupKey]; ok && v != nil {
+ dataMap[constant.GroupKey] = v.(string)
}
- if v, ok := attachments[constant.TIMESTAMP_KEY]; ok && v != nil {
- dataMap[constant.TIMESTAMP_KEY] = v.(string)
+ if v, ok := attachments[constant.TimestampKey]; ok && v != nil {
+ dataMap[constant.TimestampKey] = v.(string)
}
- if v, ok := attachments[constant.LOCAL_ADDR]; ok && v != nil {
- dataMap[constant.LOCAL_ADDR] = v.(string)
+ if v, ok := attachments[constant.LocalAddr]; ok && v != nil {
+ dataMap[constant.LocalAddr] = v.(string)
}
- if v, ok := attachments[constant.REMOTE_ADDR]; ok && v != nil {
- dataMap[constant.REMOTE_ADDR] = v.(string)
+ if v, ok := attachments[constant.RemoteAddr]; ok && v != nil {
+ dataMap[constant.RemoteAddr] = v.(string)
}
if len(invocation.Arguments()) > 0 {
@@ -240,26 +240,26 @@ type Data struct {
func (d *Data) toLogMessage() string {
builder := strings.Builder{}
builder.WriteString("[")
- builder.WriteString(d.data[constant.TIMESTAMP_KEY])
+ builder.WriteString(d.data[constant.TimestampKey])
builder.WriteString("] ")
- builder.WriteString(d.data[constant.REMOTE_ADDR])
+ builder.WriteString(d.data[constant.RemoteAddr])
builder.WriteString(" -> ")
- builder.WriteString(d.data[constant.LOCAL_ADDR])
+ builder.WriteString(d.data[constant.LocalAddr])
builder.WriteString(" - ")
- if len(d.data[constant.GROUP_KEY]) > 0 {
- builder.WriteString(d.data[constant.GROUP_KEY])
+ if len(d.data[constant.GroupKey]) > 0 {
+ builder.WriteString(d.data[constant.GroupKey])
builder.WriteString("/")
}
- builder.WriteString(d.data[constant.INTERFACE_KEY])
+ builder.WriteString(d.data[constant.InterfaceKey])
- if len(d.data[constant.VERSION_KEY]) > 0 {
+ if len(d.data[constant.VersionKey]) > 0 {
builder.WriteString(":")
- builder.WriteString(d.data[constant.VERSION_KEY])
+ builder.WriteString(d.data[constant.VersionKey])
}
builder.WriteString(" ")
- builder.WriteString(d.data[constant.METHOD_KEY])
+ builder.WriteString(d.data[constant.MethodKey])
builder.WriteString("(")
if len(d.data[Types]) > 0 {
builder.WriteString(d.data[Types])
diff --git a/filter/accesslog/filter_test.go b/filter/accesslog/filter_test.go
index 4bd6f2e..4fa5f7e 100644
--- a/filter/accesslog/filter_test.go
+++ b/filter/accesslog/filter_test.go
@@ -66,8 +66,8 @@ func TestFilterInvokeDefaultConfig(t *testing.T) {
invoker := protocol.NewBaseInvoker(url)
attach := make(map[string]interface{}, 10)
- attach[constant.VERSION_KEY] = "1.0"
- attach[constant.GROUP_KEY] = "MyGroup"
+ attach[constant.VersionKey] = "1.0"
+ attach[constant.GroupKey] = "MyGroup"
inv := invocation.NewRPCInvocation("MethodName", []interface{}{"OK", "Hello"}, attach)
accessLogFilter := &Filter{}
diff --git a/filter/auth/accesskey_storage.go b/filter/auth/accesskey_storage.go
index de6c456..4566cfb 100644
--- a/filter/auth/accesskey_storage.go
+++ b/filter/auth/accesskey_storage.go
@@ -26,7 +26,7 @@ import (
)
func init() {
- extension.SetAccessKeyStorages(constant.DEFAULT_ACCESS_KEY_STORAGE, func() filter.AccessKeyStorage {
+ extension.SetAccessKeyStorages(constant.DefaultAccessKeyStorage, func() filter.AccessKeyStorage {
return &DefaultAccesskeyStorage{}
})
}
@@ -37,7 +37,7 @@ type DefaultAccesskeyStorage struct{}
// GetAccessKeyPair retrieves AccessKeyPair from url by the key "accessKeyId" and "secretAccessKey"
func (storage *DefaultAccesskeyStorage) GetAccessKeyPair(invocation protocol.Invocation, url *common.URL) *filter.AccessKeyPair {
return &filter.AccessKeyPair{
- AccessKey: url.GetParam(constant.ACCESS_KEY_ID_KEY, ""),
- SecretKey: url.GetParam(constant.SECRET_ACCESS_KEY_KEY, ""),
+ AccessKey: url.GetParam(constant.AccessKeyIDKey, ""),
+ SecretKey: url.GetParam(constant.SecretAccessKeyKey, ""),
}
}
diff --git a/filter/auth/accesskey_storage_test.go b/filter/auth/accesskey_storage_test.go
index a8b1eb6..8c72e7c 100644
--- a/filter/auth/accesskey_storage_test.go
+++ b/filter/auth/accesskey_storage_test.go
@@ -35,8 +35,8 @@ import (
func TestDefaultAccesskeyStorage_GetAccesskeyPair(t *testing.T) {
url := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.SECRET_ACCESS_KEY_KEY, "skey"),
- common.WithParamsValue(constant.ACCESS_KEY_ID_KEY, "akey"))
+ common.WithParamsValue(constant.SecretAccessKeyKey, "skey"),
+ common.WithParamsValue(constant.AccessKeyIDKey, "akey"))
invocation := &invocation2.RPCInvocation{}
storage := &DefaultAccesskeyStorage{}
accesskeyPair := storage.GetAccessKeyPair(invocation, url)
diff --git a/filter/auth/consumer_sign_filter_test.go b/filter/auth/consumer_sign_filter_test.go
index ba024bd..187f125 100644
--- a/filter/auth/consumer_sign_filter_test.go
+++ b/filter/auth/consumer_sign_filter_test.go
@@ -38,8 +38,8 @@ import (
func TestConsumerSignFilter_Invoke(t *testing.T) {
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=gg&version=2.6.0")
- url.SetParam(constant.SECRET_ACCESS_KEY_KEY, "sk")
- url.SetParam(constant.ACCESS_KEY_ID_KEY, "ak")
+ url.SetParam(constant.SecretAccessKeyKey, "sk")
+ url.SetParam(constant.AccessKeyIDKey, "ak")
inv := invocation.NewRPCInvocation("test", []interface{}{"OK"}, nil)
filter := &ConsumerSignFilter{}
ctrl := gomock.NewController(t)
@@ -50,6 +50,6 @@ func TestConsumerSignFilter_Invoke(t *testing.T) {
invoker.EXPECT().GetUrl().Return(url).Times(2)
assert.Equal(t, result, filter.Invoke(context.Background(), invoker, inv))
- url.SetParam(constant.SERVICE_AUTH_KEY, "true")
+ url.SetParam(constant.ServiceAuthKey, "true")
assert.Equal(t, result, filter.Invoke(context.Background(), invoker, inv))
}
diff --git a/filter/auth/default_authenticator.go b/filter/auth/default_authenticator.go
index a36f1e1..845bc2e 100644
--- a/filter/auth/default_authenticator.go
+++ b/filter/auth/default_authenticator.go
@@ -34,7 +34,7 @@ import (
)
func init() {
- extension.SetAuthenticator(constant.DEFAULT_AUTHENTICATOR, func() filter.Authenticator {
+ extension.SetAuthenticator(constant.DefaultAuthenticator, func() filter.Authenticator {
return &DefaultAuthenticator{}
})
}
@@ -46,7 +46,7 @@ type DefaultAuthenticator struct{}
func (authenticator *DefaultAuthenticator) Sign(invocation protocol.Invocation, url *common.URL) error {
currentTimeMillis := strconv.Itoa(int(time.Now().Unix() * 1000))
- consumer := url.GetParam(constant.APPLICATION_KEY, "")
+ consumer := url.GetParam(constant.ApplicationKey, "")
accessKeyPair, err := getAccessKeyPair(invocation, url)
if err != nil {
return errors.New("get accesskey pair failed, cause: " + err.Error())
@@ -56,20 +56,20 @@ func (authenticator *DefaultAuthenticator) Sign(invocation protocol.Invocation,
if err != nil {
return err
}
- inv.SetAttachments(constant.REQUEST_SIGNATURE_KEY, signature)
- inv.SetAttachments(constant.REQUEST_TIMESTAMP_KEY, currentTimeMillis)
- inv.SetAttachments(constant.AK_KEY, accessKeyPair.AccessKey)
- inv.SetAttachments(constant.CONSUMER, consumer)
+ inv.SetAttachments(constant.RequestSignatureKey, signature)
+ inv.SetAttachments(constant.RequestTimestampKey, currentTimeMillis)
+ inv.SetAttachments(constant.AKKey, accessKeyPair.AccessKey)
+ inv.SetAttachments(constant.Consumer, consumer)
return nil
}
// getSignature
// get signature by the metadata and params of the invocation
func getSignature(url *common.URL, invocation protocol.Invocation, secrectKey string, currentTime string) (string, error) {
- requestString := fmt.Sprintf(constant.SIGNATURE_STRING_FORMAT,
+ requestString := fmt.Sprintf(constant.SignatureStringFormat,
url.ColonSeparatedKey(), invocation.MethodName(), secrectKey, currentTime)
var signature string
- if parameterEncrypt := url.GetParamBool(constant.PARAMETER_SIGNATURE_ENABLE_KEY, false); parameterEncrypt {
+ if parameterEncrypt := url.GetParamBool(constant.ParameterSignatureEnableKey, false); parameterEncrypt {
var err error
if signature, err = SignWithParams(invocation.Arguments(), requestString, secrectKey); err != nil {
// TODO
@@ -84,11 +84,11 @@ func getSignature(url *common.URL, invocation protocol.Invocation, secrectKey st
// Authenticate verifies whether the signature sent by the requester is correct
func (authenticator *DefaultAuthenticator) Authenticate(invocation protocol.Invocation, url *common.URL) error {
- accessKeyId := invocation.AttachmentsByKey(constant.AK_KEY, "")
+ accessKeyId := invocation.AttachmentsByKey(constant.AKKey, "")
- requestTimestamp := invocation.AttachmentsByKey(constant.REQUEST_TIMESTAMP_KEY, "")
- originSignature := invocation.AttachmentsByKey(constant.REQUEST_SIGNATURE_KEY, "")
- consumer := invocation.AttachmentsByKey(constant.CONSUMER, "")
+ requestTimestamp := invocation.AttachmentsByKey(constant.RequestTimestampKey, "")
+ originSignature := invocation.AttachmentsByKey(constant.RequestSignatureKey, "")
+ consumer := invocation.AttachmentsByKey(constant.Consumer, "")
if IsEmpty(accessKeyId, false) || IsEmpty(consumer, false) ||
IsEmpty(requestTimestamp, false) || IsEmpty(originSignature, false) {
return errors.New("failed to authenticate your ak/sk, maybe the consumer has not enabled the auth")
@@ -110,7 +110,7 @@ func (authenticator *DefaultAuthenticator) Authenticate(invocation protocol.Invo
}
func getAccessKeyPair(invocation protocol.Invocation, url *common.URL) (*filter.AccessKeyPair, error) {
- accesskeyStorage := extension.GetAccessKeyStorages(url.GetParam(constant.ACCESS_KEY_STORAGE_KEY, constant.DEFAULT_ACCESS_KEY_STORAGE))
+ accesskeyStorage := extension.GetAccessKeyStorages(url.GetParam(constant.AccessKeyStorageKey, constant.DefaultAccessKeyStorage))
accessKeyPair := accesskeyStorage.GetAccessKeyPair(invocation, url)
if accessKeyPair == nil || IsEmpty(accessKeyPair.AccessKey, false) || IsEmpty(accessKeyPair.SecretKey, true) {
return nil, errors.New("accessKeyId or secretAccessKey not found")
@@ -120,9 +120,9 @@ func getAccessKeyPair(invocation protocol.Invocation, url *common.URL) (*filter.
}
func doAuthWork(url *common.URL, do func(filter.Authenticator) error) error {
- shouldAuth := url.GetParamBool(constant.SERVICE_AUTH_KEY, false)
+ shouldAuth := url.GetParamBool(constant.ServiceAuthKey, false)
if shouldAuth {
- authenticator := extension.GetAuthenticator(url.GetParam(constant.AUTHENTICATOR_KEY, constant.DEFAULT_AUTHENTICATOR))
+ authenticator := extension.GetAuthenticator(url.GetParam(constant.AuthenticatorKey, constant.DefaultAuthenticator))
return do(authenticator)
}
return nil
diff --git a/filter/auth/default_authenticator_test.go b/filter/auth/default_authenticator_test.go
index eeab4cc..d6ce6ef 100644
--- a/filter/auth/default_authenticator_test.go
+++ b/filter/auth/default_authenticator_test.go
@@ -39,9 +39,9 @@ func TestDefaultAuthenticator_Authenticate(t *testing.T) {
secret := "dubbo-sk"
access := "dubbo-ak"
testurl, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=gg&version=2.6.0")
- testurl.SetParam(constant.PARAMETER_SIGNATURE_ENABLE_KEY, "true")
- testurl.SetParam(constant.ACCESS_KEY_ID_KEY, access)
- testurl.SetParam(constant.SECRET_ACCESS_KEY_KEY, secret)
+ testurl.SetParam(constant.ParameterSignatureEnableKey, "true")
+ testurl.SetParam(constant.AccessKeyIDKey, access)
+ testurl.SetParam(constant.SecretAccessKeyKey, secret)
parmas := []interface{}{"OK", struct {
Name string
ID int64
@@ -53,19 +53,19 @@ func TestDefaultAuthenticator_Authenticate(t *testing.T) {
authenticator := &DefaultAuthenticator{}
invcation := invocation.NewRPCInvocation("test", parmas, map[string]interface{}{
- constant.REQUEST_SIGNATURE_KEY: signature,
- constant.CONSUMER: "test",
- constant.REQUEST_TIMESTAMP_KEY: requestTime,
- constant.AK_KEY: access,
+ constant.RequestSignatureKey: signature,
+ constant.Consumer: "test",
+ constant.RequestTimestampKey: requestTime,
+ constant.AKKey: access,
})
err := authenticator.Authenticate(invcation, testurl)
assert.Nil(t, err)
// modify the params
invcation = invocation.NewRPCInvocation("test", parmas[:1], map[string]interface{}{
- constant.REQUEST_SIGNATURE_KEY: signature,
- constant.CONSUMER: "test",
- constant.REQUEST_TIMESTAMP_KEY: requestTime,
- constant.AK_KEY: access,
+ constant.RequestSignatureKey: signature,
+ constant.Consumer: "test",
+ constant.RequestTimestampKey: requestTime,
+ constant.AKKey: access,
})
err = authenticator.Authenticate(invcation, testurl)
assert.NotNil(t, err)
@@ -74,22 +74,22 @@ func TestDefaultAuthenticator_Authenticate(t *testing.T) {
func TestDefaultAuthenticator_Sign(t *testing.T) {
authenticator := &DefaultAuthenticator{}
testurl, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?application=test&interface=com.ikurento.user.UserProvider&group=gg&version=2.6.0")
- testurl.SetParam(constant.ACCESS_KEY_ID_KEY, "akey")
- testurl.SetParam(constant.SECRET_ACCESS_KEY_KEY, "skey")
- testurl.SetParam(constant.PARAMETER_SIGNATURE_ENABLE_KEY, "false")
+ testurl.SetParam(constant.AccessKeyIDKey, "akey")
+ testurl.SetParam(constant.SecretAccessKeyKey, "skey")
+ testurl.SetParam(constant.ParameterSignatureEnableKey, "false")
inv := invocation.NewRPCInvocation("test", []interface{}{"OK"}, nil)
_ = 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, ""), "")
- assert.Equal(t, inv.AttachmentsByKey(constant.AK_KEY, ""), "akey")
+ assert.NotEqual(t, inv.AttachmentsByKey(constant.RequestSignatureKey, ""), "")
+ assert.NotEqual(t, inv.AttachmentsByKey(constant.Consumer, ""), "")
+ assert.NotEqual(t, inv.AttachmentsByKey(constant.RequestTimestampKey, ""), "")
+ assert.Equal(t, inv.AttachmentsByKey(constant.AKKey, ""), "akey")
}
func Test_getAccessKeyPairSuccess(t *testing.T) {
testurl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.SECRET_ACCESS_KEY_KEY, "skey"),
- common.WithParamsValue(constant.ACCESS_KEY_ID_KEY, "akey"))
+ common.WithParamsValue(constant.SecretAccessKeyKey, "skey"),
+ common.WithParamsValue(constant.AccessKeyIDKey, "akey"))
invcation := invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, nil)
_, e := getAccessKeyPair(invcation, testurl)
assert.Nil(t, e)
@@ -102,28 +102,28 @@ func Test_getAccessKeyPairFailed(t *testing.T) {
}()
testurl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.ACCESS_KEY_ID_KEY, "akey"))
+ common.WithParamsValue(constant.AccessKeyIDKey, "akey"))
invcation := invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, nil)
_, e := getAccessKeyPair(invcation, testurl)
assert.NotNil(t, e)
testurl = common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.SECRET_ACCESS_KEY_KEY, "skey"),
- common.WithParamsValue(constant.ACCESS_KEY_ID_KEY, "akey"), common.WithParamsValue(constant.ACCESS_KEY_STORAGE_KEY, "dubbo"))
+ common.WithParamsValue(constant.SecretAccessKeyKey, "skey"),
+ common.WithParamsValue(constant.AccessKeyIDKey, "akey"), common.WithParamsValue(constant.AccessKeyStorageKey, "dubbo"))
_, e = getAccessKeyPair(invcation, testurl)
assert.NoError(t, e)
}
func Test_getSignatureWithinParams(t *testing.T) {
testurl, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=gg&version=2.6.0")
- testurl.SetParam(constant.PARAMETER_SIGNATURE_ENABLE_KEY, "true")
+ testurl.SetParam(constant.ParameterSignatureEnableKey, "true")
inv := invocation.NewRPCInvocation("test", []interface{}{"OK"}, map[string]interface{}{
"": "",
})
secret := "dubbo"
current := strconv.Itoa(int(time.Now().Unix() * 1000))
signature, _ := getSignature(testurl, inv, secret, current)
- requestString := fmt.Sprintf(constant.SIGNATURE_STRING_FORMAT,
+ requestString := fmt.Sprintf(constant.SignatureStringFormat,
testurl.ColonSeparatedKey(), inv.MethodName(), secret, current)
s, _ := SignWithParams(inv.Arguments(), requestString, secret)
assert.False(t, IsEmpty(signature, false))
@@ -132,12 +132,12 @@ func Test_getSignatureWithinParams(t *testing.T) {
func Test_getSignature(t *testing.T) {
testurl, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=gg&version=2.6.0")
- testurl.SetParam(constant.PARAMETER_SIGNATURE_ENABLE_KEY, "false")
+ testurl.SetParam(constant.ParameterSignatureEnableKey, "false")
inv := invocation.NewRPCInvocation("test", []interface{}{"OK"}, nil)
secret := "dubbo"
current := strconv.Itoa(int(time.Now().Unix() * 1000))
signature, _ := getSignature(testurl, inv, secret, current)
- requestString := fmt.Sprintf(constant.SIGNATURE_STRING_FORMAT,
+ requestString := fmt.Sprintf(constant.SignatureStringFormat,
testurl.ColonSeparatedKey(), inv.MethodName(), secret, current)
s := Sign(requestString, secret)
assert.False(t, IsEmpty(signature, false))
diff --git a/filter/auth/provider_auth_filter_test.go b/filter/auth/provider_auth_filter_test.go
index 1f83501..edf1dc6 100644
--- a/filter/auth/provider_auth_filter_test.go
+++ b/filter/auth/provider_auth_filter_test.go
@@ -42,8 +42,8 @@ func TestProviderAuthFilter_Invoke(t *testing.T) {
secret := "dubbo-sk"
access := "dubbo-ak"
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=gg&version=2.6.0")
- url.SetParam(constant.ACCESS_KEY_ID_KEY, access)
- url.SetParam(constant.SECRET_ACCESS_KEY_KEY, secret)
+ url.SetParam(constant.AccessKeyIDKey, access)
+ url.SetParam(constant.SecretAccessKeyKey, secret)
parmas := []interface{}{
"OK",
struct {
@@ -56,10 +56,10 @@ func TestProviderAuthFilter_Invoke(t *testing.T) {
signature, _ := getSignature(url, inv, secret, requestTime)
inv = invocation.NewRPCInvocation("test", []interface{}{"OK"}, map[string]interface{}{
- constant.REQUEST_SIGNATURE_KEY: signature,
- constant.CONSUMER: "test",
- constant.REQUEST_TIMESTAMP_KEY: requestTime,
- constant.AK_KEY: access,
+ constant.RequestSignatureKey: signature,
+ constant.Consumer: "test",
+ constant.RequestTimestampKey: requestTime,
+ constant.AKKey: access,
})
ctrl := gomock.NewController(t)
filter := &ProviderAuthFilter{}
@@ -69,6 +69,6 @@ func TestProviderAuthFilter_Invoke(t *testing.T) {
invoker.EXPECT().Invoke(inv).Return(result).Times(2)
invoker.EXPECT().GetUrl().Return(url).Times(2)
assert.Equal(t, result, filter.Invoke(context.Background(), invoker, inv))
- url.SetParam(constant.SERVICE_AUTH_KEY, "true")
+ url.SetParam(constant.ServiceAuthKey, "true")
assert.Equal(t, result, filter.Invoke(context.Background(), invoker, inv))
}
diff --git a/filter/echo/filter.go b/filter/echo/filter.go
index c6b367a..f1bc7c3 100644
--- a/filter/echo/filter.go
+++ b/filter/echo/filter.go
@@ -44,7 +44,7 @@ type Filter struct{}
// Invoke response to the callers with its first argument.
func (f *Filter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
logger.Debugf("%v,%v", invocation.MethodName(), len(invocation.Arguments()))
- if invocation.MethodName() == constant.ECHO && len(invocation.Arguments()) == 1 {
+ if invocation.MethodName() == constant.Echo && len(invocation.Arguments()) == 1 {
return &protocol.RPCResult{
Rest: invocation.Arguments()[0],
Attrs: invocation.Attachments(),
diff --git a/filter/execlmt/filter.go b/filter/execlmt/filter.go
index 060e3c4..c313c62 100644
--- a/filter/execlmt/filter.go
+++ b/filter/execlmt/filter.go
@@ -82,13 +82,13 @@ func (f *Filter) Invoke(ctx context.Context, invoker protocol.Invoker, invocatio
limitTarget := ivkURL.ServiceKey()
var limitRateConfig string
- methodLevelConfig := ivkURL.GetParam(methodConfigPrefix+constant.EXECUTE_LIMIT_KEY, "")
+ methodLevelConfig := ivkURL.GetParam(methodConfigPrefix+constant.ExecuteLimitKey, "")
if len(methodLevelConfig) > 0 {
// we have the method-level configuration
limitTarget = limitTarget + "#" + invocation.MethodName()
limitRateConfig = methodLevelConfig
} else {
- limitRateConfig = ivkURL.GetParam(constant.EXECUTE_LIMIT_KEY, constant.DEFAULT_EXECUTE_LIMIT)
+ limitRateConfig = ivkURL.GetParam(constant.ExecuteLimitKey, constant.DefaultExecuteLimit)
}
limitRate, err := strconv.ParseInt(limitRateConfig, 0, 0)
@@ -109,8 +109,8 @@ func (f *Filter) Invoke(ctx context.Context, invoker protocol.Invoker, invocatio
defer state.(*ExecuteState).decrease()
if concurrentCount > limitRate {
logger.Errorf("The invocation was rejected due to over the execute limitation, url: %s ", ivkURL.String())
- rejectedHandlerConfig := ivkURL.GetParam(methodConfigPrefix+constant.EXECUTE_REJECTED_EXECUTION_HANDLER_KEY,
- ivkURL.GetParam(constant.EXECUTE_REJECTED_EXECUTION_HANDLER_KEY, constant.DEFAULT_KEY))
+ rejectedHandlerConfig := ivkURL.GetParam(methodConfigPrefix+constant.ExecuteRejectedExecutionHandlerKey,
+ ivkURL.GetParam(constant.ExecuteRejectedExecutionHandlerKey, constant.DefaultKey))
return extension.GetRejectedExecutionHandler(rejectedHandlerConfig).RejectedExecution(ivkURL, invocation)
}
diff --git a/filter/execlmt/filter_test.go b/filter/execlmt/filter_test.go
index d5ff237..c255c5a 100644
--- a/filter/execlmt/filter_test.go
+++ b/filter/execlmt/filter_test.go
@@ -40,7 +40,7 @@ func TestFilterInvokeIgnored(t *testing.T) {
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.INTERFACE_KEY, methodName))
+ common.WithParamsValue(constant.InterfaceKey, methodName))
limitFilter := newFilter()
@@ -55,8 +55,8 @@ func TestFilterInvokeConfigureError(t *testing.T) {
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.INTERFACE_KEY, methodName),
- common.WithParamsValue(constant.EXECUTE_LIMIT_KEY, "13a"),
+ common.WithParamsValue(constant.InterfaceKey, methodName),
+ common.WithParamsValue(constant.ExecuteLimitKey, "13a"),
)
limitFilter := newFilter()
@@ -72,8 +72,8 @@ func TestFilterInvoke(t *testing.T) {
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.INTERFACE_KEY, methodName),
- common.WithParamsValue(constant.EXECUTE_LIMIT_KEY, "20"),
+ common.WithParamsValue(constant.InterfaceKey, methodName),
+ common.WithParamsValue(constant.ExecuteLimitKey, "20"),
)
limitFilter := newFilter()
diff --git a/filter/generic/filter.go b/filter/generic/filter.go
index 4aa2d6e..38fa76b 100644
--- a/filter/generic/filter.go
+++ b/filter/generic/filter.go
@@ -54,7 +54,7 @@ func (f *Filter) Invoke(ctx context.Context, invoker protocol.Invoker, invocatio
args := make([]hessian.Object, 0, len(oldargs))
// get generic info from attachments of invocation, the default value is "true"
- generic := invocation.AttachmentsByKey(constant.GENERIC_KEY, constant.GenericSerializationDefault)
+ generic := invocation.AttachmentsByKey(constant.GenericKey, constant.GenericSerializationDefault)
// get generalizer according to value in the `generic`
g := getGeneralizer(generic)
@@ -79,13 +79,13 @@ func (f *Filter) Invoke(ctx context.Context, invoker protocol.Invoker, invocatio
types,
args,
}
- newivc := invocation2.NewRPCInvocation(constant.GENERIC, newargs, invocation.Attachments())
+ newivc := invocation2.NewRPCInvocation(constant.Generic, newargs, invocation.Attachments())
newivc.SetReply(invocation.Reply())
- newivc.Attachments()[constant.GENERIC_KEY] = invoker.GetURL().GetParam(constant.GENERIC_KEY, "")
+ newivc.Attachments()[constant.GenericKey] = invoker.GetURL().GetParam(constant.GenericKey, "")
return invoker.Invoke(ctx, newivc)
} else if isMakingAGenericCall(invoker, invocation) {
- invocation.Attachments()[constant.GENERIC_KEY] = invoker.GetURL().GetParam(constant.GENERIC_KEY, "")
+ invocation.Attachments()[constant.GenericKey] = invoker.GetURL().GetParam(constant.GenericKey, "")
}
return invoker.Invoke(ctx, invocation)
}
diff --git a/filter/generic/filter_test.go b/filter/generic/filter_test.go
index c8bf45a..8ad669d 100644
--- a/filter/generic/filter_test.go
+++ b/filter/generic/filter_test.go
@@ -43,7 +43,7 @@ import (
func TestFilter_Invoke(t *testing.T) {
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.GENERIC_KEY, constant.GenericSerializationDefault))
+ common.WithParamsValue(constant.GenericKey, constant.GenericSerializationDefault))
filter := &Filter{}
ctrl := gomock.NewController(t)
@@ -55,12 +55,12 @@ func TestFilter_Invoke(t *testing.T) {
mockInvoker.EXPECT().GetUrl().Return(invokeUrl).Times(2)
mockInvoker.EXPECT().Invoke(gomock.Not(normalInvocation)).DoAndReturn(
func(invocation protocol.Invocation) protocol.Result {
- assert.Equal(t, constant.GENERIC, invocation.MethodName())
+ assert.Equal(t, constant.Generic, invocation.MethodName())
args := invocation.Arguments()
assert.Equal(t, "Hello", args[0])
assert.Equal(t, "java.lang.String", args[1].([]string)[0])
assert.Equal(t, "arg1", args[2].([]hessian.Object)[0].(string))
- assert.Equal(t, constant.GenericSerializationDefault, invocation.AttachmentsByKey(constant.GENERIC_KEY, ""))
+ assert.Equal(t, constant.GenericSerializationDefault, invocation.AttachmentsByKey(constant.GenericKey, ""))
return &protocol.RPCResult{}
})
@@ -72,13 +72,13 @@ func TestFilter_Invoke(t *testing.T) {
func TestFilter_InvokeWithGenericCall(t *testing.T) {
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.GENERIC_KEY, constant.GenericSerializationDefault))
+ common.WithParamsValue(constant.GenericKey, constant.GenericSerializationDefault))
filter := &Filter{}
ctrl := gomock.NewController(t)
defer ctrl.Finish()
- genericInvocation := invocation.NewRPCInvocation(constant.GENERIC, []interface{}{
+ genericInvocation := invocation.NewRPCInvocation(constant.Generic, []interface{}{
"hello",
[]string{"java.lang.String"},
[]string{"arg1"},
@@ -88,12 +88,12 @@ func TestFilter_InvokeWithGenericCall(t *testing.T) {
mockInvoker.EXPECT().GetUrl().Return(invokeUrl).Times(3)
mockInvoker.EXPECT().Invoke(gomock.Any()).DoAndReturn(
func(invocation protocol.Invocation) protocol.Result {
- assert.Equal(t, constant.GENERIC, invocation.MethodName())
+ assert.Equal(t, constant.Generic, invocation.MethodName())
args := invocation.Arguments()
assert.Equal(t, "hello", args[0])
assert.Equal(t, "java.lang.String", args[1].([]string)[0])
assert.Equal(t, "arg1", args[2].([]string)[0])
- assert.Equal(t, constant.GenericSerializationDefault, invocation.AttachmentsByKey(constant.GENERIC_KEY, ""))
+ assert.Equal(t, constant.GenericSerializationDefault, invocation.AttachmentsByKey(constant.GenericKey, ""))
return &protocol.RPCResult{}
})
diff --git a/filter/generic/service_filter.go b/filter/generic/service_filter.go
index 2b6f7e4..3693825 100644
--- a/filter/generic/service_filter.go
+++ b/filter/generic/service_filter.go
@@ -75,7 +75,7 @@ func (f *ServiceFilter) Invoke(ctx context.Context, invoker protocol.Invoker, in
argsType := method.ArgsType()
// get generic info from attachments of invocation, the default value is "true"
- generic := invocation.AttachmentsByKey(constant.GENERIC_KEY, constant.GenericSerializationDefault)
+ generic := invocation.AttachmentsByKey(constant.GenericKey, constant.GenericSerializationDefault)
// get generalizer according to value in the `generic`
g := getGeneralizer(generic)
@@ -114,7 +114,7 @@ func (f *ServiceFilter) Invoke(ctx context.Context, invoker protocol.Invoker, in
func (f *ServiceFilter) OnResponse(_ context.Context, result protocol.Result, _ protocol.Invoker, invocation protocol.Invocation) protocol.Result {
if isGenericInvocation(invocation) && result.Result() != nil {
// get generic info from attachments of invocation, the default value is "true"
- generic := invocation.AttachmentsByKey(constant.GENERIC_KEY, constant.GenericSerializationDefault)
+ generic := invocation.AttachmentsByKey(constant.GenericKey, constant.GenericSerializationDefault)
// get generalizer according to value in the `generic`
g := getGeneralizer(generic)
diff --git a/filter/generic/service_filter_test.go b/filter/generic/service_filter_test.go
index c6eb499..24bd7be 100644
--- a/filter/generic/service_filter_test.go
+++ b/filter/generic/service_filter_test.go
@@ -82,11 +82,11 @@ func TestServiceFilter_Invoke(t *testing.T) {
mockInvoker.EXPECT().Invoke(gomock.Eq(invocation1))
_ = filter.Invoke(context.Background(), mockInvoker, invocation1)
// arguments are nil
- invocation2 := invocation.NewRPCInvocation(constant.GENERIC, nil, nil)
+ invocation2 := invocation.NewRPCInvocation(constant.Generic, nil, nil)
mockInvoker.EXPECT().Invoke(gomock.Eq(invocation2))
_ = filter.Invoke(context.Background(), mockInvoker, invocation2)
// the number of arguments is not 3
- invocation3 := invocation.NewRPCInvocation(constant.GENERIC, []interface{}{"hello"}, nil)
+ invocation3 := invocation.NewRPCInvocation(constant.Generic, []interface{}{"hello"}, nil)
mockInvoker.EXPECT().Invoke(gomock.Eq(invocation3))
_ = filter.Invoke(context.Background(), mockInvoker, invocation3)
@@ -96,10 +96,10 @@ func TestServiceFilter_Invoke(t *testing.T) {
ivkUrl := common.NewURLWithOptions(
common.WithProtocol("test"),
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.INTERFACE_KEY, service.Reference()),
- common.WithParamsValue(constant.GENERIC_KEY, constant.GenericSerializationDefault))
+ common.WithParamsValue(constant.InterfaceKey, service.Reference()),
+ common.WithParamsValue(constant.GenericKey, constant.GenericSerializationDefault))
// registry RPC service
- _, err := common.ServiceMap.Register(ivkUrl.GetParam(constant.INTERFACE_KEY, ""),
+ _, err := common.ServiceMap.Register(ivkUrl.GetParam(constant.InterfaceKey, ""),
ivkUrl.Protocol,
"",
"",
@@ -110,40 +110,40 @@ func TestServiceFilter_Invoke(t *testing.T) {
mockInvoker.EXPECT().GetUrl().Return(ivkUrl).Times(3)
// invoke a method without errors using default generalization
- invocation4 := invocation.NewRPCInvocation(constant.GENERIC,
+ invocation4 := invocation.NewRPCInvocation(constant.Generic,
[]interface{}{
"Hello",
[]string{"java.lang.String"},
[]hessian.Object{"world"},
}, map[string]interface{}{
- constant.GENERIC_KEY: "true",
+ constant.GenericKey: "true",
})
// invoke a non-existed method
- invocation5 := invocation.NewRPCInvocation(constant.GENERIC,
+ invocation5 := invocation.NewRPCInvocation(constant.Generic,
[]interface{}{
"hello11",
[]string{"java.lang.String"},
[]hessian.Object{"world"},
}, map[string]interface{}{
- constant.GENERIC_KEY: "true",
+ constant.GenericKey: "true",
})
// invoke a method with incorrect arguments
- invocation6 := invocation.NewRPCInvocation(constant.GENERIC,
+ invocation6 := invocation.NewRPCInvocation(constant.Generic,
[]interface{}{
"Hello",
[]string{"java.lang.String", "java.lang.String"},
[]hessian.Object{"world", "haha"},
}, map[string]interface{}{
- constant.GENERIC_KEY: "true",
+ constant.GenericKey: "true",
})
// invoke a method without errors using protobuf-json generalization
- //invocation7 := invocation.NewRPCInvocation(constant.GENERIC,
+ //invocation7 := invocation.NewRPCInvocation(constant.Generic,
// []interface{}{
// "HelloPB",
// []string{},
// []hessian.Object{"{\"id\":1}"},
// }, map[string]interface{}{
- // constant.GENERIC_KEY: constant.GenericSerializationProtobuf,
+ // constant.GenericKey: constant.GenericSerializationProtobuf,
// })
mockInvoker.EXPECT().Invoke(gomock.All(
@@ -196,13 +196,13 @@ func TestServiceFilter_OnResponse(t *testing.T) {
filter := &ServiceFilter{}
// invoke a method without errors
- invocation1 := invocation.NewRPCInvocation(constant.GENERIC,
+ invocation1 := invocation.NewRPCInvocation(constant.Generic,
[]interface{}{
"hello",
[]interface{}{"java.lang.String"},
[]interface{}{"world"},
}, map[string]interface{}{
- constant.GENERIC_KEY: "true",
+ constant.GenericKey: "true",
})
rpcResult := &protocol.RPCResult{
diff --git a/filter/generic/util.go b/filter/generic/util.go
index a7fe467..9936ec7 100644
--- a/filter/generic/util.go
+++ b/filter/generic/util.go
@@ -30,14 +30,14 @@ import (
// isCallingToGenericService check if it calls to a generic service
func isCallingToGenericService(invoker protocol.Invoker, invocation protocol.Invocation) bool {
- return isGeneric(invoker.GetURL().GetParam(constant.GENERIC_KEY, "")) &&
- invocation.MethodName() != constant.GENERIC
+ return isGeneric(invoker.GetURL().GetParam(constant.GenericKey, "")) &&
+ invocation.MethodName() != constant.Generic
}
// isMakingAGenericCall check if it is making a generic call to a generic service
func isMakingAGenericCall(invoker protocol.Invoker, invocation protocol.Invocation) bool {
- return isGeneric(invoker.GetURL().GetParam(constant.GENERIC_KEY, "")) &&
- invocation.MethodName() == constant.GENERIC &&
+ return isGeneric(invoker.GetURL().GetParam(constant.GenericKey, "")) &&
+ invocation.MethodName() == constant.Generic &&
invocation.Arguments() != nil &&
len(invocation.Arguments()) == 3
}
@@ -50,7 +50,7 @@ func isGeneric(generic string) bool {
// isGenericInvocation determines if the invocation has generic format
func isGenericInvocation(invocation protocol.Invocation) bool {
- return invocation.MethodName() == constant.GENERIC &&
+ return invocation.MethodName() == constant.Generic &&
invocation.Arguments() != nil &&
len(invocation.Arguments()) == 3
}
diff --git a/filter/gshutdown/filter.go b/filter/gshutdown/filter.go
index 7b4a905..6d2b960 100644
--- a/filter/gshutdown/filter.go
+++ b/filter/gshutdown/filter.go
@@ -87,7 +87,7 @@ func (f *Filter) rejectNewRequest() bool {
}
func (f *Filter) getRejectHandler() filter.RejectedExecutionHandler {
- handler := constant.DEFAULT_KEY
+ handler := constant.DefaultKey
if f.shutdownConfig != nil && len(f.shutdownConfig.RejectRequestHandler) > 0 {
handler = f.shutdownConfig.RejectRequestHandler
}
diff --git a/filter/gshutdown/filter_test.go b/filter/gshutdown/filter_test.go
index b86ed4d..36ddccb 100644
--- a/filter/gshutdown/filter_test.go
+++ b/filter/gshutdown/filter_test.go
@@ -49,7 +49,7 @@ func TestGenericFilterInvoke(t *testing.T) {
assert.False(t, shutdownFilter.rejectNewRequest())
assert.Nil(t, rootConfig.Shutdown)
- assert.Equal(t, extension.GetRejectedExecutionHandler(constant.DEFAULT_KEY),
+ assert.Equal(t, extension.GetRejectedExecutionHandler(constant.DefaultKey),
shutdownFilter.getRejectHandler())
result := shutdownFilter.Invoke(context.Background(), protocol.NewBaseInvoker(invokeUrl), invoc)
diff --git a/filter/handler/rejected_execution_handler_only_log.go b/filter/handler/rejected_execution_handler_only_log.go
index c370fe6..ac541d3 100644
--- a/filter/handler/rejected_execution_handler_only_log.go
+++ b/filter/handler/rejected_execution_handler_only_log.go
@@ -38,7 +38,7 @@ const (
func init() {
// this implementation is the the default implementation of RejectedExecutionHandler
extension.SetRejectedExecutionHandler(HandlerName, GetOnlyLogRejectedExecutionHandler)
- extension.SetRejectedExecutionHandler(constant.DEFAULT_KEY, GetOnlyLogRejectedExecutionHandler)
+ extension.SetRejectedExecutionHandler(constant.DefaultKey, GetOnlyLogRejectedExecutionHandler)
}
var (
diff --git a/filter/handler/rejected_execution_handler_only_log_test.go b/filter/handler/rejected_execution_handler_only_log_test.go
index 9dd47c9..27e2fb7 100644
--- a/filter/handler/rejected_execution_handler_only_log_test.go
+++ b/filter/handler/rejected_execution_handler_only_log_test.go
@@ -31,6 +31,6 @@ func TestOnlyLogRejectedExecutionHandler_RejectedExecution(t *testing.T) {
handler := GetOnlyLogRejectedExecutionHandler()
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.INTERFACE_KEY, "methodName"))
+ common.WithParamsValue(constant.InterfaceKey, "methodName"))
handler.RejectedExecution(invokeUrl, nil)
}
diff --git a/filter/hystrix/filter_test.go b/filter/hystrix/filter_test.go
index 4718fa2..41a6ba6 100644
--- a/filter/hystrix/filter_test.go
+++ b/filter/hystrix/filter_test.go
@@ -152,7 +152,7 @@ func (iv *testMockFailInvoker) Invoke(_ context.Context, _ protocol.Invocation)
func TestHystrixFilterInvokeSuccess(t *testing.T) {
hf := &Filter{}
testUrl, err := common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LocalHostValue, constant.DefaultPort))
assert.NoError(t, err)
testInvoker := testMockSuccessInvoker{*protocol.NewBaseInvoker(testUrl)}
result := hf.Invoke(context.Background(), &testInvoker, &invocation.RPCInvocation{})
@@ -164,7 +164,7 @@ func TestHystrixFilterInvokeSuccess(t *testing.T) {
func TestHystrixFilterInvokeFail(t *testing.T) {
hf := &Filter{}
testUrl, err := common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LocalHostValue, constant.DefaultPort))
assert.NoError(t, err)
testInvoker := testMockFailInvoker{*protocol.NewBaseInvoker(testUrl)}
result := hf.Invoke(context.Background(), &testInvoker, &invocation.RPCInvocation{})
@@ -180,7 +180,7 @@ func TestHystricFilterInvokeCircuitBreak(t *testing.T) {
for i := 0; i < 50; i++ {
go func() {
testUrl, err := common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LocalHostValue, constant.DefaultPort))
assert.NoError(t, err)
testInvoker := testMockSuccessInvoker{*protocol.NewBaseInvoker(testUrl)}
result := hf.Invoke(context.Background(), &testInvoker, &invocation.RPCInvocation{})
@@ -208,7 +208,7 @@ func TestHystricFilterInvokeCircuitBreakOmitException(t *testing.T) {
for i := 0; i < 50; i++ {
go func() {
testUrl, err := common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LocalHostValue, constant.DefaultPort))
assert.NoError(t, err)
testInvoker := testMockSuccessInvoker{*protocol.NewBaseInvoker(testUrl)}
result := hf.Invoke(context.Background(), &testInvoker, &invocation.RPCInvocation{})
diff --git a/filter/sentinel/filter.go b/filter/sentinel/filter.go
index ceadb32..2bbb46c 100644
--- a/filter/sentinel/filter.go
+++ b/filter/sentinel/filter.go
@@ -243,6 +243,6 @@ func getInterfaceGroupAndVersionEnabled() bool {
func getColonSeparatedKey(url *common.URL) string {
return fmt.Sprintf("%s:%s:%s",
url.Service(),
- url.GetParam(constant.GROUP_KEY, ""),
- url.GetParam(constant.VERSION_KEY, ""))
+ url.GetParam(constant.GroupKey, ""),
+ url.GetParam(constant.VersionKey, ""))
}
diff --git a/filter/token/filter.go b/filter/token/filter.go
index 7362c2c..c7eba70 100644
--- a/filter/token/filter.go
+++ b/filter/token/filter.go
@@ -44,10 +44,10 @@ type Filter struct{}
// Invoke verifies the incoming token with the service configured token
func (f *Filter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
- invokerTkn := invoker.GetURL().GetParam(constant.TOKEN_KEY, "")
+ invokerTkn := invoker.GetURL().GetParam(constant.TokenKey, "")
if len(invokerTkn) > 0 {
attachs := invocation.Attachments()
- remoteTkn, exist := attachs[constant.TOKEN_KEY]
+ remoteTkn, exist := attachs[constant.TokenKey]
if exist && remoteTkn != nil && strings.EqualFold(invokerTkn, remoteTkn.(string)) {
return invoker.Invoke(ctx, invocation)
}
diff --git a/filter/token/filter_test.go b/filter/token/filter_test.go
index ddc44c2..10edd3f 100644
--- a/filter/token/filter_test.go
+++ b/filter/token/filter_test.go
@@ -39,9 +39,9 @@ func TestTokenFilterInvoke(t *testing.T) {
url := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.TOKEN_KEY, "ori_key"))
+ common.WithParamsValue(constant.TokenKey, "ori_key"))
attch := make(map[string]interface{})
- attch[constant.TOKEN_KEY] = "ori_key"
+ attch[constant.TokenKey] = "ori_key"
result := filter.Invoke(context.Background(),
protocol.NewBaseInvoker(url),
invocation.NewRPCInvocation("MethodName",
@@ -55,7 +55,7 @@ func TestTokenFilterInvokeEmptyToken(t *testing.T) {
testUrl := common.URL{}
attch := make(map[string]interface{})
- attch[constant.TOKEN_KEY] = "ori_key"
+ attch[constant.TokenKey] = "ori_key"
result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(&testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
assert.Nil(t, result.Error())
assert.Nil(t, result.Result())
@@ -66,7 +66,7 @@ func TestTokenFilterInvokeEmptyAttach(t *testing.T) {
testUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.TOKEN_KEY, "ori_key"))
+ common.WithParamsValue(constant.TokenKey, "ori_key"))
attch := make(map[string]interface{})
result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
assert.NotNil(t, result.Error())
@@ -77,9 +77,9 @@ func TestTokenFilterInvokeNotEqual(t *testing.T) {
testUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.TOKEN_KEY, "ori_key"))
+ common.WithParamsValue(constant.TokenKey, "ori_key"))
attch := make(map[string]interface{})
- attch[constant.TOKEN_KEY] = "err_key"
+ attch[constant.TokenKey] = "err_key"
result := filter.Invoke(context.Background(),
protocol.NewBaseInvoker(testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch))
assert.NotNil(t, result.Error())
diff --git a/filter/tps/filter.go b/filter/tps/filter.go
index 32a31ae..32f45f5 100644
--- a/filter/tps/filter.go
+++ b/filter/tps/filter.go
@@ -56,8 +56,8 @@ type Filter struct{}
// Invoke gets the configured limter to impose TPS limiting
func (t *Filter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
url := invoker.GetURL()
- tpsLimiter := url.GetParam(constant.TPS_LIMITER_KEY, "")
- rejectedExeHandler := url.GetParam(constant.TPS_REJECTED_EXECUTION_HANDLER_KEY, constant.DEFAULT_KEY)
+ tpsLimiter := url.GetParam(constant.TPSLimiterKey, "")
+ rejectedExeHandler := url.GetParam(constant.TPSRejectedExecutionHandlerKey, constant.DefaultKey)
if len(tpsLimiter) > 0 {
allow := extension.GetTpsLimiter(tpsLimiter).IsAllowable(invoker.GetURL(), invocation)
if allow {
diff --git a/filter/tps/filter_test.go b/filter/tps/filter_test.go
index 8e0a529..11f553d 100644
--- a/filter/tps/filter_test.go
+++ b/filter/tps/filter_test.go
@@ -44,7 +44,7 @@ func TestTpsLimitFilterInvokeWithNoTpsLimiter(t *testing.T) {
tpsFilter := &Filter{}
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.TPS_LIMITER_KEY, ""))
+ common.WithParamsValue(constant.TPSLimiterKey, ""))
attch := make(map[string]interface{})
result := tpsFilter.Invoke(context.Background(),
@@ -60,14 +60,14 @@ func TestGenericFilterInvokeWithDefaultTpsLimiter(t *testing.T) {
defer ctrl.Finish()
mockLimiter := limiter.NewMockTpsLimiter(ctrl)
mockLimiter.EXPECT().IsAllowable(gomock.Any(), gomock.Any()).Return(true).Times(1)
- extension.SetTpsLimiter(constant.DEFAULT_KEY, func() filter.TpsLimiter {
+ extension.SetTpsLimiter(constant.DefaultKey, func() filter.TpsLimiter {
return mockLimiter
})
tpsFilter := &Filter{}
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.TPS_LIMITER_KEY, constant.DEFAULT_KEY))
+ common.WithParamsValue(constant.TPSLimiterKey, constant.DefaultKey))
attch := make(map[string]interface{})
result := tpsFilter.Invoke(context.Background(),
@@ -83,7 +83,7 @@ func TestGenericFilterInvokeWithDefaultTpsLimiterNotAllow(t *testing.T) {
defer ctrl.Finish()
mockLimiter := limiter.NewMockTpsLimiter(ctrl)
mockLimiter.EXPECT().IsAllowable(gomock.Any(), gomock.Any()).Return(false).Times(1)
- extension.SetTpsLimiter(constant.DEFAULT_KEY, func() filter.TpsLimiter {
+ extension.SetTpsLimiter(constant.DefaultKey, func() filter.TpsLimiter {
return mockLimiter
})
@@ -91,14 +91,14 @@ func TestGenericFilterInvokeWithDefaultTpsLimiterNotAllow(t *testing.T) {
mockRejectedHandler := handler.NewMockRejectedExecutionHandler(ctrl)
mockRejectedHandler.EXPECT().RejectedExecution(gomock.Any(), gomock.Any()).Return(mockResult).Times(1)
- extension.SetRejectedExecutionHandler(constant.DEFAULT_KEY, func() filter.RejectedExecutionHandler {
+ extension.SetRejectedExecutionHandler(constant.DefaultKey, func() filter.RejectedExecutionHandler {
return mockRejectedHandler
})
tpsFilter := &Filter{}
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.TPS_LIMITER_KEY, constant.DEFAULT_KEY))
+ common.WithParamsValue(constant.TPSLimiterKey, constant.DefaultKey))
attch := make(map[string]interface{})
result := tpsFilter.Invoke(context.Background(),
diff --git a/filter/tps/limiter/method_service.go b/filter/tps/limiter/method_service.go
index ff3817c..41c16f8 100644
--- a/filter/tps/limiter/method_service.go
+++ b/filter/tps/limiter/method_service.go
@@ -40,7 +40,7 @@ const (
)
func init() {
- extension.SetTpsLimiter(constant.DEFAULT_KEY, GetMethodServiceTpsLimiter)
+ extension.SetTpsLimiter(constant.DefaultKey, GetMethodServiceTpsLimiter)
extension.SetTpsLimiter(name, GetMethodServiceTpsLimiter)
}
@@ -123,8 +123,8 @@ type MethodServiceTpsLimiter struct {
func (limiter MethodServiceTpsLimiter) IsAllowable(url *common.URL, invocation protocol.Invocation) bool {
methodConfigPrefix := "methods." + invocation.MethodName() + "."
- methodLimitRateConfig := url.GetParam(methodConfigPrefix+constant.TPS_LIMIT_RATE_KEY, "")
- methodIntervalConfig := url.GetParam(methodConfigPrefix+constant.TPS_LIMIT_INTERVAL_KEY, "")
+ methodLimitRateConfig := url.GetParam(methodConfigPrefix+constant.TPSLimitRateKey, "")
+ methodIntervalConfig := url.GetParam(methodConfigPrefix+constant.TPSLimitIntervalKey, "")
// service-level tps limit
limitTarget := url.ServiceKey()
@@ -145,8 +145,8 @@ func (limiter MethodServiceTpsLimiter) IsAllowable(url *common.URL, invocation p
// we could not find the limiter, and try to create one.
limitRate := getLimitConfig(methodLimitRateConfig, url, invocation,
- constant.TPS_LIMIT_RATE_KEY,
- constant.DEFAULT_TPS_LIMIT_RATE)
+ constant.TPSLimitRateKey,
+ constant.DefaultTPSLimitRate)
if limitRate < 0 {
// the limitTarget is not necessary to be limited.
@@ -154,15 +154,15 @@ func (limiter MethodServiceTpsLimiter) IsAllowable(url *common.URL, invocation p
}
limitInterval := getLimitConfig(methodIntervalConfig, url, invocation,
- constant.TPS_LIMIT_INTERVAL_KEY,
- constant.DEFAULT_TPS_LIMIT_INTERVAL)
+ constant.TPSLimitIntervalKey,
+ constant.DefaultTPSLimitInterval)
if limitInterval <= 0 {
panic(fmt.Sprintf("The interval must be positive, please check your configuration! url: %s", url.String()))
}
// find the strategy config and then create one
- limitStrategyConfig := url.GetParam(methodConfigPrefix+constant.TPS_LIMIT_STRATEGY_KEY,
- url.GetParam(constant.TPS_LIMIT_STRATEGY_KEY, constant.DEFAULT_KEY))
+ limitStrategyConfig := url.GetParam(methodConfigPrefix+constant.TPSLimitStrategyKey,
+ url.GetParam(constant.TPSLimitStrategyKey, constant.DefaultKey))
limitStateCreator := extension.GetTpsLimitStrategyCreator(limitStrategyConfig)
// we using loadOrStore to ensure thread-safe
diff --git a/filter/tps/limiter/method_service_test.go b/filter/tps/limiter/method_service_test.go
index df79def..21886fe 100644
--- a/filter/tps/limiter/method_service_test.go
+++ b/filter/tps/limiter/method_service_test.go
@@ -46,13 +46,13 @@ func TestMethodServiceTpsLimiterImplIsAllowableOnlyServiceLevel(t *testing.T) {
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.INTERFACE_KEY, methodName),
- common.WithParamsValue(constant.TPS_LIMIT_RATE_KEY, "20"))
+ common.WithParamsValue(constant.InterfaceKey, methodName),
+ common.WithParamsValue(constant.TPSLimitRateKey, "20"))
mockStrategyImpl := strategy.NewMockTpsLimitStrategy(ctrl)
mockStrategyImpl.EXPECT().IsAllowable().Return(true).Times(1)
- extension.SetTpsLimitStrategy(constant.DEFAULT_KEY, &mockStrategyCreator{
+ extension.SetTpsLimitStrategy(constant.DefaultKey, &mockStrategyCreator{
rate: 20,
interval: 60000,
t: t,
@@ -72,8 +72,8 @@ func TestMethodServiceTpsLimiterImplIsAllowableNoConfig(t *testing.T) {
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.INTERFACE_KEY, methodName),
- common.WithParamsValue(constant.TPS_LIMIT_RATE_KEY, ""))
+ common.WithParamsValue(constant.InterfaceKey, methodName),
+ common.WithParamsValue(constant.TPSLimitRateKey, ""))
limiter := GetMethodServiceTpsLimiter()
result := limiter.IsAllowable(invokeUrl, invoc)
@@ -89,19 +89,19 @@ func TestMethodServiceTpsLimiterImplIsAllowableMethodLevelOverride(t *testing.T)
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.INTERFACE_KEY, methodName),
- common.WithParamsValue(constant.TPS_LIMIT_RATE_KEY, "20"),
- common.WithParamsValue(constant.TPS_LIMIT_INTERVAL_KEY, "3000"),
- common.WithParamsValue(constant.TPS_LIMIT_STRATEGY_KEY, "invalid"),
- common.WithParamsValue(methodConfigPrefix+constant.TPS_LIMIT_RATE_KEY, "40"),
- common.WithParamsValue(methodConfigPrefix+constant.TPS_LIMIT_INTERVAL_KEY, "7000"),
- common.WithParamsValue(methodConfigPrefix+constant.TPS_LIMIT_STRATEGY_KEY, "default"),
+ common.WithParamsValue(constant.InterfaceKey, methodName),
+ common.WithParamsValue(constant.TPSLimitRateKey, "20"),
+ common.WithParamsValue(constant.TPSLimitIntervalKey, "3000"),
+ common.WithParamsValue(constant.TPSLimitStrategyKey, "invalid"),
+ common.WithParamsValue(methodConfigPrefix+constant.TPSLimitRateKey, "40"),
+ common.WithParamsValue(methodConfigPrefix+constant.TPSLimitIntervalKey, "7000"),
+ common.WithParamsValue(methodConfigPrefix+constant.TPSLimitStrategyKey, "default"),
)
mockStrategyImpl := strategy.NewMockTpsLimitStrategy(ctrl)
mockStrategyImpl.EXPECT().IsAllowable().Return(true).Times(1)
- extension.SetTpsLimitStrategy(constant.DEFAULT_KEY, &mockStrategyCreator{
+ extension.SetTpsLimitStrategy(constant.DefaultKey, &mockStrategyCreator{
rate: 40,
interval: 7000,
t: t,
@@ -122,16 +122,16 @@ func TestMethodServiceTpsLimiterImplIsAllowableBothMethodAndService(t *testing.T
invokeUrl := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.INTERFACE_KEY, methodName),
- common.WithParamsValue(constant.TPS_LIMIT_RATE_KEY, "20"),
- common.WithParamsValue(constant.TPS_LIMIT_INTERVAL_KEY, "3000"),
- common.WithParamsValue(methodConfigPrefix+constant.TPS_LIMIT_RATE_KEY, "40"),
+ common.WithParamsValue(constant.InterfaceKey, methodName),
+ common.WithParamsValue(constant.TPSLimitRateKey, "20"),
+ common.WithParamsValue(constant.TPSLimitIntervalKey, "3000"),
+ common.WithParamsValue(methodConfigPrefix+constant.TPSLimitRateKey, "40"),
)
mockStrategyImpl := strategy.NewMockTpsLimitStrategy(ctrl)
mockStrategyImpl.EXPECT().IsAllowable().Return(true).Times(1)
- extension.SetTpsLimitStrategy(constant.DEFAULT_KEY, &mockStrategyCreator{
+ extension.SetTpsLimitStrategy(constant.DefaultKey, &mockStrategyCreator{
rate: 40,
interval: 3000,
t: t,
diff --git a/filter/tps/strategy/fix_window.go b/filter/tps/strategy/fix_window.go
index 043e5bf..8b34bf9 100644
--- a/filter/tps/strategy/fix_window.go
+++ b/filter/tps/strategy/fix_window.go
@@ -36,7 +36,7 @@ const (
func init() {
creator := &fixedWindowStrategyCreator{}
extension.SetTpsLimitStrategy(FixedWindowKey, creator)
- extension.SetTpsLimitStrategy(constant.DEFAULT_KEY, creator)
+ extension.SetTpsLimitStrategy(constant.DefaultKey, creator)
}
// FixedWindowTpsLimitStrategy implements the TPS limit strategy base on requests count during the interval
diff --git a/filter/tracing/filter.go b/filter/tracing/filter.go
index 0966966..920e659 100644
--- a/filter/tracing/filter.go
+++ b/filter/tracing/filter.go
@@ -55,7 +55,7 @@ func (tf *tracingFilter) Invoke(ctx context.Context, invoker protocol.Invoker, i
)
operationName := invoker.GetURL().ServiceKey() + "#" + invocation.MethodName()
- wiredCtx := ctx.Value(constant.TRACING_REMOTE_SPAN_CTX)
+ wiredCtx := ctx.Value(constant.TracingRemoteSpanCtx)
preSpan := opentracing.SpanFromContext(ctx)
if preSpan != nil {
diff --git a/filter/tracing/filter_test.go b/filter/tracing/filter_test.go
index 9d28393..e56ab7b 100644
--- a/filter/tracing/filter_test.go
+++ b/filter/tracing/filter_test.go
@@ -57,6 +57,6 @@ func TestTracingFilterInvoke(t *testing.T) {
tf.Invoke(ctx, invoker, inv)
// has remote ctx
- ctx = context.WithValue(context.Background(), constant.DubboCtxKey(constant.TRACING_REMOTE_SPAN_CTX), span.Context())
+ ctx = context.WithValue(context.Background(), constant.DubboCtxKey(constant.TracingRemoteSpanCtx), span.Context())
tf.Invoke(ctx, invoker, inv)
}
diff --git a/metadata/definition/definition.go b/metadata/definition/definition.go
index 1278416..695ca84 100644
--- a/metadata/definition/definition.go
+++ b/metadata/definition/definition.go
@@ -126,11 +126,11 @@ func ServiceDescriperBuild(serviceName string, group string, version string) str
buf := &bytes.Buffer{}
if group != "" {
buf.WriteString(group)
- buf.WriteString(constant.PATH_SEPARATOR)
+ buf.WriteString(constant.PathSeparator)
}
buf.WriteString(serviceName)
if version != "" && version != "0.0.0" {
- buf.WriteString(constant.KEY_SEPARATOR)
+ buf.WriteString(constant.KeySeparator)
buf.WriteString(version)
}
return buf.String()
diff --git a/metadata/identifier/base_metadata_identifier.go b/metadata/identifier/base_metadata_identifier.go
index 9659e45..6bb3c28 100644
--- a/metadata/identifier/base_metadata_identifier.go
+++ b/metadata/identifier/base_metadata_identifier.go
@@ -52,27 +52,27 @@ func joinParams(joinChar string, params []string) string {
// getIdentifierKey returns string that format is service:Version:Group:Side:param1:param2...
func (mdi *BaseMetadataIdentifier) getIdentifierKey(params ...string) string {
return mdi.ServiceInterface +
- constant.KEY_SEPARATOR + mdi.Version +
- constant.KEY_SEPARATOR + mdi.Group +
- constant.KEY_SEPARATOR + mdi.Side +
- joinParams(constant.KEY_SEPARATOR, params)
+ constant.KeySeparator + mdi.Version +
+ constant.KeySeparator + mdi.Group +
+ constant.KeySeparator + mdi.Side +
+ joinParams(constant.KeySeparator, params)
}
// getFilePathKey returns string that format is metadata/path/Version/Group/Side/param1/param2...
func (mdi *BaseMetadataIdentifier) getFilePathKey(params ...string) string {
path := serviceToPath(mdi.ServiceInterface)
- return constant.DEFAULT_PATH_TAG +
+ return constant.DefaultPathTag +
withPathSeparator(path) +
withPathSeparator(mdi.Version) +
withPathSeparator(mdi.Group) +
withPathSeparator(mdi.Side) +
- joinParams(constant.PATH_SEPARATOR, params)
+ joinParams(constant.PathSeparator, params)
}
// serviceToPath uss URL encode to decode the @serviceInterface
func serviceToPath(serviceInterface string) string {
- if serviceInterface == constant.ANY_VALUE {
+ if serviceInterface == constant.AnyValue {
return ""
}
return url.PathEscape(serviceInterface)
@@ -81,7 +81,7 @@ func serviceToPath(serviceInterface string) string {
// withPathSeparator return "/" + @path
func withPathSeparator(path string) string {
if len(path) != 0 {
- path = constant.PATH_SEPARATOR + path
+ path = constant.PathSeparator + path
}
return path
}
@@ -94,12 +94,12 @@ type BaseApplicationMetadataIdentifier struct {
// getIdentifierKey returns string that format is application/param
func (madi *BaseApplicationMetadataIdentifier) getIdentifierKey(params ...string) string {
- return madi.Application + joinParams(constant.KEY_SEPARATOR, params)
+ return madi.Application + joinParams(constant.KeySeparator, params)
}
// getFilePathKey returns string that format is metadata/application/revision
func (madi *BaseApplicationMetadataIdentifier) getFilePathKey(params ...string) string {
- return constant.DEFAULT_PATH_TAG +
+ return constant.DefaultPathTag +
withPathSeparator(madi.Application) +
- joinParams(constant.PATH_SEPARATOR, params)
+ joinParams(constant.PathSeparator, params)
}
diff --git a/metadata/identifier/service_metadata_identifier.go b/metadata/identifier/service_metadata_identifier.go
index b8e56ad..f555e22 100644
--- a/metadata/identifier/service_metadata_identifier.go
+++ b/metadata/identifier/service_metadata_identifier.go
@@ -36,9 +36,9 @@ func NewServiceMetadataIdentifier(url *common.URL) *ServiceMetadataIdentifier {
return &ServiceMetadataIdentifier{
BaseMetadataIdentifier: BaseMetadataIdentifier{
ServiceInterface: url.Service(),
- Version: url.GetParam(constant.VERSION_KEY, ""),
- Group: url.GetParam(constant.GROUP_KEY, ""),
- Side: url.GetParam(constant.SIDE_KEY, ""),
+ Version: url.GetParam(constant.VersionKey, ""),
+ Group: url.GetParam(constant.GroupKey, ""),
+ Side: url.GetParam(constant.SideKey, ""),
},
Protocol: url.Protocol,
}
@@ -46,10 +46,10 @@ func NewServiceMetadataIdentifier(url *common.URL) *ServiceMetadataIdentifier {
// GetIdentifierKey returns string that format is service:Version:Group:Side:Protocol:"revision"+Revision
func (mdi *ServiceMetadataIdentifier) GetIdentifierKey() string {
- return mdi.BaseMetadataIdentifier.getIdentifierKey(mdi.Protocol, constant.KEY_REVISON_PREFIX+mdi.Revision)
+ return mdi.BaseMetadataIdentifier.getIdentifierKey(mdi.Protocol, constant.KeyRevisionPrefix+mdi.Revision)
}
// GetFilePathKey returns string that format is metadata/path/Version/Group/Side/Protocol/"revision"+Revision
func (mdi *ServiceMetadataIdentifier) GetFilePathKey() string {
- return mdi.BaseMetadataIdentifier.getFilePathKey(mdi.Protocol, constant.KEY_REVISON_PREFIX+mdi.Revision)
+ return mdi.BaseMetadataIdentifier.getFilePathKey(mdi.Protocol, constant.KeyRevisionPrefix+mdi.Revision)
}
diff --git a/metadata/identifier/subscribe_metadata_identifier.go b/metadata/identifier/subscribe_metadata_identifier.go
index ee83b5a..1e0c5e3 100644
--- a/metadata/identifier/subscribe_metadata_identifier.go
+++ b/metadata/identifier/subscribe_metadata_identifier.go
@@ -32,7 +32,7 @@ func NewSubscriberMetadataIdentifier(application string, revision string) *Subsc
Revision: revision,
BaseApplicationMetadataIdentifier: BaseApplicationMetadataIdentifier{
Application: application,
- Group: constant.DUBBO,
+ Group: constant.Dubbo,
},
}
}
diff --git a/metadata/mapping/metadata/service_name_mapping.go b/metadata/mapping/metadata/service_name_mapping.go
index f155aa9..550fc4f 100644
--- a/metadata/mapping/metadata/service_name_mapping.go
+++ b/metadata/mapping/metadata/service_name_mapping.go
@@ -53,9 +53,9 @@ type MetadataServiceNameMapping struct {
// Map will map the service to this application-level service
func (d *MetadataServiceNameMapping) Map(url *common.URL) error {
- serviceInterface := url.GetParam(constant.INTERFACE_KEY, "")
+ serviceInterface := url.GetParam(constant.InterfaceKey, "")
// metadata service is admin service, should not be mapped
- if constant.METADATA_SERVICE_NAME == serviceInterface {
+ if constant.MetadataServiceName == serviceInterface {
logger.Info("try to map the metadata service, will be ignored")
return nil
}
@@ -71,7 +71,7 @@ func (d *MetadataServiceNameMapping) Map(url *common.URL) error {
// Get will return the application-level services. If not found, the empty set will be returned.
func (d *MetadataServiceNameMapping) Get(url *common.URL) (*gxset.HashSet, error) {
- serviceInterface := url.GetParam(constant.INTERFACE_KEY, "")
+ serviceInterface := url.GetParam(constant.InterfaceKey, "")
metadataReport := instance.GetMetadataReportInstance()
return metadataReport.GetServiceAppMapping(serviceInterface, defaultGroup)
}
diff --git a/metadata/report/delegate/delegate_report.go b/metadata/report/delegate/delegate_report.go
index 536da6b..96e902d 100644
--- a/metadata/report/delegate/delegate_report.go
+++ b/metadata/report/delegate/delegate_report.go
@@ -117,14 +117,14 @@ func NewMetadataReport() (*MetadataReport, error) {
}
bmr := &MetadataReport{
reportUrl: url,
- syncReport: url.GetParamBool(constant.SYNC_REPORT_KEY, false),
+ syncReport: url.GetParamBool(constant.SyncReportKey, false),
failedReports: make(map[*identifier.MetadataIdentifier]interface{}, 4),
allMetadataReports: make(map[*identifier.MetadataIdentifier]interface{}, 4),
}
mrr, err := newMetadataReportRetry(
- url.GetParamInt(constant.RETRY_PERIOD_KEY, defaultMetadataReportRetryPeriod),
- url.GetParamInt(constant.RETRY_TIMES_KEY, defaultMetadataReportRetryTimes),
+ url.GetParamInt(constant.RetryPeriodKey, defaultMetadataReportRetryPeriod),
+ url.GetParamInt(constant.RetryTimesKey, defaultMetadataReportRetryTimes),
bmr.retry,
)
if err != nil {
@@ -132,7 +132,7 @@ func NewMetadataReport() (*MetadataReport, error) {
}
bmr.metadataReportRetry = mrr
- if url.GetParamBool(constant.CYCLE_REPORT_KEY, defaultMetadataReportCycleReport) {
+ if url.GetParamBool(constant.CycleReportKey, defaultMetadataReportCycleReport) {
scheduler := gocron.NewScheduler(time.UTC)
_, err := scheduler.Every(1).Day().Do(
func() {
diff --git a/metadata/report/delegate/delegate_report_test.go b/metadata/report/delegate/delegate_report_test.go
index 5d2b40b..631e6c0 100644
--- a/metadata/report/delegate/delegate_report_test.go
+++ b/metadata/report/delegate/delegate_report_test.go
@@ -75,8 +75,8 @@ func mockNewMetadataReport(t *testing.T) *MetadataReport {
cycleReportKey := "true"
url, err := common.NewURL(fmt.Sprintf(
- "test://127.0.0.1:20000/?"+constant.SYNC_REPORT_KEY+"=%v&"+constant.RETRY_PERIOD_KEY+"=%v&"+
- constant.RETRY_TIMES_KEY+"=%v&"+constant.CYCLE_REPORT_KEY+"=%v",
+ "test://127.0.0.1:20000/?"+constant.SyncReportKey+"=%v&"+constant.RetryPeriodKey+"=%v&"+
+ constant.RetryTimesKey+"=%v&"+constant.CycleReportKey+"=%v",
syncReportKey, retryPeriodKey, retryTimesKey, cycleReportKey))
assert.NoError(t, err)
instance.SetMetadataReportUrl(url)
diff --git a/metadata/report/etcd/report.go b/metadata/report/etcd/report.go
index a677b76..ee439d6 100644
--- a/metadata/report/etcd/report.go
+++ b/metadata/report/etcd/report.go
@@ -42,7 +42,7 @@ import (
const DEFAULT_ROOT = "dubbo"
func init() {
- extension.SetMetadataReportFactory(constant.ETCDV3_KEY, func() factory.MetadataReportFactory {
+ extension.SetMetadataReportFactory(constant.EtcdV3Key, func() factory.MetadataReportFactory {
return &etcdMetadataReportFactory{}
})
}
@@ -146,7 +146,7 @@ func (e *etcdMetadataReport) GetServiceDefinition(metadataIdentifier *identifier
// RegisterServiceAppMapping map the specified Dubbo service interface to current Dubbo app name
func (e *etcdMetadataReport) RegisterServiceAppMapping(key string, group string, value string) error {
- path := e.root + constant.PATH_SEPARATOR + group + constant.PATH_SEPARATOR + key
+ path := e.root + constant.PathSeparator + group + constant.PathSeparator + key
oldVal, err := e.client.Get(path)
if perrors.Cause(err) == gxetcd.ErrKVPairNotFound {
return e.client.Put(path, value)
@@ -156,18 +156,18 @@ func (e *etcdMetadataReport) RegisterServiceAppMapping(key string, group string,
if strings.Contains(oldVal, value) {
return nil
}
- value = oldVal + constant.COMMA_SEPARATOR + value
+ value = oldVal + constant.CommaSeparator + value
return e.client.Put(path, value)
}
// GetServiceAppMapping get the app names from the specified Dubbo service interface
func (e *etcdMetadataReport) GetServiceAppMapping(key string, group string) (*gxset.HashSet, error) {
- path := e.root + constant.PATH_SEPARATOR + group + constant.PATH_SEPARATOR + key
+ path := e.root + constant.PathSeparator + group + constant.PathSeparator + key
v, err := e.client.Get(path)
if err != nil {
return nil, err
}
- appNames := strings.Split(v, constant.COMMA_SEPARATOR)
+ appNames := strings.Split(v, constant.CommaSeparator)
set := gxset.NewSet()
for _, app := range appNames {
set.Add(app)
@@ -179,24 +179,24 @@ type etcdMetadataReportFactory struct{}
// CreateMetadataReport get the MetadataReport instance of etcd
func (e *etcdMetadataReportFactory) CreateMetadataReport(url *common.URL) report.MetadataReport {
- timeout := url.GetParamDuration(constant.CONFIG_TIMEOUT_KEY, constant.DEFAULT_REG_TIMEOUT)
+ timeout := url.GetParamDuration(constant.ConfigTimeoutKey, constant.DefaultRegTimeout)
addresses := strings.Split(url.Location, ",")
client, err := gxetcd.NewClient(gxetcd.MetadataETCDV3Client, addresses, timeout, 1)
if err != nil {
logger.Errorf("Could not create etcd metadata report. URL: %s,error:{%v}", url.String(), err)
return nil
}
- group := url.GetParam(constant.GROUP_KEY, DEFAULT_ROOT)
- group = constant.PATH_SEPARATOR + strings.TrimPrefix(group, constant.PATH_SEPARATOR)
+ group := url.GetParam(constant.GroupKey, DEFAULT_ROOT)
+ group = constant.PathSeparator + strings.TrimPrefix(group, constant.PathSeparator)
return &etcdMetadataReport{client: client, root: group}
}
func (e *etcdMetadataReport) getNodeKey(MetadataIdentifier identifier.IMetadataIdentifier) string {
var rootDir string
- if e.root == constant.PATH_SEPARATOR {
+ if e.root == constant.PathSeparator {
rootDir = e.root
} else {
- rootDir = e.root + constant.PATH_SEPARATOR
+ rootDir = e.root + constant.PathSeparator
}
return rootDir + MetadataIdentifier.GetFilePathKey()
}
diff --git a/metadata/report/etcd/report_test.go b/metadata/report/etcd/report_test.go
index aed380b..8453db0 100644
--- a/metadata/report/etcd/report_test.go
+++ b/metadata/report/etcd/report_test.go
@@ -56,7 +56,7 @@ func initEtcd(t *testing.T) *embed.Etcd {
func TestEtcdMetadataReportFactory_CreateMetadataReport(t *testing.T) {
e := initEtcd(t)
- url, err := common.NewURL("registry://127.0.0.1:2379", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
+ url, err := common.NewURL("registry://127.0.0.1:2379", common.WithParamsValue(constant.RoleKey, strconv.Itoa(common.PROVIDER)))
if err != nil {
t.Fatal(err)
}
@@ -68,7 +68,7 @@ func TestEtcdMetadataReportFactory_CreateMetadataReport(t *testing.T) {
func TestEtcdMetadataReport_CRUD(t *testing.T) {
e := initEtcd(t)
- url, err := common.NewURL("registry://127.0.0.1:2379", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
+ url, err := common.NewURL("registry://127.0.0.1:2379", common.WithParamsValue(constant.RoleKey, strconv.Itoa(common.PROVIDER)))
if err != nil {
t.Fatal(err)
}
@@ -83,7 +83,7 @@ func TestEtcdMetadataReport_CRUD(t *testing.T) {
assert.Nil(t, err)
serviceMi := newServiceMetadataIdentifier()
- serviceUrl, err := common.NewURL("registry://localhost:8848", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
+ serviceUrl, err := common.NewURL("registry://localhost:8848", common.WithParamsValue(constant.RoleKey, strconv.Itoa(common.PROVIDER)))
assert.Nil(t, err)
err = metadataReport.SaveServiceMetadata(serviceMi, serviceUrl)
assert.Nil(t, err)
@@ -116,7 +116,7 @@ func TestEtcdMetadataReport_CRUD(t *testing.T) {
func TestEtcdMetadataReport_ServiceAppMapping(t *testing.T) {
e := initEtcd(t)
- url, err := common.NewURL("registry://127.0.0.1:2379", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
+ url, err := common.NewURL("registry://127.0.0.1:2379", common.WithParamsValue(constant.RoleKey, strconv.Itoa(common.PROVIDER)))
if err != nil {
t.Fatal(err)
}
diff --git a/metadata/report/nacos/report.go b/metadata/report/nacos/report.go
index 37e17d2..645dc78 100644
--- a/metadata/report/nacos/report.go
+++ b/metadata/report/nacos/report.go
@@ -222,7 +222,7 @@ func (n *nacosMetadataReport) RegisterServiceAppMapping(key string, group string
return nil
}
if oldVal != "" {
- value = oldVal + constant.COMMA_SEPARATOR + value
+ value = oldVal + constant.CommaSeparator + value
}
return n.storeMetadata(vo.ConfigParam{
DataId: key,
@@ -243,7 +243,7 @@ func (n *nacosMetadataReport) GetServiceAppMapping(key string, group string) (*g
if v == "" {
return nil, perrors.New("There is no service app mapping data.")
}
- appNames := strings.Split(v, constant.COMMA_SEPARATOR)
+ appNames := strings.Split(v, constant.CommaSeparator)
set := gxset.NewSet()
for _, e := range appNames {
set.Add(e)
diff --git a/metadata/report/nacos/report_test.go b/metadata/report/nacos/report_test.go
index 2f5e375..a261e15 100644
--- a/metadata/report/nacos/report_test.go
+++ b/metadata/report/nacos/report_test.go
@@ -54,7 +54,7 @@ func TestNacosMetadataReport_CRUD(t *testing.T) {
assert.Nil(t, err)
serviceMi := newServiceMetadataIdentifier()
- serviceUrl, _ := common.NewURL("registry://console.nacos.io:80", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
+ serviceUrl, _ := common.NewURL("registry://console.nacos.io:80", common.WithParamsValue(constant.RoleKey, strconv.Itoa(common.PROVIDER)))
err = rpt.SaveServiceMetadata(serviceMi, serviceUrl)
assert.Nil(t, err)
@@ -97,7 +97,7 @@ func TestNacosMetadataReportFactory_CreateMetadataReport(t *testing.T) {
}
func newTestReport() report.MetadataReport {
- regurl, _ := common.NewURL("registry://console.nacos.io:80", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
+ regurl, _ := common.NewURL("registry://console.nacos.io:80", common.WithParamsValue(constant.RoleKey, strconv.Itoa(common.PROVIDER)))
res := extension.GetMetadataReportFactory("nacos").CreateMetadataReport(regurl)
return res
}
diff --git a/metadata/report/zookeeper/report.go b/metadata/report/zookeeper/report.go
index 4402d61..2a665f9 100644
--- a/metadata/report/zookeeper/report.go
+++ b/metadata/report/zookeeper/report.go
@@ -145,7 +145,7 @@ func (m *zookeeperMetadataReport) GetServiceDefinition(metadataIdentifier *ident
// RegisterServiceAppMapping map the specified Dubbo service interface to current Dubbo app name
func (m *zookeeperMetadataReport) RegisterServiceAppMapping(key string, group string, value string) error {
- path := m.rootDir + group + constant.PATH_SEPARATOR + key
+ path := m.rootDir + group + constant.PathSeparator + key
v, state, err := m.client.GetContent(path)
if err == zk.ErrNoNode {
return m.client.CreateWithValue(path, []byte(value))
@@ -156,19 +156,19 @@ func (m *zookeeperMetadataReport) RegisterServiceAppMapping(key string, group st
if strings.Contains(oldValue, value) {
return nil
}
- value = oldValue + constant.COMMA_SEPARATOR + value
+ value = oldValue + constant.CommaSeparator + value
_, err = m.client.SetContent(path, []byte(value), state.Version)
return err
}
// GetServiceAppMapping get the app names from the specified Dubbo service interface
func (m *zookeeperMetadataReport) GetServiceAppMapping(key string, group string) (*gxset.HashSet, error) {
- path := m.rootDir + group + constant.PATH_SEPARATOR + key
+ path := m.rootDir + group + constant.PathSeparator + key
v, _, err := m.client.GetContent(path)
if err != nil {
return nil, err
}
- appNames := strings.Split(string(v), constant.COMMA_SEPARATOR)
+ appNames := strings.Split(string(v), constant.CommaSeparator)
set := gxset.NewSet()
for _, e := range appNames {
set.Add(e)
@@ -190,12 +190,12 @@ func (mf *zookeeperMetadataReportFactory) CreateMetadataReport(url *common.URL)
panic(err)
}
- rootDir := url.GetParam(constant.GROUP_KEY, "dubbo")
- if !strings.HasPrefix(rootDir, constant.PATH_SEPARATOR) {
- rootDir = constant.PATH_SEPARATOR + rootDir
+ rootDir := url.GetParam(constant.GroupKey, "dubbo")
+ if !strings.HasPrefix(rootDir, constant.PathSeparator) {
+ rootDir = constant.PathSeparator + rootDir
}
- if rootDir != constant.PATH_SEPARATOR {
- rootDir = rootDir + constant.PATH_SEPARATOR
+ if rootDir != constant.PathSeparator {
+ rootDir = rootDir + constant.PathSeparator
}
return &zookeeperMetadataReport{client: client, rootDir: rootDir}
diff --git a/metadata/service/exporter/configurable/exporter.go b/metadata/service/exporter/configurable/exporter.go
index 5675b65..84a9449 100644
--- a/metadata/service/exporter/configurable/exporter.go
+++ b/metadata/service/exporter/configurable/exporter.go
@@ -42,7 +42,7 @@ type MetadataServiceExporter struct {
}
func init() {
- extension.SetMetadataServiceExporter(constant.DEFAULT_Key, NewMetadataServiceExporter)
+ extension.SetMetadataServiceExporter(constant.DefaultKey, NewMetadataServiceExporter)
}
// NewMetadataServiceExporter will return a service_exporter.MetadataServiceExporter with the specified metadata service
@@ -59,17 +59,17 @@ func (exporter *MetadataServiceExporter) Export(url *common.URL) error {
exporter.lock.Lock()
defer exporter.lock.Unlock()
exporter.ServiceConfig = config.NewServiceConfigBuilder().
- SetServiceID(constant.SIMPLE_METADATA_SERVICE_NAME).
- SetProtocolIDs(constant.DEFAULT_PROTOCOL).
- AddRCProtocol(constant.DEFAULT_PROTOCOL, config.NewProtocolConfigBuilder().
- SetName(constant.DEFAULT_PROTOCOL).
+ SetServiceID(constant.SimpleMetadataServiceName).
+ SetProtocolIDs(constant.DefaultProtocol).
+ AddRCProtocol(constant.DefaultProtocol, config.NewProtocolConfigBuilder().
+ SetName(constant.DefaultProtocol).
Build()).
SetRegistryIDs("N/A").
- SetInterface(constant.METADATA_SERVICE_NAME).
+ SetInterface(constant.MetadataServiceName).
SetGroup(config.GetApplicationConfig().Name).
SetVersion(version).
- SetProxyFactoryKey(constant.DEFAULT_Key).
- SetMetadataType(constant.REMOTE_METADATA_STORAGE_TYPE).
+ SetProxyFactoryKey(constant.DefaultKey).
+ SetMetadataType(constant.RemoteMetadataStorageType).
Build()
exporter.ServiceConfig.Implement(exporter.metadataService)
err := exporter.ServiceConfig.Export()
diff --git a/metadata/service/local/metadata_service_proxy_factory.go b/metadata/service/local/metadata_service_proxy_factory.go
index e6e2f40..ee9c292 100644
--- a/metadata/service/local/metadata_service_proxy_factory.go
+++ b/metadata/service/local/metadata_service_proxy_factory.go
@@ -33,7 +33,7 @@ import (
func init() {
factory := service.NewBaseMetadataServiceProxyFactory(createProxy)
- extension.SetMetadataServiceProxyFactory(constant.DEFAULT_KEY, func() service.MetadataServiceProxyFactory {
+ extension.SetMetadataServiceProxyFactory(constant.DefaultKey, func() service.MetadataServiceProxyFactory {
return factory
})
}
@@ -72,7 +72,7 @@ func createProxy(ins registry.ServiceInstance) service.MetadataService {
// buildStandardMetadataServiceURL will use standard format to build the metadata service url.
func buildStandardMetadataServiceURL(ins registry.ServiceInstance) []*common.URL {
ps := getMetadataServiceUrlParams(ins)
- if ps[constant.PROTOCOL_KEY] == "" {
+ if ps[constant.ProtocolKey] == "" {
return nil
}
res := make([]*common.URL, 0, len(ps))
@@ -83,12 +83,12 @@ func buildStandardMetadataServiceURL(ins registry.ServiceInstance) []*common.URL
convertedParams[k] = []string{v}
}
u := common.NewURLWithOptions(common.WithIp(host),
- common.WithPath(constant.METADATA_SERVICE_NAME),
- common.WithProtocol(ps[constant.PROTOCOL_KEY]),
- common.WithPort(ps[constant.PORT_KEY]),
+ common.WithPath(constant.MetadataServiceName),
+ common.WithProtocol(ps[constant.ProtocolKey]),
+ common.WithPort(ps[constant.PortKey]),
common.WithParams(convertedParams),
- common.WithParamsValue(constant.GROUP_KEY, sn),
- common.WithParamsValue(constant.INTERFACE_KEY, constant.METADATA_SERVICE_NAME))
+ common.WithParamsValue(constant.GroupKey, sn),
+ common.WithParamsValue(constant.InterfaceKey, constant.MetadataServiceName))
res = append(res, u)
return res
@@ -100,7 +100,7 @@ func buildStandardMetadataServiceURL(ins registry.ServiceInstance) []*common.URL
func getMetadataServiceUrlParams(ins registry.ServiceInstance) map[string]string {
ps := ins.GetMetadata()
res := make(map[string]string, 2)
- if str, ok := ps[constant.METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME]; ok && len(str) > 0 {
+ if str, ok := ps[constant.MetadataServiceURLParamsPropertyName]; ok && len(str) > 0 {
err := json.Unmarshal([]byte(str), &res)
if err != nil {
diff --git a/metadata/service/local/metadata_service_proxy_factory_test.go b/metadata/service/local/metadata_service_proxy_factory_test.go
index b20ca93..95665ba 100644
--- a/metadata/service/local/metadata_service_proxy_factory_test.go
+++ b/metadata/service/local/metadata_service_proxy_factory_test.go
@@ -57,7 +57,7 @@ func TestCreateProxy(t *testing.T) {
pxy := createProxy(ins)
assert.Nil(t, pxy)
- ins.Metadata = map[string]string{constant.METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME: `{"protocol":"mock","timeout":"10000","version":"1.0.0","dubbo":"2.0.2","release":"2.7.6","port":"20880"}`}
+ ins.Metadata = map[string]string{constant.MetadataServiceURLParamsPropertyName: `{"protocol":"mock","timeout":"10000","version":"1.0.0","dubbo":"2.0.2","release":"2.7.6","port":"20880"}`}
pxy = createProxy(ins)
assert.NotNil(t, pxy)
}
diff --git a/metadata/service/local/service.go b/metadata/service/local/service.go
index c5c1418..3a0f94d 100644
--- a/metadata/service/local/service.go
+++ b/metadata/service/local/service.go
@@ -36,7 +36,7 @@ import (
)
func init() {
- extension.SetLocalMetadataService(constant.DEFAULT_KEY, GetLocalMetadataService)
+ extension.SetLocalMetadataService(constant.DefaultKey, GetLocalMetadataService)
}
// version will be used by Version func
@@ -128,7 +128,7 @@ func (mts *MetadataService) getAllService(services *sync.Map) []*common.URL {
urls := value.(*skip.SkipList)
for i := uint64(0); i < urls.Len(); i++ {
url := urls.ByPosition(i).(*common.URL)
- if url.Service() != constant.METADATA_SERVICE_NAME {
+ if url.Service() != constant.MetadataServiceName {
res = append(res, url)
}
}
@@ -146,7 +146,7 @@ func (mts *MetadataService) getSpecifiedService(services *sync.Map, serviceKey s
urls := serviceList.(*skip.SkipList)
for i := uint64(0); i < urls.Len(); i++ {
url := urls.ByPosition(i).(*common.URL)
- if len(protocol) == 0 || protocol == constant.ANY_VALUE || url.Protocol == protocol || url.GetParam(constant.PROTOCOL_KEY, "") == protocol {
+ if len(protocol) == 0 || protocol == constant.AnyValue || url.Protocol == protocol || url.GetParam(constant.ProtocolKey, "") == protocol {
res = append(res, url)
}
}
@@ -157,7 +157,7 @@ func (mts *MetadataService) getSpecifiedService(services *sync.Map, serviceKey s
// ExportURL can store the in memory
func (mts *MetadataService) ExportURL(url *common.URL) (bool, error) {
- if constant.METADATA_SERVICE_NAME == url.GetParam(constant.INTERFACE_KEY, "") {
+ if constant.MetadataServiceName == url.GetParam(constant.InterfaceKey, "") {
mts.metadataServiceURL = url
return true, nil
}
@@ -170,7 +170,7 @@ func (mts *MetadataService) ExportURL(url *common.URL) (bool, error) {
// UnexportURL can remove the url store in memory
func (mts *MetadataService) UnexportURL(url *common.URL) error {
- if constant.METADATA_SERVICE_NAME == url.GetParam(constant.INTERFACE_KEY, "") {
+ if constant.MetadataServiceName == url.GetParam(constant.InterfaceKey, "") {
mts.metadataServiceURL = nil
return nil
}
@@ -194,11 +194,11 @@ func (mts *MetadataService) UnsubscribeURL(url *common.URL) error {
// PublishServiceDefinition: publish url's service metadata info, and write into memory
func (mts *MetadataService) PublishServiceDefinition(url *common.URL) error {
- if common.RoleType(common.CONSUMER).Role() == url.GetParam(constant.SIDE_KEY, "") {
+ if common.RoleType(common.CONSUMER).Role() == url.GetParam(constant.SideKey, "") {
return nil
}
- interfaceName := url.GetParam(constant.INTERFACE_KEY, "")
- isGeneric := url.GetParamBool(constant.GENERIC_KEY, false)
+ interfaceName := url.GetParam(constant.InterfaceKey, "")
+ isGeneric := url.GetParamBool(constant.GenericKey, false)
if len(interfaceName) > 0 && !isGeneric {
tmpService := common.ServiceMap.GetServiceByServiceKey(url.Protocol, url.ServiceKey())
sd := definition.BuildServiceDefinition(*tmpService, url)
@@ -216,7 +216,7 @@ func (mts *MetadataService) PublishServiceDefinition(url *common.URL) error {
// GetExportedURLs get all exported urls
func (mts *MetadataService) GetExportedURLs(serviceInterface string, group string, version string, protocol string) ([]*common.URL, error) {
- if serviceInterface == constant.ANY_VALUE {
+ if serviceInterface == constant.AnyValue {
return mts.getAllService(mts.exportedServiceURLs), nil
} else {
serviceKey := definition.ServiceDescriperBuild(serviceInterface, group, version)
diff --git a/metadata/service/local/service_proxy.go b/metadata/service/local/service_proxy.go
index 03c71aa..4d6555f 100644
--- a/metadata/service/local/service_proxy.go
+++ b/metadata/service/local/service_proxy.go
@@ -55,7 +55,7 @@ func (m *MetadataServiceProxy) GetExportedURLs(serviceInterface string, group st
inv := invocation.NewRPCInvocationWithOptions(invocation.WithMethodName(methodName),
invocation.WithArguments([]interface{}{siV.Interface(), gV.Interface(), vV.Interface(), pV.Interface()}),
invocation.WithReply(reflect.ValueOf(&[]interface{}{}).Interface()),
- invocation.WithAttachments(map[string]interface{}{constant.ASYNC_KEY: "false"}),
+ invocation.WithAttachments(map[string]interface{}{constant.AsyncKey: "false"}),
invocation.WithParameterValues([]reflect.Value{siV, gV, vV, pV}))
res := m.invkr.Invoke(context.Background(), inv)
@@ -101,7 +101,7 @@ func (m *MetadataServiceProxy) MethodMapper() map[string]string {
// nolint
func (m *MetadataServiceProxy) Reference() string {
logger.Error("you should never invoke this implementation")
- return constant.METADATA_SERVICE_NAME
+ return constant.MetadataServiceName
}
// nolint
@@ -177,7 +177,7 @@ func (m *MetadataServiceProxy) GetMetadataInfo(revision string) (*common.Metadat
inv := invocation.NewRPCInvocationWithOptions(invocation.WithMethodName(methodName),
invocation.WithArguments([]interface{}{rV.Interface()}),
invocation.WithReply(reflect.ValueOf(&common.MetadataInfo{}).Interface()),
- invocation.WithAttachments(map[string]interface{}{constant.ASYNC_KEY: "false"}),
+ invocation.WithAttachments(map[string]interface{}{constant.AsyncKey: "false"}),
invocation.WithParameterValues([]reflect.Value{rV}))
res := m.invkr.Invoke(context.Background(), inv)
if res.Error() != nil {
diff --git a/metadata/service/local/service_proxy_test.go b/metadata/service/local/service_proxy_test.go
index df2f5c1..6c89076 100644
--- a/metadata/service/local/service_proxy_test.go
+++ b/metadata/service/local/service_proxy_test.go
@@ -37,7 +37,7 @@ import (
func TestMetadataServiceProxy_GetExportedURLs(t *testing.T) {
pxy := createPxy()
assert.NotNil(t, pxy)
- res, err := pxy.GetExportedURLs(constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE)
+ res, err := pxy.GetExportedURLs(constant.AnyValue, constant.AnyValue, constant.AnyValue, constant.AnyValue)
assert.Nil(t, err)
assert.Len(t, res, 1)
}
@@ -50,7 +50,7 @@ func TestNewMetadataService(t *testing.T) {
assert.Nil(t, err)
err = pxy.PublishServiceDefinition(&common.URL{})
assert.Nil(t, err)
- _, err = pxy.GetServiceDefinition(constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE)
+ _, err = pxy.GetServiceDefinition(constant.AnyValue, constant.AnyValue, constant.AnyValue)
assert.Nil(t, err)
_, err = pxy.Version()
assert.Nil(t, err)
@@ -70,7 +70,7 @@ func TestNewMetadataService(t *testing.T) {
assert.True(t, len(m) == 0)
err = pxy.UnexportURL(&common.URL{})
assert.NoError(t, err)
- ok, err = pxy.RefreshMetadata(constant.ANY_VALUE, constant.ANY_VALUE)
+ ok, err = pxy.RefreshMetadata(constant.AnyValue, constant.AnyValue)
assert.False(t, ok)
assert.NoError(t, err)
}
@@ -87,7 +87,7 @@ func createPxy() service.MetadataService {
Port: 8080,
Enable: true,
Healthy: true,
- Metadata: map[string]string{constant.METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME: `{"timeout":"10000", "protocol":"mock","version":"1.0.0","dubbo":"2.0.2","release":"2.7.6","port":"20880"}`},
+ Metadata: map[string]string{constant.MetadataServiceURLParamsPropertyName: `{"timeout":"10000", "protocol":"mock","version":"1.0.0","dubbo":"2.0.2","release":"2.7.6","port":"20880"}`},
}
return extension.GetMetadataServiceProxyFactory("").GetProxy(ins)
diff --git a/metadata/service/local_service.go b/metadata/service/local_service.go
index 1230e3a..9f80761 100644
--- a/metadata/service/local_service.go
+++ b/metadata/service/local_service.go
@@ -96,7 +96,7 @@ func (mts *BaseMetadataService) ServiceName() (string, error) {
// Reference will return the reference id of metadata service
func (mts *BaseMetadataService) Reference() string {
- return constant.SIMPLE_METADATA_SERVICE_NAME
+ return constant.SimpleMetadataServiceName
}
type MetadataServiceProxyFactory interface {
@@ -127,7 +127,7 @@ func (b *BaseMetadataServiceProxyFactory) GetProxy(ins registry.ServiceInstance)
func getExportedServicesRevision(serviceInstance registry.ServiceInstance) string {
metaData := serviceInstance.GetMetadata()
- return metaData[constant.EXPORTED_SERVICES_REVISION_PROPERTY_NAME]
+ return metaData[constant.ExportedServicesRevisionPropertyName]
}
func ConvertURLArrToIntfArr(urls []*common.URL) []interface{} {
diff --git a/metadata/service/remote/service.go b/metadata/service/remote/service.go
index dfe9ec5..0c8ee8f 100644
--- a/metadata/service/remote/service.go
+++ b/metadata/service/remote/service.go
@@ -96,25 +96,25 @@ func (s *MetadataService) PublishMetadata(service string) {
// GetMetadata get the medata info of service from report
func (s *MetadataService) GetMetadata(instance registry.ServiceInstance) (*common.MetadataInfo, error) {
- revision := instance.GetMetadata()[constant.EXPORTED_SERVICES_REVISION_PROPERTY_NAME]
+ revision := instance.GetMetadata()[constant.ExportedServicesRevisionPropertyName]
id := identifier.NewSubscriberMetadataIdentifier(instance.GetServiceName(), revision)
return s.delegateReport.GetAppMetadata(id)
}
// PublishServiceDefinition will call remote metadata's StoreProviderMetadata to store url info and service definition
func (s *MetadataService) PublishServiceDefinition(url *common.URL) error {
- interfaceName := url.GetParam(constant.INTERFACE_KEY, "")
- isGeneric := url.GetParamBool(constant.GENERIC_KEY, false)
- if common.RoleType(common.PROVIDER).Role() == url.GetParam(constant.SIDE_KEY, "") {
+ interfaceName := url.GetParam(constant.InterfaceKey, "")
+ isGeneric := url.GetParamBool(constant.GenericKey, false)
+ if common.RoleType(common.PROVIDER).Role() == url.GetParam(constant.SideKey, "") {
if len(interfaceName) > 0 && !isGeneric {
sv := common.ServiceMap.GetServiceByServiceKey(url.Protocol, url.ServiceKey())
sd := definition.BuildServiceDefinition(*sv, url)
id := &identifier.MetadataIdentifier{
BaseMetadataIdentifier: identifier.BaseMetadataIdentifier{
ServiceInterface: interfaceName,
- Version: url.GetParam(constant.VERSION_KEY, ""),
- Group: url.GetParam(constant.GROUP_KEY, constant.DUBBO),
- Side: url.GetParam(constant.SIDE_KEY, constant.PROVIDER_PROTOCOL),
+ Version: url.GetParam(constant.VersionKey, ""),
+ Group: url.GetParam(constant.GroupKey, constant.Dubbo),
+ Side: url.GetParam(constant.SideKey, constant.ProviderProtocol),
},
}
s.delegateReport.StoreProviderMetadata(id, sd)
@@ -130,9 +130,9 @@ func (s *MetadataService) PublishServiceDefinition(url *common.URL) error {
id := &identifier.MetadataIdentifier{
BaseMetadataIdentifier: identifier.BaseMetadataIdentifier{
ServiceInterface: interfaceName,
- Version: url.GetParam(constant.VERSION_KEY, ""),
- Group: url.GetParam(constant.GROUP_KEY, constant.DUBBO),
- Side: url.GetParam(constant.SIDE_KEY, "consumer"),
+ Version: url.GetParam(constant.VersionKey, ""),
+ Group: url.GetParam(constant.GroupKey, constant.Dubbo),
+ Side: url.GetParam(constant.SideKey, "consumer"),
},
}
s.delegateReport.StoreConsumerMetadata(id, params)
diff --git a/metrics/prometheus/reporter.go b/metrics/prometheus/reporter.go
index 110d759..9abc65f 100644
--- a/metrics/prometheus/reporter.go
+++ b/metrics/prometheus/reporter.go
@@ -44,11 +44,11 @@ import (
const (
reporterName = "prometheus"
- serviceKey = constant.SERVICE_KEY
- groupKey = constant.GROUP_KEY
- versionKey = constant.VERSION_KEY
- methodKey = constant.METHOD_KEY
- timeoutKey = constant.TIMEOUT_KEY
+ serviceKey = constant.ServiceKey
+ groupKey = constant.GroupKey
+ versionKey = constant.VersionKey
+ methodKey = constant.MethodKey
+ timeoutKey = constant.TimeoutKey
// to identify side
providerPrefix = "provider_"
@@ -116,7 +116,7 @@ func (reporter *PrometheusReporter) Report(ctx context.Context, invoker protocol
labels := prometheus.Labels{
serviceKey: url.Service(),
groupKey: url.GetParam(groupKey, ""),
- versionKey: url.GetParam(constant.APP_VERSION_KEY, ""),
+ versionKey: url.GetParam(constant.AppVersionKey, ""),
methodKey: invocation.MethodName(),
timeoutKey: url.GetParam(timeoutKey, ""),
}
@@ -196,13 +196,13 @@ func newSummaryVec(name, namespace string, labels []string) *prometheus.SummaryV
// isProvider shows whether this url represents the application received the request as server
func isProvider(url *common.URL) bool {
- role := url.GetParam(constant.ROLE_KEY, "")
+ role := url.GetParam(constant.RoleKey, "")
return strings.EqualFold(role, strconv.Itoa(common.PROVIDER))
}
// isConsumer shows whether this url represents the application sent then request as client
func isConsumer(url *common.URL) bool {
- role := url.GetParam(constant.ROLE_KEY, "")
+ role := url.GetParam(constant.RoleKey, "")
return strings.EqualFold(role, strconv.Itoa(common.CONSUMER))
}
diff --git a/protocol/dubbo/dubbo_codec.go b/protocol/dubbo/dubbo_codec.go
index 1ad4c37..32dc5f5 100644
--- a/protocol/dubbo/dubbo_codec.go
+++ b/protocol/dubbo/dubbo_codec.go
@@ -64,12 +64,12 @@ func (c *DubboCodec) EncodeRequest(request *remoting.Request) (*bytes.Buffer, er
invocation := *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.Path = invocation.AttachmentsByKey(constant.PathKey, "")
+ svc.Interface = invocation.AttachmentsByKey(constant.InterfaceKey, "")
+ svc.Version = invocation.AttachmentsByKey(constant.VersionKey, "")
+ svc.Group = invocation.AttachmentsByKey(constant.GroupKey, "")
svc.Method = invocation.MethodName()
- timeout, err := strconv.Atoi(invocation.AttachmentsByKey(constant.TIMEOUT_KEY, strconv.Itoa(constant.DEFAULT_REMOTING_TIMEOUT)))
+ timeout, err := strconv.Atoi(invocation.AttachmentsByKey(constant.TimeoutKey, strconv.Itoa(constant.DefaultRemotingTimeout)))
if err != nil {
// it will be wrapped in readwrite.Write .
return nil, perrors.WithStack(err)
@@ -77,11 +77,11 @@ func (c *DubboCodec) EncodeRequest(request *remoting.Request) (*bytes.Buffer, er
svc.Timeout = time.Duration(timeout)
header := impl.DubboHeader{}
- serialization := invocation.AttachmentsByKey(constant.SERIALIZATION_KEY, constant.HESSIAN2_SERIALIZATION)
- if serialization == constant.PROTOBUF_SERIALIZATION {
- header.SerialID = constant.S_Proto
+ serialization := invocation.AttachmentsByKey(constant.SerializationKey, constant.Hessian2Serialization)
+ if serialization == constant.ProtobufSerialization {
+ header.SerialID = constant.SProto
} else {
- header.SerialID = constant.S_Hessian2
+ header.SerialID = constant.SHessian2
}
header.ID = request.ID
if request.TwoWay {
@@ -109,7 +109,7 @@ func (c *DubboCodec) EncodeRequest(request *remoting.Request) (*bytes.Buffer, er
func (c *DubboCodec) encodeHeartbeartReqeust(request *remoting.Request) (*bytes.Buffer, error) {
header := impl.DubboHeader{
Type: impl.PackageHeartbeat,
- SerialID: constant.S_Hessian2,
+ SerialID: constant.SHessian2,
ID: request.ID,
}
@@ -216,9 +216,9 @@ func (c *DubboCodec) decodeRequest(data []byte) (*remoting.Request, int, error)
request.Version = req[impl.DubboVersionKey].(string)
}
// path
- attachments[constant.PATH_KEY] = pkg.Service.Path
+ attachments[constant.PathKey] = pkg.Service.Path
// version
- attachments[constant.VERSION_KEY] = pkg.Service.Version
+ attachments[constant.VersionKey] = pkg.Service.Version
// method
methodName = pkg.Service.Method
args = req[impl.ArgsKey].([]interface{})
diff --git a/protocol/dubbo/dubbo_exporter.go b/protocol/dubbo/dubbo_exporter.go
index 5343658..655c28e 100644
--- a/protocol/dubbo/dubbo_exporter.go
+++ b/protocol/dubbo/dubbo_exporter.go
@@ -42,7 +42,7 @@ func NewDubboExporter(key string, invoker protocol.Invoker, exporterMap *sync.Ma
// Unexport unexport dubbo service exporter.
func (de *DubboExporter) Unexport() {
- interfaceName := de.GetInvoker().GetURL().GetParam(constant.INTERFACE_KEY, "")
+ interfaceName := de.GetInvoker().GetURL().GetParam(constant.InterfaceKey, "")
de.BaseExporter.Unexport()
err := common.ServiceMap.UnRegister(interfaceName, DUBBO, de.GetInvoker().GetURL().ServiceKey())
if err != nil {
diff --git a/protocol/dubbo/dubbo_invoker.go b/protocol/dubbo/dubbo_invoker.go
index 7ae6723..0f23070 100644
--- a/protocol/dubbo/dubbo_invoker.go
+++ b/protocol/dubbo/dubbo_invoker.go
@@ -40,8 +40,8 @@ import (
)
var attachmentKey = []string{
- constant.INTERFACE_KEY, constant.GROUP_KEY, constant.TOKEN_KEY, constant.TIMEOUT_KEY,
- constant.VERSION_KEY,
+ constant.InterfaceKey, constant.GroupKey, constant.TokenKey, constant.TimeoutKey,
+ constant.VersionKey,
}
// DubboInvoker is implement of protocol.Invoker. A dubboInvoker refers to one service and ip.
@@ -59,7 +59,7 @@ type DubboInvoker struct {
func NewDubboInvoker(url *common.URL, client *remoting.ExchangeClient) *DubboInvoker {
rt := config.GetConsumerConfig().RequestTimeout
- timeout := url.GetParamDuration(constant.TIMEOUT_KEY, rt)
+ timeout := url.GetParamDuration(constant.TimeoutKey, rt)
di := &DubboInvoker{
BaseInvoker: *protocol.NewBaseInvoker(url),
clientGuard: &sync.RWMutex{},
@@ -117,7 +117,7 @@ func (di *DubboInvoker) Invoke(ctx context.Context, invocation protocol.Invocati
inv := invocation.(*invocation_impl.RPCInvocation)
// init param
- inv.SetAttachments(constant.PATH_KEY, di.GetURL().GetParam(constant.INTERFACE_KEY, ""))
+ inv.SetAttachments(constant.PathKey, di.GetURL().GetParam(constant.InterfaceKey, ""))
for _, k := range attachmentKey {
if v := di.GetURL().GetParam(k, ""); len(v) > 0 {
inv.SetAttachments(k, v)
@@ -129,11 +129,11 @@ func (di *DubboInvoker) Invoke(ctx context.Context, invocation protocol.Invocati
url := di.GetURL()
// default hessian2 serialization, compatible
- if url.GetParam(constant.SERIALIZATION_KEY, "") == "" {
- url.SetParam(constant.SERIALIZATION_KEY, constant.HESSIAN2_SERIALIZATION)
+ if url.GetParam(constant.SerializationKey, "") == "" {
+ url.SetParam(constant.SerializationKey, constant.Hessian2Serialization)
}
// async
- async, err := strconv.ParseBool(inv.AttachmentsByKey(constant.ASYNC_KEY, "false"))
+ async, err := strconv.ParseBool(inv.AttachmentsByKey(constant.AsyncKey, "false"))
if err != nil {
logger.Errorf("ParseBool - error: %v", err)
async = false
@@ -166,19 +166,19 @@ func (di *DubboInvoker) Invoke(ctx context.Context, invocation protocol.Invocati
// get timeout including methodConfig
func (di *DubboInvoker) getTimeout(invocation *invocation_impl.RPCInvocation) time.Duration {
methodName := invocation.MethodName()
- if di.GetURL().GetParamBool(constant.GENERIC_KEY, false) {
+ if di.GetURL().GetParamBool(constant.GenericKey, false) {
methodName = invocation.Arguments()[0].(string)
}
- timeout := di.GetURL().GetParam(strings.Join([]string{constant.METHOD_KEYS, methodName, constant.TIMEOUT_KEY}, "."), "")
+ timeout := di.GetURL().GetParam(strings.Join([]string{constant.MethodKeys, methodName, constant.TimeoutKey}, "."), "")
if len(timeout) != 0 {
if t, err := time.ParseDuration(timeout); err == nil {
// config timeout into attachment
- invocation.SetAttachments(constant.TIMEOUT_KEY, strconv.Itoa(int(t.Milliseconds())))
+ invocation.SetAttachments(constant.TimeoutKey, strconv.Itoa(int(t.Milliseconds())))
return t
}
}
// set timeout into invocation at method level
- invocation.SetAttachments(constant.TIMEOUT_KEY, strconv.Itoa(int(di.timeout.Milliseconds())))
+ invocation.SetAttachments(constant.TimeoutKey, strconv.Itoa(int(di.timeout.Milliseconds())))
return di.timeout
}
diff --git a/protocol/dubbo/dubbo_protocol.go b/protocol/dubbo/dubbo_protocol.go
index fe35e35..f2de5b7 100644
--- a/protocol/dubbo/dubbo_protocol.go
+++ b/protocol/dubbo/dubbo_protocol.go
@@ -234,7 +234,7 @@ func rebuildCtx(inv *invocation.RPCInvocation) context.Context {
spanCtx, err := opentracing.GlobalTracer().Extract(opentracing.TextMap,
opentracing.TextMapCarrier(filterContext(inv.Attachments())))
if err == nil {
- ctx = context.WithValue(ctx, constant.DubboCtxKey(constant.TRACING_REMOTE_SPAN_CTX), spanCtx)
+ ctx = context.WithValue(ctx, constant.DubboCtxKey(constant.TracingRemoteSpanCtx), spanCtx)
}
return ctx
}
diff --git a/protocol/dubbo/impl/codec.go b/protocol/dubbo/impl/codec.go
index cc842dc..cc7abad 100644
--- a/protocol/dubbo/impl/codec.go
+++ b/protocol/dubbo/impl/codec.go
@@ -276,7 +276,7 @@ func packResponse(p DubboPackage, serializer Serializer) ([]byte, error) {
}
func NewDubboCodec(reader *bufio.Reader) *ProtocolCodec {
- s, _ := GetSerializerById(constant.S_Hessian2)
+ s, _ := GetSerializerById(constant.SHessian2)
return &ProtocolCodec{
reader: reader,
pkgType: 0,
diff --git a/protocol/dubbo/impl/codec_test.go b/protocol/dubbo/impl/codec_test.go
index 2ea2e2f..9a64ac5 100644
--- a/protocol/dubbo/impl/codec_test.go
+++ b/protocol/dubbo/impl/codec_test.go
@@ -34,7 +34,7 @@ func TestDubboPackage_MarshalAndUnmarshal(t *testing.T) {
pkg := NewDubboPackage(nil)
pkg.Body = []interface{}{"a"}
pkg.Header.Type = PackageHeartbeat
- pkg.Header.SerialID = constant.S_Hessian2
+ pkg.Header.SerialID = constant.SHessian2
pkg.Header.ID = 10086
pkg.SetSerializer(HessianSerializer{})
@@ -49,7 +49,7 @@ func TestDubboPackage_MarshalAndUnmarshal(t *testing.T) {
err = pkgres.Unmarshal()
assert.NoError(t, err)
assert.Equal(t, PackageHeartbeat|PackageRequest|PackageRequest_TwoWay, pkgres.Header.Type)
- assert.Equal(t, constant.S_Hessian2, pkgres.Header.SerialID)
+ assert.Equal(t, constant.SHessian2, pkgres.Header.SerialID)
assert.Equal(t, int64(10086), pkgres.Header.ID)
assert.Equal(t, 0, len(pkgres.Body.([]interface{})))
@@ -70,7 +70,7 @@ func TestDubboPackage_MarshalAndUnmarshal(t *testing.T) {
reassembleBody := pkgres.GetBody().(map[string]interface{})
assert.NoError(t, err)
assert.Equal(t, PackageRequest, pkgres.Header.Type)
- assert.Equal(t, constant.S_Hessian2, pkgres.Header.SerialID)
+ assert.Equal(t, constant.SHessian2, pkgres.Header.SerialID)
assert.Equal(t, int64(10086), pkgres.Header.ID)
assert.Equal(t, "2.0.2", reassembleBody["dubboVersion"].(string))
assert.Equal(t, "path", pkgres.Service.Path)
diff --git a/protocol/dubbo/impl/hessian.go b/protocol/dubbo/impl/hessian.go
index 756650f..26858dc 100644
--- a/protocol/dubbo/impl/hessian.go
+++ b/protocol/dubbo/impl/hessian.go
@@ -255,7 +255,7 @@ func unmarshalRequestBody(body []byte, p *DubboPackage) error {
}
if attachments == nil {
- attachments = map[interface{}]interface{}{constant.INTERFACE_KEY: target}
+ attachments = map[interface{}]interface{}{constant.InterfaceKey: target}
}
if v, ok := attachments.(map[interface{}]interface{}); ok {
@@ -370,16 +370,16 @@ func buildServerSidePackageBody(pkg *DubboPackage) {
if req[6] != nil {
attachments = req[6].(map[string]interface{})
}
- if svc.Path == "" && attachments[constant.PATH_KEY] != nil && len(attachments[constant.PATH_KEY].(string)) > 0 {
- svc.Path = attachments[constant.PATH_KEY].(string)
+ if svc.Path == "" && attachments[constant.PathKey] != nil && len(attachments[constant.PathKey].(string)) > 0 {
+ svc.Path = attachments[constant.PathKey].(string)
}
- if _, ok := attachments[constant.INTERFACE_KEY]; ok {
- svc.Interface = attachments[constant.INTERFACE_KEY].(string)
+ if _, ok := attachments[constant.InterfaceKey]; ok {
+ svc.Interface = attachments[constant.InterfaceKey].(string)
} else {
svc.Interface = svc.Path
}
- if _, ok := attachments[constant.GROUP_KEY]; ok {
- svc.Group = attachments[constant.GROUP_KEY].(string)
+ if _, ok := attachments[constant.GroupKey]; ok {
+ svc.Group = attachments[constant.GroupKey].(string)
}
pkg.SetService(svc)
pkg.SetBody(map[string]interface{}{
diff --git a/protocol/dubbo/impl/serialization.go b/protocol/dubbo/impl/serialization.go
index 8137a2f..a98d408 100644
--- a/protocol/dubbo/impl/serialization.go
+++ b/protocol/dubbo/impl/serialization.go
@@ -32,8 +32,8 @@ var (
func init() {
nameMaps = map[byte]string{
- constant.S_Hessian2: constant.HESSIAN2_SERIALIZATION,
- constant.S_Proto: constant.PROTOBUF_SERIALIZATION,
+ constant.SHessian2: constant.Hessian2Serialization,
+ constant.SProto: constant.ProtobufSerialization,
}
}
diff --git a/protocol/dubbo/impl/serialize.go b/protocol/dubbo/impl/serialize.go
index 771d91e..23e9fbc 100644
--- a/protocol/dubbo/impl/serialize.go
+++ b/protocol/dubbo/impl/serialize.go
@@ -29,7 +29,7 @@ func LoadSerializer(p *DubboPackage) error {
// NOTE: default serialID is S_Hessian
serialID := p.Header.SerialID
if serialID == 0 {
- serialID = constant.S_Hessian2
+ serialID = constant.SHessian2
}
serializer, err := GetSerializerById(serialID)
if err != nil {
diff --git a/protocol/dubbo3/dubbo3_exporter.go b/protocol/dubbo3/dubbo3_exporter.go
index 8bea0fa..e824238 100644
--- a/protocol/dubbo3/dubbo3_exporter.go
+++ b/protocol/dubbo3/dubbo3_exporter.go
@@ -50,8 +50,8 @@ func NewDubboExporter(key string, invoker protocol.Invoker, exporterMap *sync.Ma
// Unexport unexport dubbo3 service exporter.
func (de *DubboExporter) Unexport() {
url := de.GetInvoker().GetURL()
- serviceId := url.GetParam(constant.BEAN_NAME_KEY, "")
- interfaceName := url.GetParam(constant.INTERFACE_KEY, "")
+ serviceId := url.GetParam(constant.BeanNameKey, "")
+ interfaceName := url.GetParam(constant.InterfaceKey, "")
de.BaseExporter.Unexport()
err := common.ServiceMap.UnRegister(interfaceName, tripleConstant.TRIPLE, serviceId)
if err != nil {
diff --git a/protocol/dubbo3/dubbo3_invoker.go b/protocol/dubbo3/dubbo3_invoker.go
index a55ee54..c978f85 100644
--- a/protocol/dubbo3/dubbo3_invoker.go
+++ b/protocol/dubbo3/dubbo3_invoker.go
@@ -58,21 +58,21 @@ type DubboInvoker struct {
func NewDubboInvoker(url *common.URL) (*DubboInvoker, error) {
rt := config.GetConsumerConfig().RequestTimeout
- timeout := url.GetParamDuration(constant.TIMEOUT_KEY, rt)
+ timeout := url.GetParamDuration(constant.TimeoutKey, rt)
// for triple pb serialization. The bean name from provider is the provider reference key,
// which can't locate the target consumer stub, so we use interface key..
- interfaceKey := url.GetParam(constant.INTERFACE_KEY, "")
+ interfaceKey := url.GetParam(constant.InterfaceKey, "")
consumerService := config.GetConsumerServiceByInterfaceName(interfaceKey)
- dubboSerializaerType := url.GetParam(constant.SERIALIZATION_KEY, constant.PROTOBUF_SERIALIZATION)
+ dubboSerializaerType := url.GetParam(constant.SerializationKey, constant.ProtobufSerialization)
triCodecType := tripleConstant.CodecType(dubboSerializaerType)
// new triple client
triOption := triConfig.NewTripleOption(
triConfig.WithClientTimeout(uint32(timeout.Seconds())),
triConfig.WithCodecType(triCodecType),
triConfig.WithLocation(url.Location),
- triConfig.WithHeaderAppVersion(url.GetParam(constant.APP_VERSION_KEY, "")),
- triConfig.WithHeaderGroup(url.GetParam(constant.GROUP_KEY, "")),
+ triConfig.WithHeaderAppVersion(url.GetParam(constant.AppVersionKey, "")),
+ triConfig.WithHeaderGroup(url.GetParam(constant.GroupKey, "")),
triConfig.WithLogger(logger.GetLogger()),
)
client, err := triple.NewTripleClient(consumerService, triOption)
@@ -135,7 +135,7 @@ func (di *DubboInvoker) Invoke(ctx context.Context, invocation protocol.Invocati
// append interface id to ctx
ctx = context.WithValue(ctx, tripleConstant.CtxAttachmentKey, invocation.Attachments())
- ctx = context.WithValue(ctx, tripleConstant.InterfaceKey, di.BaseInvoker.GetURL().GetParam(constant.INTERFACE_KEY, ""))
+ ctx = context.WithValue(ctx, tripleConstant.InterfaceKey, di.BaseInvoker.GetURL().GetParam(constant.InterfaceKey, ""))
in := make([]reflect.Value, 0, 16)
in = append(in, reflect.ValueOf(ctx))
@@ -155,16 +155,16 @@ func (di *DubboInvoker) Invoke(ctx context.Context, invocation protocol.Invocati
// get timeout including methodConfig
func (di *DubboInvoker) getTimeout(invocation *invocation_impl.RPCInvocation) time.Duration {
- timeout := di.GetURL().GetParam(strings.Join([]string{constant.METHOD_KEYS, invocation.MethodName(), constant.TIMEOUT_KEY}, "."), "")
+ timeout := di.GetURL().GetParam(strings.Join([]string{constant.MethodKeys, invocation.MethodName(), constant.TimeoutKey}, "."), "")
if len(timeout) != 0 {
if t, err := time.ParseDuration(timeout); err == nil {
// config timeout into attachment
- invocation.SetAttachments(constant.TIMEOUT_KEY, strconv.Itoa(int(t.Milliseconds())))
+ invocation.SetAttachments(constant.TimeoutKey, strconv.Itoa(int(t.Milliseconds())))
return t
}
}
// set timeout into invocation at method level
- invocation.SetAttachments(constant.TIMEOUT_KEY, strconv.Itoa(int(di.timeout.Milliseconds())))
+ invocation.SetAttachments(constant.TimeoutKey, strconv.Itoa(int(di.timeout.Milliseconds())))
return di.timeout
}
diff --git a/protocol/dubbo3/dubbo3_protocol.go b/protocol/dubbo3/dubbo3_protocol.go
index d0854df..c84cbc1 100644
--- a/protocol/dubbo3/dubbo3_protocol.go
+++ b/protocol/dubbo3/dubbo3_protocol.go
@@ -79,14 +79,14 @@ func (dp *DubboProtocol) Export(invoker protocol.Invoker) protocol.Exporter {
dp.SetExporterMap(serviceKey, exporter)
logger.Infof("Export service: %s", url.String())
- key := url.GetParam(constant.BEAN_NAME_KEY, "")
+ key := url.GetParam(constant.BeanNameKey, "")
var service interface{}
service = config.GetProviderService(key)
- serializationType := url.GetParam(constant.SERIALIZATION_KEY, constant.PROTOBUF_SERIALIZATION)
+ serializationType := url.GetParam(constant.SerializationKey, constant.ProtobufSerialization)
var triSerializationType tripleConstant.CodecType
- if serializationType == constant.PROTOBUF_SERIALIZATION {
+ if serializationType == constant.ProtobufSerialization {
m, ok := reflect.TypeOf(service).MethodByName("XXX_SetProxyImpl")
if !ok {
panic("method XXX_SetProxyImpl is necessary for triple service")
@@ -119,7 +119,7 @@ func (dp *DubboProtocol) Export(invoker protocol.Invoker) protocol.Exporter {
triSerializationType = tripleConstant.CodecType(serializationType)
}
- dp.serviceMap.Store(url.GetParam(constant.INTERFACE_KEY, ""), service)
+ dp.serviceMap.Store(url.GetParam(constant.InterfaceKey, ""), service)
// try start server
dp.openServer(url, triSerializationType)
diff --git a/protocol/grpc/client.go b/protocol/grpc/client.go
index ab8c0db..b6f2b03 100644
--- a/protocol/grpc/client.go
+++ b/protocol/grpc/client.go
@@ -58,7 +58,7 @@ func NewClient(url *common.URL) (*Client, error) {
// If not, will return NoopTracer.
tracer := opentracing.GlobalTracer()
dialOpts := make([]grpc.DialOption, 0, 4)
- maxMessageSize, _ := strconv.Atoi(url.GetParam(constant.MESSAGE_SIZE_KEY, "4"))
+ maxMessageSize, _ := strconv.Atoi(url.GetParam(constant.MessageSizeKey, "4"))
// consumer config client connectTimeout
//connectTimeout := config.GetConsumerConfig().ConnectTimeout
@@ -83,7 +83,7 @@ func NewClient(url *common.URL) (*Client, error) {
return nil, err
}
- key := url.GetParam(constant.INTERFACE_KEY, "")
+ key := url.GetParam(constant.InterfaceKey, "")
impl := config.GetConsumerServiceByInterfaceName(key)
invoker := getInvoker(impl, conn)
diff --git a/protocol/grpc/grpc_exporter.go b/protocol/grpc/grpc_exporter.go
index 46740f7..a5f0045 100644
--- a/protocol/grpc/grpc_exporter.go
+++ b/protocol/grpc/grpc_exporter.go
@@ -42,7 +42,7 @@ func NewGrpcExporter(key string, invoker protocol.Invoker, exporterMap *sync.Map
// Unexport and unregister gRPC service from registry and memory.
func (gg *GrpcExporter) Unexport() {
- interfaceName := gg.GetInvoker().GetURL().GetParam(constant.INTERFACE_KEY, "")
+ interfaceName := gg.GetInvoker().GetURL().GetParam(constant.InterfaceKey, "")
gg.BaseExporter.Unexport()
err := common.ServiceMap.UnRegister(interfaceName, GRPC, gg.GetInvoker().GetURL().ServiceKey())
if err != nil {
diff --git a/protocol/grpc/grpc_protocol.go b/protocol/grpc/grpc_protocol.go
index 83ae1c3..cafd5a7 100644
--- a/protocol/grpc/grpc_protocol.go
+++ b/protocol/grpc/grpc_protocol.go
@@ -79,7 +79,7 @@ func (gp *GrpcProtocol) openServer(url *common.URL) {
panic("[GrpcProtocol]" + url.Key() + "is not existing")
}
- grpcMessageSize, _ := strconv.Atoi(url.GetParam(constant.MESSAGE_SIZE_KEY, "4"))
+ grpcMessageSize, _ := strconv.Atoi(url.GetParam(constant.MessageSizeKey, "4"))
srv := NewServer()
srv.SetBufferSize(grpcMessageSize)
gp.serverMap[url.Location] = srv
diff --git a/protocol/invocation/rpcinvocation.go b/protocol/invocation/rpcinvocation.go
index 6aa4940..bac9060 100644
--- a/protocol/invocation/rpcinvocation.go
+++ b/protocol/invocation/rpcinvocation.go
@@ -194,8 +194,8 @@ func (r *RPCInvocation) SetCallBack(c interface{}) {
}
func (r *RPCInvocation) ServiceKey() string {
- return common.ServiceKey(strings.TrimPrefix(r.AttachmentsByKey(constant.PATH_KEY, r.AttachmentsByKey(constant.INTERFACE_KEY, "")), "/"),
- r.AttachmentsByKey(constant.GROUP_KEY, ""), r.AttachmentsByKey(constant.VERSION_KEY, ""))
+ return common.ServiceKey(strings.TrimPrefix(r.AttachmentsByKey(constant.PathKey, r.AttachmentsByKey(constant.InterfaceKey, "")), "/"),
+ r.AttachmentsByKey(constant.GroupKey, ""), r.AttachmentsByKey(constant.VersionKey, ""))
}
// /////////////////////////
diff --git a/protocol/invocation/rpcinvocation_test.go b/protocol/invocation/rpcinvocation_test.go
index 320f8ae..2a36506 100644
--- a/protocol/invocation/rpcinvocation_test.go
+++ b/protocol/invocation/rpcinvocation_test.go
@@ -54,10 +54,10 @@ func TestRPCInvocation_ServiceKey(t *testing.T) {
sameInfPathConsumerUrl, err := common.NewURL(sameInfPathConsumerURL)
assert.NoError(t, err)
invocation := NewRPCInvocationWithOptions(WithAttachments(map[string]interface{}{
- constant.INTERFACE_KEY: sameInfPathConsumerUrl.GetParam(constant.INTERFACE_KEY, ""),
- constant.PATH_KEY: sameInfPathConsumerUrl.Path,
- constant.GROUP_KEY: sameInfPathConsumerUrl.GetParam(constant.GROUP_KEY, ""),
- constant.VERSION_KEY: sameInfPathConsumerUrl.GetParam(constant.VERSION_KEY, ""),
+ constant.InterfaceKey: sameInfPathConsumerUrl.GetParam(constant.InterfaceKey, ""),
+ constant.PathKey: sameInfPathConsumerUrl.Path,
+ constant.GroupKey: sameInfPathConsumerUrl.GetParam(constant.GroupKey, ""),
+ constant.VersionKey: sameInfPathConsumerUrl.GetParam(constant.VersionKey, ""),
}))
assert.Equal(t, providerUrl.ServiceKey(), invocation.ServiceKey())
@@ -65,10 +65,10 @@ func TestRPCInvocation_ServiceKey(t *testing.T) {
diffInfPathConsumerUrl, err := common.NewURL(diffInfPathConsumerURL)
assert.NoError(t, err)
invocation = NewRPCInvocationWithOptions(WithAttachments(map[string]interface{}{
- constant.INTERFACE_KEY: diffInfPathConsumerUrl.GetParam(constant.INTERFACE_KEY, ""),
- constant.PATH_KEY: diffInfPathConsumerUrl.Path,
- constant.GROUP_KEY: diffInfPathConsumerUrl.GetParam(constant.GROUP_KEY, ""),
- constant.VERSION_KEY: diffInfPathConsumerUrl.GetParam(constant.VERSION_KEY, ""),
+ constant.InterfaceKey: diffInfPathConsumerUrl.GetParam(constant.InterfaceKey, ""),
+ constant.PathKey: diffInfPathConsumerUrl.Path,
+ constant.GroupKey: diffInfPathConsumerUrl.GetParam(constant.GroupKey, ""),
+ constant.VersionKey: diffInfPathConsumerUrl.GetParam(constant.VersionKey, ""),
}))
assert.Equal(t, providerUrl.ServiceKey(), invocation.ServiceKey())
}
diff --git a/protocol/jsonrpc/http.go b/protocol/jsonrpc/http.go
index 92c748a..ad1b226 100644
--- a/protocol/jsonrpc/http.go
+++ b/protocol/jsonrpc/http.go
@@ -101,9 +101,9 @@ func NewHTTPClient(opt *HTTPOptions) *HTTPClient {
func (c *HTTPClient) NewRequest(service *common.URL, method string, args interface{}) *Request {
return &Request{
ID: atomic.AddInt64(&c.ID, 1),
- group: service.GetParam(constant.GROUP_KEY, ""),
+ group: service.GetParam(constant.GroupKey, ""),
protocol: service.Protocol,
- version: service.GetParam(constant.VERSION_KEY, ""),
+ version: service.GetParam(constant.VersionKey, ""),
service: service.Path,
method: method,
args: args,
@@ -122,7 +122,7 @@ func (c *HTTPClient) Call(ctx context.Context, service *common.URL, req *Request
reqTimeout = 100 * time.Millisecond
}
httpHeader.Set("Timeout", reqTimeout.String())
- if md, ok := ctx.Value(constant.DUBBOGO_CTX_KEY).(map[string]string); ok {
+ if md, ok := ctx.Value(constant.DubboGoCtxKey).(map[string]string); ok {
for k := range md {
httpHeader.Set(k, md[k])
}
diff --git a/protocol/jsonrpc/jsonrpc_exporter.go b/protocol/jsonrpc/jsonrpc_exporter.go
index dc9848c..a1b85a0 100644
--- a/protocol/jsonrpc/jsonrpc_exporter.go
+++ b/protocol/jsonrpc/jsonrpc_exporter.go
@@ -42,7 +42,7 @@ func NewJsonrpcExporter(key string, invoker protocol.Invoker, exporterMap *sync.
// Unexport exported JSON RPC service.
func (je *JsonrpcExporter) Unexport() {
- interfaceName := je.GetInvoker().GetURL().GetParam(constant.INTERFACE_KEY, "")
+ interfaceName := je.GetInvoker().GetURL().GetParam(constant.InterfaceKey, "")
je.BaseExporter.Unexport()
err := common.ServiceMap.UnRegister(interfaceName, JSONRPC, je.GetInvoker().GetURL().ServiceKey())
if err != nil {
diff --git a/protocol/jsonrpc/jsonrpc_invoker.go b/protocol/jsonrpc/jsonrpc_invoker.go
index d2a0d1e..03b3280 100644
--- a/protocol/jsonrpc/jsonrpc_invoker.go
+++ b/protocol/jsonrpc/jsonrpc_invoker.go
@@ -50,7 +50,7 @@ func (ji *JsonrpcInvoker) Invoke(ctx context.Context, invocation protocol.Invoca
inv := invocation.(*invocation_impl.RPCInvocation)
url := ji.GetURL()
req := ji.client.NewRequest(url, inv.MethodName(), inv.Arguments())
- ctxNew := context.WithValue(ctx, constant.DUBBOGO_CTX_KEY, map[string]string{
+ ctxNew := context.WithValue(ctx, constant.DubboGoCtxKey, map[string]string{
"X-Proxy-ID": "dubbogo",
"X-Services": url.Path,
"X-Method": inv.MethodName(),
diff --git a/protocol/jsonrpc/server.go b/protocol/jsonrpc/server.go
index 771615f..340849c 100644
--- a/protocol/jsonrpc/server.go
+++ b/protocol/jsonrpc/server.go
@@ -160,7 +160,7 @@ func (s *Server) handlePkg(conn net.Conn) {
spanCtx, err := opentracing.GlobalTracer().Extract(opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(r.Header))
if err == nil {
- ctx = context.WithValue(ctx, constant.TRACING_REMOTE_SPAN_CTX, spanCtx)
+ ctx = context.WithValue(ctx, constant.TracingRemoteSpanCtx, spanCtx)
}
if len(reqHeader["Timeout"]) > 0 {
@@ -347,8 +347,8 @@ func serveRequest(ctx context.Context, header map[string]string, body []byte, co
invoker := exporter.(*JsonrpcExporter).GetInvoker()
if invoker != nil {
result := invoker.Invoke(ctx, invocation.NewRPCInvocation(methodName, args, map[string]interface{}{
- constant.PATH_KEY: path,
- constant.VERSION_KEY: codec.req.Version,
+ constant.PathKey: path,
+ constant.VersionKey: codec.req.Version,
}))
if err := result.Error(); err != nil {
rspStream, codecErr := codec.Write(err.Error(), invalidRequest)
diff --git a/protocol/protocolwrapper/protocol_filter_wrapper.go b/protocol/protocolwrapper/protocol_filter_wrapper.go
index 42b6905..2c24178 100644
--- a/protocol/protocolwrapper/protocol_filter_wrapper.go
+++ b/protocol/protocolwrapper/protocol_filter_wrapper.go
@@ -50,7 +50,7 @@ func (pfw *ProtocolFilterWrapper) Export(invoker protocol.Invoker) protocol.Expo
if pfw.protocol == nil {
pfw.protocol = extension.GetProtocol(invoker.GetURL().Protocol)
}
- invoker = BuildInvokerChain(invoker, constant.SERVICE_FILTER_KEY)
+ invoker = BuildInvokerChain(invoker, constant.ServiceFilterKey)
return pfw.protocol.Export(invoker)
}
@@ -63,7 +63,7 @@ func (pfw *ProtocolFilterWrapper) Refer(url *common.URL) protocol.Invoker {
if invoker == nil {
return nil
}
- return BuildInvokerChain(invoker, constant.REFERENCE_FILTER_KEY)
+ return BuildInvokerChain(invoker, constant.ReferenceFilterKey)
}
// Destroy will destroy all invoker and exporter.
diff --git a/protocol/protocolwrapper/protocol_filter_wrapper_test.go b/protocol/protocolwrapper/protocol_filter_wrapper_test.go
index 2400058..7862e4e 100644
--- a/protocol/protocolwrapper/protocol_filter_wrapper_test.go
+++ b/protocol/protocolwrapper/protocol_filter_wrapper_test.go
@@ -44,7 +44,7 @@ func TestProtocolFilterWrapperExport(t *testing.T) {
u := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.SERVICE_FILTER_KEY, mockFilterKey))
+ common.WithParamsValue(constant.ServiceFilterKey, mockFilterKey))
exporter := filtProto.Export(protocol.NewBaseInvoker(u))
_, ok := exporter.GetInvoker().(*FilterInvoker)
assert.True(t, ok)
@@ -56,7 +56,7 @@ func TestProtocolFilterWrapperRefer(t *testing.T) {
u := common.NewURLWithOptions(
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.REFERENCE_FILTER_KEY, mockFilterKey))
+ common.WithParamsValue(constant.ReferenceFilterKey, mockFilterKey))
invoker := filtProto.Refer(u)
_, ok := invoker.(*FilterInvoker)
assert.True(t, ok)
@@ -72,7 +72,7 @@ type mockEchoFilter struct{}
func (ef *mockEchoFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
logger.Infof("invoking echo filter.")
logger.Debugf("%v,%v", invocation.MethodName(), len(invocation.Arguments()))
- if invocation.MethodName() == constant.ECHO && len(invocation.Arguments()) == 1 {
+ if invocation.MethodName() == constant.Echo && len(invocation.Arguments()) == 1 {
return &protocol.RPCResult{
Rest: invocation.Arguments()[0],
}
diff --git a/protocol/rest/client/client_impl/resty_client.go b/protocol/rest/client/client_impl/resty_client.go
index c7c16e8..7044a53 100644
--- a/protocol/rest/client/client_impl/resty_client.go
+++ b/protocol/rest/client/client_impl/resty_client.go
@@ -38,7 +38,7 @@ import (
)
func init() {
- extension.SetRestClient(constant.DEFAULT_REST_CLIENT, NewRestyClient)
+ extension.SetRestClient(constant.DefaultRestClient, NewRestyClient)
}
// RestyClient a rest client implement by Resty
diff --git a/protocol/rest/config/reader/rest_config_reader.go b/protocol/rest/config/reader/rest_config_reader.go
index 18f06b2..6bfe5c2 100644
--- a/protocol/rest/config/reader/rest_config_reader.go
+++ b/protocol/rest/config/reader/rest_config_reader.go
@@ -60,7 +60,7 @@ func (cr *RestConfigReader) ReadConsumerConfig(reader *bytes.Buffer) error {
restConsumerServiceConfigMap := make(map[string]*config.RestServiceConfig, len(restConsumerConfig.RestServiceConfigsMap))
for key, rc := range restConsumerConfig.RestServiceConfigsMap {
- rc.Client = getNotEmptyStr(rc.Client, restConsumerConfig.Client, constant.DEFAULT_REST_CLIENT)
+ rc.Client = getNotEmptyStr(rc.Client, restConsumerConfig.Client, constant.DefaultRestClient)
rc.RestMethodConfigsMap = initMethodConfigMap(rc, restConsumerConfig.Consumes, restConsumerConfig.Produces)
restConsumerServiceConfigMap[key] = rc
}
@@ -77,7 +77,7 @@ func (cr *RestConfigReader) ReadProviderConfig(reader *bytes.Buffer) error {
}
restProviderServiceConfigMap := make(map[string]*config.RestServiceConfig, len(restProviderConfig.RestServiceConfigsMap))
for key, rc := range restProviderConfig.RestServiceConfigsMap {
- rc.Server = getNotEmptyStr(rc.Server, restProviderConfig.Server, constant.DEFAULT_REST_SERVER)
+ rc.Server = getNotEmptyStr(rc.Server, restProviderConfig.Server, constant.DefaultRestServer)
rc.RestMethodConfigsMap = initMethodConfigMap(rc, restProviderConfig.Consumes, restProviderConfig.Produces)
restProviderServiceConfigMap[key] = rc
}
diff --git a/protocol/rest/rest_exporter.go b/protocol/rest/rest_exporter.go
index 68f5667..b3e3a48 100644
--- a/protocol/rest/rest_exporter.go
+++ b/protocol/rest/rest_exporter.go
@@ -42,7 +42,7 @@ func NewRestExporter(key string, invoker protocol.Invoker, exporterMap *sync.Map
// Unexport unexport the RestExporter
func (re *RestExporter) Unexport() {
- interfaceName := re.GetInvoker().GetURL().GetParam(constant.INTERFACE_KEY, "")
+ interfaceName := re.GetInvoker().GetURL().GetParam(constant.InterfaceKey, "")
re.BaseExporter.Unexport()
err := common.ServiceMap.UnRegister(interfaceName, REST, re.GetInvoker().GetURL().ServiceKey())
if err != nil {
diff --git a/protocol/rest/rest_protocol.go b/protocol/rest/rest_protocol.go
index 476a9fe..32d007a 100644
--- a/protocol/rest/rest_protocol.go
+++ b/protocol/rest/rest_protocol.go
@@ -68,7 +68,7 @@ func (rp *RestProtocol) Export(invoker protocol.Invoker) protocol.Exporter {
url := invoker.GetURL()
serviceKey := url.ServiceKey()
exporter := NewRestExporter(serviceKey, invoker, rp.ExporterMap())
- id := url.GetParam(constant.BEAN_NAME_KEY, "")
+ id := url.GetParam(constant.BeanNameKey, "")
restServiceConfig := rest_config.GetRestProviderServiceConfig(id)
if restServiceConfig == nil {
logger.Errorf("%s service doesn't has provider config", url.Path)
@@ -88,13 +88,13 @@ func (rp *RestProtocol) Refer(url *common.URL) protocol.Invoker {
// todo fix timeout config
// start
requestTimeout := time.Duration(3 * time.Second)
- requestTimeoutStr := url.GetParam(constant.TIMEOUT_KEY, "3s")
+ requestTimeoutStr := url.GetParam(constant.TimeoutKey, "3s")
connectTimeout := requestTimeout // config.GetConsumerConfig().ConnectTimeout
// end
if t, err := time.ParseDuration(requestTimeoutStr); err == nil {
requestTimeout = t
}
- id := url.GetParam(constant.BEAN_NAME_KEY, "")
+ id := url.GetParam(constant.BeanNameKey, "")
restServiceConfig := rest_config.GetRestConsumerServiceConfig(id)
if restServiceConfig == nil {
logger.Errorf("%s service doesn't has consumer config", url.Path)
diff --git a/protocol/rest/server/server_impl/go_restful_server.go b/protocol/rest/server/server_impl/go_restful_server.go
index af7eb5a..464f5c8 100644
--- a/protocol/rest/server/server_impl/go_restful_server.go
+++ b/protocol/rest/server/server_impl/go_restful_server.go
@@ -42,7 +42,7 @@ import (
)
func init() {
- extension.SetRestServer(constant.DEFAULT_REST_SERVER, NewGoRestfulServer)
+ extension.SetRestServer(constant.DefaultRestServer, NewGoRestfulServer)
}
var filterSlice []restful.FilterFunction
diff --git a/protocol/rpc_status.go b/protocol/rpc_status.go
index e0147e0..f35b2ae 100644
--- a/protocol/rpc_status.go
+++ b/protocol/rpc_status.go
@@ -256,7 +256,7 @@ func TryRefreshBlackList() {
atomic.CompareAndSwapInt32(&blackListRefreshing, 1, 0)
}()
- ivks := GetBlackListInvokers(constant.DEFAULT_BLACK_LIST_RECOVER_BLOCK)
+ ivks := GetBlackListInvokers(constant.DefaultBlackListRecoverBlock)
logger.Debug("blackList len = ", len(ivks))
for i := 0; i < 3; i++ {
diff --git a/registry/base_configuration_listener.go b/registry/base_configuration_listener.go
index 39ab265..f82e834 100644
--- a/registry/base_configuration_listener.go
+++ b/registry/base_configuration_listener.go
@@ -55,7 +55,7 @@ func (bcl *BaseConfigurationListener) InitWith(key string, listener config_cente
bcl.defaultConfiguratorFunc = f
bcl.dynamicConfiguration.AddListener(key, listener)
if rawConfig, err := bcl.dynamicConfiguration.GetInternalProperty(key,
- config_center.WithGroup(constant.DUBBO)); err != nil {
+ config_center.WithGroup(constant.Dubbo)); err != nil {
//set configurators to empty
bcl.configurators = []config_center.Configurator{}
return
@@ -102,13 +102,13 @@ func ToConfigurators(urls []*common.URL, f func(url *common.URL) config_center.C
}
var configurators []config_center.Configurator
for _, url := range urls {
- if url.Protocol == constant.EMPTY_PROTOCOL {
+ if url.Protocol == constant.EmptyProtocol {
configurators = []config_center.Configurator{}
break
}
override := url.GetParams()
- delete(override, constant.ANYHOST_KEY)
+ delete(override, constant.AnyhostKey)
if len(override) == 0 {
continue
}
diff --git a/registry/base_registry.go b/registry/base_registry.go
index bdc9915..52f4dc1 100644
--- a/registry/base_registry.go
+++ b/registry/base_registry.go
@@ -144,8 +144,8 @@ func (r *BaseRegistry) Register(conf *common.URL) error {
conf.Port = portToRegistry
}
// todo bug when provider、consumer simultaneous initialization
- //role, _ := strconv.Atoi(r.URL.GetParam(constant.ROLE_KEY, ""))
- role, _ := strconv.Atoi(conf.GetParam(constant.ROLE_KEY, ""))
+ //role, _ := strconv.Atoi(r.URL.GetParam(constant.RoleKey, ""))
+ role, _ := strconv.Atoi(conf.GetParam(constant.RoleKey, ""))
// Check if the service has been registered
r.cltLock.Lock()
_, ok = r.services[conf.Key()]
@@ -270,8 +270,8 @@ func (r *BaseRegistry) processURL(c *common.URL, f func(string, string) error, c
params.Add("ip", localIP)
// params.Add("timeout", fmt.Sprintf("%d", int64(r.Timeout)/1e6))
- role, _ := strconv.Atoi(c.GetParam(constant.ROLE_KEY, ""))
- //role, _ := strconv.Atoi(r.URL.GetParam(constant.ROLE_KEY, ""))
+ role, _ := strconv.Atoi(c.GetParam(constant.RoleKey, ""))
+ //role, _ := strconv.Atoi(r.URL.GetParam(constant.RoleKey, ""))
switch role {
case common.PROVIDER:
@@ -320,13 +320,13 @@ func (r *BaseRegistry) providerRegistry(c *common.URL, params url.Values, f crea
logger.Errorf("facadeBasedRegistry.CreatePath(path{%s}) = error{%#v}", dubboPath, perrors.WithStack(err))
return "", "", perrors.WithMessagef(err, "facadeBasedRegistry.CreatePath(path:%s)", dubboPath)
}
- params.Add(constant.ANYHOST_KEY, "true")
+ params.Add(constant.AnyhostKey, "true")
// Dubbo java consumer to start looking for the provider url,because the category does not match,
// the provider will not find, causing the consumer can not start, so we use consumers.
if len(c.Methods) != 0 {
- params.Add(constant.METHODS_KEY, strings.Join(c.Methods, ","))
+ params.Add(constant.MethodsKey, strings.Join(c.Methods, ","))
}
logger.Debugf("provider url params:%#v", params)
var host string
diff --git a/registry/directory/directory.go b/registry/directory/directory.go
index bec0334..0a340af 100644
--- a/registry/directory/directory.go
+++ b/registry/directory/directory.go
@@ -191,7 +191,7 @@ func (dir *RegistryDirectory) refreshAllInvokers(events []*registry.ServiceEvent
if event != nil && event.Service != nil {
logger.Infof("selector add service url{%s}", event.Service.String())
}
- if event != nil && event.Service != nil && constant.ROUTER_PROTOCOL == event.Service.Protocol {
+ if event != nil && event.Service != nil && constant.RouterProtocol == event.Service.Protocol {
dir.configRouters()
}
if oldInvoker, _ := dir.doCacheInvoker(event.Service, event); oldInvoker != nil {
@@ -246,7 +246,7 @@ func (dir *RegistryDirectory) cacheInvokerByEvent(event *registry.ServiceEvent)
case remoting.EventTypeAdd, remoting.EventTypeUpdate:
u := dir.convertUrl(event)
logger.Infof("selector add service url{%s}", event.Service)
- if u != nil && constant.ROUTER_PROTOCOL == u.Protocol {
+ if u != nil && constant.RouterProtocol == u.Protocol {
dir.configRouters()
}
return dir.cacheInvoker(u, event), nil
@@ -267,12 +267,12 @@ func (dir *RegistryDirectory) configRouters() {
// convertUrl processes override:// and router://
func (dir *RegistryDirectory) convertUrl(res *registry.ServiceEvent) *common.URL {
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 {
+ if ret.Protocol == constant.OverrideProtocol || // 1.for override url in 2.6.x
+ ret.GetParam(constant.CategoryKey, constant.DefaultCategory) == constant.ConfiguratorsCategory {
dir.configurators = append(dir.configurators, extension.GetDefaultConfigurator(ret))
ret = nil
- } else if ret.Protocol == constant.ROUTER_PROTOCOL || // 2.for router
- ret.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY) == constant.ROUTER_CATEGORY {
+ } else if ret.Protocol == constant.RouterProtocol || // 2.for router
+ ret.GetParam(constant.CategoryKey, constant.DefaultCategory) == constant.RouterCategory {
ret = nil
}
return ret
@@ -291,7 +291,7 @@ func (dir *RegistryDirectory) toGroupInvokers() []protocol.Invoker {
})
for _, invoker := range newInvokersList {
- group := invoker.GetURL().GetParam(constant.GROUP_KEY, "")
+ group := invoker.GetURL().GetParam(constant.GroupKey, "")
groupInvokersMap[group] = append(groupInvokersMap[group], invoker)
}
@@ -304,7 +304,7 @@ func (dir *RegistryDirectory) toGroupInvokers() []protocol.Invoker {
} else {
for _, invokers := range groupInvokersMap {
staticDir := static.NewDirectory(invokers)
- cst := extension.GetCluster(dir.GetURL().SubURL.GetParam(constant.CLUSTER_KEY, constant.DEFAULT_CLUSTER))
+ cst := extension.GetCluster(dir.GetURL().SubURL.GetParam(constant.ClusterKey, constant.DefaultCluster))
err = staticDir.BuildRouterChain(invokers)
if err != nil {
logger.Error(err)
diff --git a/registry/directory/directory_test.go b/registry/directory/directory_test.go
index 49f305e..ce760cc 100644
--- a/registry/directory/directory_test.go
+++ b/registry/directory/directory_test.go
@@ -82,36 +82,36 @@ func Test_List(t *testing.T) {
func Test_MergeProviderUrl(t *testing.T) {
registryDirectory, mockRegistry := normalRegistryDir(true)
providerUrl, _ := common.NewURL("dubbo://0.0.0.0:20000/org.apache.dubbo-go.mockService",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock1"),
- common.WithParamsValue(constant.GROUP_KEY, "group"),
- common.WithParamsValue(constant.VERSION_KEY, "1.0.0"))
+ common.WithParamsValue(constant.ClusterKey, "mock1"),
+ common.WithParamsValue(constant.GroupKey, "group"),
+ common.WithParamsValue(constant.VersionKey, "1.0.0"))
mockRegistry.MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: providerUrl})
time.Sleep(1e9)
assert.Len(t, registryDirectory.cacheInvokers, 1)
if len(registryDirectory.cacheInvokers) > 0 {
- assert.Equal(t, "mock", registryDirectory.cacheInvokers[0].GetURL().GetParam(constant.CLUSTER_KEY, ""))
+ assert.Equal(t, "mock", registryDirectory.cacheInvokers[0].GetURL().GetParam(constant.ClusterKey, ""))
}
}
func Test_MergeOverrideUrl(t *testing.T) {
registryDirectory, mockRegistry := normalRegistryDir(true)
providerUrl, _ := common.NewURL("dubbo://0.0.0.0:20000/org.apache.dubbo-go.mockService",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
- common.WithParamsValue(constant.GROUP_KEY, "group"),
- common.WithParamsValue(constant.VERSION_KEY, "1.0.0"))
+ common.WithParamsValue(constant.ClusterKey, "mock"),
+ common.WithParamsValue(constant.GroupKey, "group"),
+ common.WithParamsValue(constant.VersionKey, "1.0.0"))
mockRegistry.MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: providerUrl})
Loop1:
for {
if len(registryDirectory.cacheInvokers) > 0 {
overrideUrl, _ := common.NewURL("override://0.0.0.0:20000/org.apache.dubbo-go.mockService",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock1"),
- common.WithParamsValue(constant.GROUP_KEY, "group"),
- common.WithParamsValue(constant.VERSION_KEY, "1.0.0"))
+ common.WithParamsValue(constant.ClusterKey, "mock1"),
+ common.WithParamsValue(constant.GroupKey, "group"),
+ common.WithParamsValue(constant.VersionKey, "1.0.0"))
mockRegistry.MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: overrideUrl})
Loop2:
for {
if len(registryDirectory.cacheInvokers) > 0 {
- if "mock1" == registryDirectory.cacheInvokers[0].GetURL().GetParam(constant.CLUSTER_KEY, "") {
+ if "mock1" == registryDirectory.cacheInvokers[0].GetURL().GetParam(constant.ClusterKey, "") {
assert.Len(t, registryDirectory.cacheInvokers, 1)
assert.True(t, true)
break Loop2
@@ -128,13 +128,13 @@ Loop1:
func Test_RefreshUrl(t *testing.T) {
registryDirectory, mockRegistry := normalRegistryDir()
providerUrl, _ := common.NewURL("dubbo://0.0.0.0:20011/org.apache.dubbo-go.mockService",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock1"),
- common.WithParamsValue(constant.GROUP_KEY, "group"),
- common.WithParamsValue(constant.VERSION_KEY, "1.0.0"))
+ common.WithParamsValue(constant.ClusterKey, "mock1"),
+ common.WithParamsValue(constant.GroupKey, "group"),
+ common.WithParamsValue(constant.VersionKey, "1.0.0"))
providerUrl2, _ := common.NewURL("dubbo://0.0.0.0:20012/org.apache.dubbo-go.mockService",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock1"),
- common.WithParamsValue(constant.GROUP_KEY, "group"),
- common.WithParamsValue(constant.VERSION_KEY, "1.0.0"))
+ common.WithParamsValue(constant.ClusterKey, "mock1"),
+ common.WithParamsValue(constant.GroupKey, "group"),
+ common.WithParamsValue(constant.VersionKey, "1.0.0"))
time.Sleep(1e9)
assert.Len(t, registryDirectory.cacheInvokers, 3)
mockRegistry.MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: providerUrl})
@@ -161,9 +161,9 @@ func normalRegistryDir(noMockEvent ...bool) (*RegistryDirectory, *registry.MockR
url, _ := common.NewURL("mock://127.0.0.1:1111")
suburl, _ := common.NewURL(
"dubbo://127.0.0.1:20000/org.apache.dubbo-go.mockService",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
- common.WithParamsValue(constant.GROUP_KEY, "group"),
- common.WithParamsValue(constant.VERSION_KEY, "1.0.0"),
+ common.WithParamsValue(constant.ClusterKey, "mock"),
+ common.WithParamsValue(constant.GroupKey, "group"),
+ common.WithParamsValue(constant.VersionKey, "1.0.0"),
)
url.SubURL = suburl
mockRegistry, _ := registry.NewMockRegistry(&common.URL{})
diff --git a/registry/etcdv3/registry.go b/registry/etcdv3/registry.go
index c777154..2576021 100644
--- a/registry/etcdv3/registry.go
+++ b/registry/etcdv3/registry.go
@@ -74,7 +74,7 @@ func (r *etcdV3Registry) ClientLock() *sync.Mutex {
}
func newETCDV3Registry(url *common.URL) (registry.Registry, error) {
- timeout := url.GetParamDuration(constant.CONFIG_TIMEOUT_KEY, constant.DEFAULT_REG_TIMEOUT)
+ timeout := url.GetParamDuration(constant.ConfigTimeoutKey, constant.DefaultRegTimeout)
logger.Infof("etcd address is: %v, timeout is: %s", url.Location, timeout.String())
@@ -160,7 +160,7 @@ func (r *etcdV3Registry) DoSubscribe(svc *common.URL) (registry.Listener, error)
// register the svc to dataListener
r.dataListener.AddInterestedURL(svc)
- go r.listener.ListenServiceEvent(fmt.Sprintf("/dubbo/%s/"+constant.DEFAULT_CATEGORY, svc.Service()), r.dataListener)
+ go r.listener.ListenServiceEvent(fmt.Sprintf("/dubbo/%s/"+constant.DefaultCategory, svc.Service()), r.dataListener)
return configListener, nil
}
diff --git a/registry/etcdv3/registry_test.go b/registry/etcdv3/registry_test.go
index 1cd300b..beca799 100644
--- a/registry/etcdv3/registry_test.go
+++ b/registry/etcdv3/registry_test.go
@@ -33,7 +33,7 @@ import (
)
func initRegistry(t *testing.T) *etcdV3Registry {
- regurl, err := common.NewURL("registry://127.0.0.1:2379", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
+ regurl, err := common.NewURL("registry://127.0.0.1:2379", common.WithParamsValue(constant.RoleKey, strconv.Itoa(common.PROVIDER)))
if err != nil {
t.Fatal(err)
}
@@ -53,7 +53,7 @@ func initRegistry(t *testing.T) *etcdV3Registry {
//func (suite *RegistryTestSuite) TestRegister() {
// t := suite.T()
//
-// url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
+// url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.ClusterKey, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
//
// reg := initRegistry(t)
// err := reg.Register(url)
@@ -68,8 +68,8 @@ func initRegistry(t *testing.T) *etcdV3Registry {
//
//func (suite *RegistryTestSuite) TestSubscribe() {
// t := suite.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"}))
+// regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.RoleKey, strconv.Itoa(common.PROVIDER)))
+// url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.ClusterKey, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
//
// reg := initRegistry(t)
// // provider register
@@ -79,7 +79,7 @@ func initRegistry(t *testing.T) *etcdV3Registry {
// }
//
// // consumer register
-// regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER))
+// regurl.SetParam(constant.RoleKey, strconv.Itoa(common.Consumer))
// reg2 := initRegistry(t)
//
// err = reg2.Register(url)
@@ -98,7 +98,7 @@ func initRegistry(t *testing.T) *etcdV3Registry {
func (suite *RegistryTestSuite) TestConsumerDestroy() {
t := suite.T()
- url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
+ url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.ClusterKey, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
reg := initRegistry(t)
_, err := reg.DoSubscribe(url)
@@ -116,7 +116,7 @@ func (suite *RegistryTestSuite) TestConsumerDestroy() {
func (suite *RegistryTestSuite) TestProviderDestroy() {
t := suite.T()
reg := initRegistry(t)
- url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
+ url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.ClusterKey, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
err := reg.Register(url)
assert.NoError(t, err)
diff --git a/registry/etcdv3/service_discovery.go b/registry/etcdv3/service_discovery.go
index a99ea94..02d3c7e 100644
--- a/registry/etcdv3/service_discovery.go
+++ b/registry/etcdv3/service_discovery.go
@@ -49,7 +49,7 @@ const (
var initLock sync.Mutex
func init() {
- extension.SetServiceDiscovery(constant.ETCDV3_KEY, newEtcdV3ServiceDiscovery)
+ extension.SetServiceDiscovery(constant.EtcdV3Key, newEtcdV3ServiceDiscovery)
}
// new etcd service discovery struct
@@ -235,12 +235,12 @@ func toPath(instance registry.ServiceInstance) string {
return ""
}
// like: /services/servicename1/host(127.0.0.1)/8080
- return fmt.Sprintf("%s%d", ROOT+constant.PATH_SEPARATOR+instance.GetServiceName()+constant.PATH_SEPARATOR+instance.GetHost()+constant.KEY_SEPARATOR, instance.GetPort())
+ return fmt.Sprintf("%s%d", ROOT+constant.PathSeparator+instance.GetServiceName()+constant.PathSeparator+instance.GetHost()+constant.KeySeparator, instance.GetPort())
}
// to dubbo service path
func toParentPath(serviceName string) string {
- return ROOT + constant.PATH_SEPARATOR + serviceName
+ return ROOT + constant.PathSeparator + serviceName
}
// register service instance listener, instance listener and watcher are matched through serviceName
diff --git a/registry/event/base_configuration_listener.go b/registry/event/base_configuration_listener.go
index 0985c78..a9e2106 100644
--- a/registry/event/base_configuration_listener.go
+++ b/registry/event/base_configuration_listener.go
@@ -55,7 +55,7 @@ func (bcl *BaseConfigurationListener) InitWith(key string, listener config_cente
bcl.defaultConfiguratorFunc = f
bcl.dynamicConfiguration.AddListener(key, listener)
if rawConfig, err := bcl.dynamicConfiguration.GetInternalProperty(key,
- config_center.WithGroup(constant.DUBBO)); err != nil {
+ config_center.WithGroup(constant.Dubbo)); err != nil {
// set configurators to empty
bcl.configurators = []config_center.Configurator{}
return
@@ -102,13 +102,13 @@ func ToConfigurators(urls []*common.URL, f func(url *common.URL) config_center.C
}
var configurators []config_center.Configurator
for _, url := range urls {
- if url.Protocol == constant.EMPTY_PROTOCOL {
+ if url.Protocol == constant.EmptyProtocol {
configurators = []config_center.Configurator{}
break
}
override := url.GetParams()
- delete(override, constant.ANYHOST_KEY)
+ delete(override, constant.AnyhostKey)
if len(override) == 0 {
continue
}
diff --git a/registry/event/metadata_service_url_params_customizer.go b/registry/event/metadata_service_url_params_customizer.go
index 53e79b4..205e3ce 100644
--- a/registry/event/metadata_service_url_params_customizer.go
+++ b/registry/event/metadata_service_url_params_customizer.go
@@ -36,12 +36,12 @@ import (
func init() {
exceptKeys := gxset.NewSet(
- // remove APPLICATION_KEY because service name must be present
- constant.APPLICATION_KEY,
- // remove GROUP_KEY, always uses service name.
- constant.GROUP_KEY,
- // remove TIMESTAMP_KEY because it's nonsense
- constant.TIMESTAMP_KEY)
+ // remove ApplicationKey because service name must be present
+ constant.ApplicationKey,
+ // remove GroupKey, always uses service name.
+ constant.GroupKey,
+ // remove TimestampKey because it's nonsense
+ constant.TimestampKey)
extension.AddCustomizers(&metadataServiceURLParamsMetadataCustomizer{exceptKeys: exceptKeys})
}
@@ -71,7 +71,7 @@ func (m *metadataServiceURLParamsMetadataCustomizer) Customize(instance registry
logger.Errorf("could not transfer the map to json", err)
return
}
- instance.GetMetadata()[constant.METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME] = string(str)
+ instance.GetMetadata()[constant.MetadataServiceURLParamsPropertyName] = string(str)
}
func (m *metadataServiceURLParamsMetadataCustomizer) convertToParams(url *common.URL) map[string]string {
@@ -84,7 +84,7 @@ func (m *metadataServiceURLParamsMetadataCustomizer) convertToParams(url *common
}
p[k] = v[0]
}
- p[constant.PORT_KEY] = url.Port
- p[constant.PROTOCOL_KEY] = url.Protocol
+ p[constant.PortKey] = url.Port
+ p[constant.ProtocolKey] = url.Protocol
return p
}
diff --git a/registry/event/protocol_ports_metadata_customizer.go b/registry/event/protocol_ports_metadata_customizer.go
index 058c0b9..8478aff 100644
--- a/registry/event/protocol_ports_metadata_customizer.go
+++ b/registry/event/protocol_ports_metadata_customizer.go
@@ -73,7 +73,7 @@ func (p *ProtocolPortsMetadataCustomizer) Customize(instance registry.ServiceIns
protocolMap[u.Protocol] = port
}
- instance.GetMetadata()[constant.SERVICE_INSTANCE_ENDPOINTS] = endpointsStr(protocolMap)
+ instance.GetMetadata()[constant.ServiceInstanceEndpoints] = endpointsStr(protocolMap)
}
// endpointsStr convert the map to json like [{"protocol": "dubbo", "port": 123}]
diff --git a/registry/event/service_instances_changed_listener_impl.go b/registry/event/service_instances_changed_listener_impl.go
index 6d6ab00..4992175 100644
--- a/registry/event/service_instances_changed_listener_impl.go
+++ b/registry/event/service_instances_changed_listener_impl.go
@@ -74,7 +74,7 @@ func (lstn *ServiceInstancesChangedListenerImpl) OnEvent(e observer.Event) error
logger.Warnf("Instance metadata is nil: %s", instance.GetHost())
continue
}
- revision := instance.GetMetadata()[constant.EXPORTED_SERVICES_REVISION_PROPERTY_NAME]
+ revision := instance.GetMetadata()[constant.ExportedServicesRevisionPropertyName]
if "0" == revision {
logger.Infof("Find instance without valid service metadata: %s", instance.GetHost())
continue
@@ -141,16 +141,16 @@ func (lstn *ServiceInstancesChangedListenerImpl) OnEvent(e observer.Event) error
return nil
}
-// getMetadataInfo get metadata info when METADATA_STORAGE_TYPE_PROPERTY_NAME is null
+// getMetadataInfo get metadata info when MetadataStorageTypePropertyName is null
func (lstn *ServiceInstancesChangedListenerImpl) getMetadataInfo(instance registry.ServiceInstance, revision string) (*common.MetadataInfo, error) {
var metadataStorageType string
var metadataInfo *common.MetadataInfo
if instance.GetMetadata() == nil {
- metadataStorageType = constant.DEFAULT_METADATA_STORAGE_TYPE
+ metadataStorageType = constant.DefaultMetadataStorageType
} else {
- metadataStorageType = instance.GetMetadata()[constant.METADATA_STORAGE_TYPE_PROPERTY_NAME]
+ metadataStorageType = instance.GetMetadata()[constant.MetadataStorageTypePropertyName]
}
- if metadataStorageType == constant.REMOTE_METADATA_STORAGE_TYPE {
+ if metadataStorageType == constant.RemoteMetadataStorageType {
remoteMetadataServiceImpl, err := extension.GetRemoteMetadataService()
if err != nil {
return nil, err
@@ -161,7 +161,7 @@ func (lstn *ServiceInstancesChangedListenerImpl) getMetadataInfo(instance regist
}
} else {
var err error
- proxyFactory := extension.GetMetadataServiceProxyFactory(constant.DEFAULT_KEY)
+ proxyFactory := extension.GetMetadataServiceProxyFactory(constant.DefaultKey)
metadataService := proxyFactory.GetProxy(instance)
metadataInfo, err = metadataService.GetMetadataInfo(revision)
if err != nil {
diff --git a/registry/event/service_revision_customizer.go b/registry/event/service_revision_customizer.go
index 77e022c..c648eed 100644
--- a/registry/event/service_revision_customizer.go
+++ b/registry/event/service_revision_customizer.go
@@ -54,7 +54,7 @@ func (e *exportedServicesRevisionMetadataCustomizer) Customize(instance registry
return
}
- urls, err := ms.GetExportedURLs(constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE)
+ urls, err := ms.GetExportedURLs(constant.AnyValue, constant.AnyValue, constant.AnyValue, constant.AnyValue)
if err != nil {
logger.Errorf("could not find the exported url", err)
}
@@ -63,7 +63,7 @@ func (e *exportedServicesRevisionMetadataCustomizer) Customize(instance registry
if len(revision) == 0 {
revision = defaultRevision
}
- instance.GetMetadata()[constant.EXPORTED_SERVICES_REVISION_PROPERTY_NAME] = revision
+ instance.GetMetadata()[constant.ExportedServicesRevisionPropertyName] = revision
}
type subscribedServicesRevisionMetadataCustomizer struct{}
@@ -90,7 +90,7 @@ func (e *subscribedServicesRevisionMetadataCustomizer) Customize(instance regist
if len(revision) == 0 {
revision = defaultRevision
}
- instance.GetMetadata()[constant.SUBSCRIBED_SERVICES_REVISION_PROPERTY_NAME] = revision
+ instance.GetMetadata()[constant.SubscribedServicesRevisionPropertyName] = revision
}
// resolveRevision is different from Dubbo because golang doesn't support overload
@@ -104,14 +104,14 @@ func resolveRevision(urls []*common.URL) string {
candidates := make([]string, 0, len(urls))
for _, u := range urls {
- sk := u.GetParam(constant.INTERFACE_KEY, "")
+ sk := u.GetParam(constant.InterfaceKey, "")
if len(u.Methods) == 0 {
candidates = append(candidates, sk)
} else {
for _, m := range u.Methods {
// methods are part of candidates
- candidates = append(candidates, sk+constant.KEY_SEPARATOR+m)
+ candidates = append(candidates, sk+constant.KeySeparator+m)
}
}
diff --git a/registry/file/service_discovery.go b/registry/file/service_discovery.go
index 4fabafb..6c8960e 100644
--- a/registry/file/service_discovery.go
+++ b/registry/file/service_discovery.go
@@ -46,7 +46,7 @@ import (
// init will put the service discovery into extension
func init() {
- extension.SetServiceDiscovery(constant.FILE_KEY, newFileSystemServiceDiscovery)
+ extension.SetServiceDiscovery(constant.FileKey, newFileSystemServiceDiscovery)
}
// fileServiceDiscovery is the implementation of service discovery based on file.
@@ -57,7 +57,7 @@ type fileSystemServiceDiscovery struct {
}
func newFileSystemServiceDiscovery() (registry.ServiceDiscovery, error) {
- if config.GetMetadataReportConfg().Protocol != constant.FILE_KEY {
+ if config.GetMetadataReportConfg().Protocol != constant.FileKey {
return nil, perrors.New("could not init the instance because the config is invalid")
}
@@ -66,8 +66,8 @@ func newFileSystemServiceDiscovery() (registry.ServiceDiscovery, error) {
return nil, perrors.WithStack(err)
}
- fdcf := extension.GetConfigCenterFactory(constant.FILE_KEY)
- p := path.Join(rp, ".dubbo", constant.REGISTRY_KEY)
+ fdcf := extension.GetConfigCenterFactory(constant.FileKey)
+ p := path.Join(rp, ".dubbo", constant.RegistryKey)
url, _ := common.NewURL("")
url.AddParamAvoidNil(file.ConfigCenterDirParamName, p)
c, err := fdcf.GetDynamicConfiguration(url)
diff --git a/registry/kubernetes/registry.go b/registry/kubernetes/registry.go
index b6e1107..63af25f 100644
--- a/registry/kubernetes/registry.go
+++ b/registry/kubernetes/registry.go
@@ -137,7 +137,7 @@ func (r *kubernetesRegistry) DoSubscribe(svc *common.URL) (registry.Listener, er
// register the svc to dataListener
r.dataListener.AddInterestedURL(svc)
- go r.listener.ListenServiceEvent(fmt.Sprintf("/dubbo/%s/"+constant.DEFAULT_CATEGORY, svc.Service()), r.dataListener)
+ go r.listener.ListenServiceEvent(fmt.Sprintf("/dubbo/%s/"+constant.DefaultCategory, svc.Service()), r.dataListener)
return configListener, nil
}
diff --git a/registry/kubernetes/registry_test.go b/registry/kubernetes/registry_test.go
index 1125a9e..d3ab0de 100644
--- a/registry/kubernetes/registry_test.go
+++ b/registry/kubernetes/registry_test.go
@@ -226,7 +226,7 @@ func getTestRegistry(t *testing.T) *kubernetesRegistry {
}
}
- regurl, err := common.NewURL("registry://127.0.0.1:443", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
+ regurl, err := common.NewURL("registry://127.0.0.1:443", common.WithParamsValue(constant.RoleKey, strconv.Itoa(common.PROVIDER)))
if err != nil {
t.Fatal(err)
}
@@ -244,7 +244,7 @@ func TestRegister(t *testing.T) {
url, _ := common.NewURL(
"dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
+ common.WithParamsValue(constant.ClusterKey, "mock"),
common.WithMethods([]string{"GetUser", "AddUser"}),
)
@@ -261,7 +261,7 @@ func TestRegister(t *testing.T) {
// r := getTestRegistry(t)
// defer r.Destroy()
//
-// url, err := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
+// url, err := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.ClusterKey, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
// if err != nil {
// t.Fatal(err)
// }
@@ -294,7 +294,7 @@ func TestConsumerDestroy(t *testing.T) {
r := getTestRegistry(t)
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
+ common.WithParamsValue(constant.ClusterKey, "mock"),
common.WithMethods([]string{"GetUser", "AddUser"}))
_, err := r.DoSubscribe(url)
@@ -313,7 +313,7 @@ func TestProviderDestroy(t *testing.T) {
r := getTestRegistry(t)
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
+ common.WithParamsValue(constant.ClusterKey, "mock"),
common.WithMethods([]string{"GetUser", "AddUser"}))
err := r.Register(url)
assert.NoError(t, err)
@@ -325,7 +325,7 @@ func TestProviderDestroy(t *testing.T) {
func TestNewRegistry(t *testing.T) {
regUrl, err := common.NewURL("registry://127.0.0.1:443",
- common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
+ common.WithParamsValue(constant.RoleKey, strconv.Itoa(common.PROVIDER)))
if err != nil {
t.Fatal(err)
}
diff --git a/registry/nacos/listener.go b/registry/nacos/listener.go
index 8dad195..3ed949c 100644
--- a/registry/nacos/listener.go
+++ b/registry/nacos/listener.go
@@ -179,9 +179,9 @@ func getSubscribeName(url *common.URL) string {
var buffer bytes.Buffer
buffer.Write([]byte(common.DubboNodes[common.PROVIDER]))
- appendParam(&buffer, url, constant.INTERFACE_KEY)
- appendParam(&buffer, url, constant.VERSION_KEY)
- appendParam(&buffer, url, constant.GROUP_KEY)
+ appendParam(&buffer, url, constant.InterfaceKey)
+ appendParam(&buffer, url, constant.VersionKey)
+ appendParam(&buffer, url, constant.GroupKey)
return buffer.String()
}
@@ -190,7 +190,7 @@ func (nl *nacosListener) startListen() error {
return perrors.New("nacos naming namingClient stopped")
}
serviceName := getSubscribeName(nl.listenUrl)
- groupName := nl.listenUrl.GetParam(constant.REGISTRY_GROUP_KEY, defaultGroup)
+ groupName := nl.listenUrl.GetParam(constant.RegistryGroupKey, defaultGroup)
nl.subscribeParam = &vo.SubscribeParam{
ServiceName: serviceName,
SubscribeCallback: nl.Callback,
diff --git a/registry/nacos/registry.go b/registry/nacos/registry.go
index 348555c..af61e8c 100644
--- a/registry/nacos/registry.go
+++ b/registry/nacos/registry.go
@@ -50,7 +50,7 @@ const (
func init() {
localIP = common.GetLocalIp()
- extension.SetRegistry(constant.NACOS_KEY, newNacosRegistry)
+ extension.SetRegistry(constant.NacosKey, newNacosRegistry)
}
type nacosRegistry struct {
@@ -60,7 +60,7 @@ type nacosRegistry struct {
}
func getCategory(url *common.URL) string {
- role, _ := strconv.Atoi(url.GetParam(constant.ROLE_KEY, strconv.Itoa(constant.NACOS_DEFAULT_ROLETYPE)))
+ role, _ := strconv.Atoi(url.GetParam(constant.RoleKey, strconv.Itoa(constant.NacosDefaultRoleType)))
category := common.DubboNodes[role]
return category
}
@@ -69,15 +69,15 @@ func getServiceName(url *common.URL) string {
var buffer bytes.Buffer
buffer.Write([]byte(getCategory(url)))
- appendParam(&buffer, url, constant.INTERFACE_KEY)
- appendParam(&buffer, url, constant.VERSION_KEY)
- appendParam(&buffer, url, constant.GROUP_KEY)
+ appendParam(&buffer, url, constant.InterfaceKey)
+ appendParam(&buffer, url, constant.VersionKey)
+ appendParam(&buffer, url, constant.GroupKey)
return buffer.String()
}
func appendParam(target *bytes.Buffer, url *common.URL, key string) {
value := url.GetParam(key, "")
- target.Write([]byte(constant.NACOS_SERVICE_NAME_SEPARATOR))
+ target.Write([]byte(constant.NacosServiceNameSeparator))
if strings.TrimSpace(value) != "" {
target.Write([]byte(value))
}
@@ -92,9 +92,9 @@ func createRegisterParam(url *common.URL, serviceName string, groupName string)
return true
})
- params[constant.NACOS_CATEGORY_KEY] = category
- params[constant.NACOS_PROTOCOL_KEY] = url.Protocol
- params[constant.NACOS_PATH_KEY] = url.Path
+ params[constant.NacosCategoryKey] = category
+ params[constant.NacosProtocolKey] = url.Protocol
+ params[constant.NacosPathKey] = url.Path
if len(url.Ip) == 0 {
url.Ip = localIP
}
@@ -119,7 +119,7 @@ func createRegisterParam(url *common.URL, serviceName string, groupName string)
// Register will register the service @url to its nacos registry center
func (nr *nacosRegistry) Register(url *common.URL) error {
serviceName := getServiceName(url)
- groupName := nr.URL.GetParam(constant.GROUP_KEY, defaultGroup)
+ groupName := nr.URL.GetParam(constant.GroupKey, defaultGroup)
param := createRegisterParam(url, serviceName, groupName)
isRegistry, err := nr.namingClient.Client().RegisterInstance(param)
if err != nil {
@@ -151,7 +151,7 @@ func createDeregisterParam(url *common.URL, serviceName string, groupName string
func (nr *nacosRegistry) DeRegister(url *common.URL) error {
serviceName := getServiceName(url)
- groupName := nr.URL.GetParam(constant.GROUP_KEY, defaultGroup)
+ groupName := nr.URL.GetParam(constant.GroupKey, defaultGroup)
param := createDeregisterParam(url, serviceName, groupName)
isDeRegistry, err := nr.namingClient.Client().DeregisterInstance(param)
if err != nil {
@@ -175,8 +175,8 @@ func (nr *nacosRegistry) subscribe(conf *common.URL) (registry.Listener, error)
// subscribe from registry
func (nr *nacosRegistry) Subscribe(url *common.URL, notifyListener registry.NotifyListener) error {
// TODO
- // role, _ := strconv.Atoi(nr.URL.GetParam(constant.ROLE_KEY, ""))
- role, _ := strconv.Atoi(url.GetParam(constant.ROLE_KEY, ""))
+ // role, _ := strconv.Atoi(nr.URL.GetParam(constant.RoleKey, ""))
+ role, _ := strconv.Atoi(url.GetParam(constant.RoleKey, ""))
if role != common.CONSUMER {
return nil
}
@@ -187,8 +187,8 @@ func (nr *nacosRegistry) Subscribe(url *common.URL, notifyListener registry.Noti
return perrors.New("nacosRegistry is not available.")
}
- groupName := nr.GetParam(constant.GROUP_KEY, defaultGroup)
- url.SetParam(constant.REGISTRY_GROUP_KEY, groupName) // update to registry.group
+ groupName := nr.GetParam(constant.GroupKey, defaultGroup)
+ url.SetParam(constant.RegistryGroupKey, groupName) // update to registry.group
listener, err := nr.subscribe(url)
if err != nil {
diff --git a/registry/nacos/registry_test.go b/registry/nacos/registry_test.go
index 4728019..36f46d7 100644
--- a/registry/nacos/registry_test.go
+++ b/registry/nacos/registry_test.go
@@ -43,16 +43,16 @@ func TestNacosRegistry_Register(t *testing.T) {
return
}
regurlMap := url.Values{}
- regurlMap.Set(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))
- regurlMap.Set(constant.NACOS_NOT_LOAD_LOCAL_CACHE, "true")
+ regurlMap.Set(constant.RoleKey, strconv.Itoa(common.PROVIDER))
+ regurlMap.Set(constant.NacosNotLoadLocalCache, "true")
regurl, _ := common.NewURL("registry://console.nacos.io:80", common.WithParams(regurlMap))
urlMap := url.Values{}
- urlMap.Set(constant.GROUP_KEY, "guangzhou-idc")
- urlMap.Set(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))
- urlMap.Set(constant.INTERFACE_KEY, "com.ikurento.user.UserProvider")
- urlMap.Set(constant.VERSION_KEY, "1.0.0")
- urlMap.Set(constant.CLUSTER_KEY, "mock")
+ urlMap.Set(constant.GroupKey, "guangzhou-idc")
+ urlMap.Set(constant.RoleKey, strconv.Itoa(common.PROVIDER))
+ urlMap.Set(constant.InterfaceKey, "com.ikurento.user.UserProvider")
+ urlMap.Set(constant.VersionKey, "1.0.0")
+ urlMap.Set(constant.ClusterKey, "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(regurl)
@@ -80,17 +80,17 @@ func TestNacosRegistry_Subscribe(t *testing.T) {
return
}
regurlMap := url.Values{}
- regurlMap.Set(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))
- regurlMap.Set(constant.NACOS_NOT_LOAD_LOCAL_CACHE, "true")
+ regurlMap.Set(constant.RoleKey, strconv.Itoa(common.PROVIDER))
+ regurlMap.Set(constant.NacosNotLoadLocalCache, "true")
regurl, _ := common.NewURL("registry://console.nacos.io:80", common.WithParams(regurlMap))
urlMap := url.Values{}
- urlMap.Set(constant.GROUP_KEY, "guangzhou-idc")
- urlMap.Set(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))
- urlMap.Set(constant.INTERFACE_KEY, "com.dubbo.user.UserProvider")
- urlMap.Set(constant.VERSION_KEY, "1.0.0")
- urlMap.Set(constant.CLUSTER_KEY, "mock")
- urlMap.Set(constant.NACOS_PATH_KEY, "")
+ urlMap.Set(constant.GroupKey, "guangzhou-idc")
+ urlMap.Set(constant.RoleKey, strconv.Itoa(common.PROVIDER))
+ urlMap.Set(constant.InterfaceKey, "com.dubbo.user.UserProvider")
+ urlMap.Set(constant.VersionKey, "1.0.0")
+ urlMap.Set(constant.ClusterKey, "mock")
+ urlMap.Set(constant.NacosPathKey, "")
testUrl, _ := common.NewURL("dubbo://127.0.0.1:20000/com.dubbo.user.UserProvider", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"}))
reg, _ := newNacosRegistry(regurl)
@@ -101,7 +101,7 @@ func TestNacosRegistry_Subscribe(t *testing.T) {
return
}
- regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER))
+ regurl.SetParam(constant.RoleKey, strconv.Itoa(common.CONSUMER))
reg2, _ := newNacosRegistry(regurl)
listener, err := reg2.(*nacosRegistry).subscribe(testUrl)
assert.Nil(t, err)
@@ -124,17 +124,17 @@ func TestNacosRegistry_Subscribe_del(t *testing.T) {
return
}
regurlMap := url.Values{}
- regurlMap.Set(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))
- regurlMap.Set(constant.NACOS_NOT_LOAD_LOCAL_CACHE, "true")
+ regurlMap.Set(constant.RoleKey, strconv.Itoa(common.PROVIDER))
+ regurlMap.Set(constant.NacosNotLoadLocalCache, "true")
regurl, _ := common.NewURL("registry://console.nacos.io:80", common.WithParams(regurlMap))
urlMap := url.Values{}
- urlMap.Set(constant.GROUP_KEY, "guangzhou-idc")
- urlMap.Set(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))
- urlMap.Set(constant.INTERFACE_KEY, "com.ikurento.user.UserProvider")
- urlMap.Set(constant.VERSION_KEY, "2.0.0")
- urlMap.Set(constant.CLUSTER_KEY, "mock")
- urlMap.Set(constant.NACOS_PATH_KEY, "")
+ urlMap.Set(constant.GroupKey, "guangzhou-idc")
+ urlMap.Set(constant.RoleKey, strconv.Itoa(common.PROVIDER))
+ urlMap.Set(constant.InterfaceKey, "com.ikurento.user.UserProvider")
+ urlMap.Set(constant.VersionKey, "2.0.0")
+ urlMap.Set(constant.ClusterKey, "mock")
+ urlMap.Set(constant.NacosPathKey, "")
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"}))
@@ -152,7 +152,7 @@ func TestNacosRegistry_Subscribe_del(t *testing.T) {
return
}
- regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER))
+ regurl.SetParam(constant.RoleKey, strconv.Itoa(common.CONSUMER))
reg2, _ := newNacosRegistry(regurl)
listener, err := reg2.(*nacosRegistry).subscribe(url1)
assert.Nil(t, err)
@@ -198,17 +198,17 @@ func TestNacosRegistry_Subscribe_del(t *testing.T) {
func TestNacosListener_Close(t *testing.T) {
regurlMap := url.Values{}
- regurlMap.Set(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))
- regurlMap.Set(constant.NACOS_NOT_LOAD_LOCAL_CACHE, "true")
+ regurlMap.Set(constant.RoleKey, strconv.Itoa(common.PROVIDER))
+ regurlMap.Set(constant.NacosNotLoadLocalCache, "true")
regurl, _ := common.NewURL("registry://console.nacos.io:80", common.WithParams(regurlMap))
urlMap := url.Values{}
- urlMap.Set(constant.GROUP_KEY, "guangzhou-idc")
- urlMap.Set(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER))
- urlMap.Set(constant.INTERFACE_KEY, "com.ikurento.user.UserProvider2")
- urlMap.Set(constant.VERSION_KEY, "1.0.0")
- urlMap.Set(constant.CLUSTER_KEY, "mock")
- urlMap.Set(constant.NACOS_PATH_KEY, "")
+ urlMap.Set(constant.GroupKey, "guangzhou-idc")
+ urlMap.Set(constant.RoleKey, strconv.Itoa(common.PROVIDER))
+ urlMap.Set(constant.InterfaceKey, "com.ikurento.user.UserProvider2")
+ urlMap.Set(constant.VersionKey, "1.0.0")
+ urlMap.Set(constant.ClusterKey, "mock")
+ urlMap.Set(constant.NacosPathKey, "")
url1, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider2", common.WithParams(urlMap), common.WithMethods([]string{"GetUser", "AddUser"}))
reg, _ := newNacosRegistry(regurl)
listener, err := reg.(*nacosRegistry).subscribe(url1)
diff --git a/registry/nacos/service_discovery.go b/registry/nacos/service_discovery.go
index 58717a5..b69053f 100644
--- a/registry/nacos/service_discovery.go
+++ b/registry/nacos/service_discovery.go
@@ -45,13 +45,13 @@ import (
)
const (
- defaultGroup = constant.SERVICE_DISCOVERY_DEFAULT_GROUP
+ defaultGroup = constant.ServiceDiscoveryDefaultGroup
idKey = "id"
)
// init will put the service discovery into extension
func init() {
- extension.SetServiceDiscovery(constant.NACOS_KEY, newNacosServiceDiscovery)
+ extension.SetServiceDiscovery(constant.NacosKey, newNacosServiceDiscovery)
}
// nacosServiceDiscovery is the implementation of service discovery based on nacos.
@@ -336,7 +336,7 @@ func newNacosServiceDiscovery() (registry.ServiceDiscovery, error) {
common.WithParams(make(url.Values)),
common.WithPassword(metadataReportConfig.Password),
common.WithUsername(metadataReportConfig.Username),
- common.WithParamsValue(constant.REGISTRY_TIMEOUT_KEY, metadataReportConfig.Timeout))
+ common.WithParamsValue(constant.RegistryTimeoutKey, metadataReportConfig.Timeout))
url.Location = metadataReportConfig.Address
client, err := nacos.NewNacosClientByUrl(url)
if err != nil {
diff --git a/registry/protocol/protocol.go b/registry/protocol/protocol.go
index 01dbdf2..ce19d38 100644
--- a/registry/protocol/protocol.go
+++ b/registry/protocol/protocol.go
@@ -136,8 +136,8 @@ func (proto *registryProtocol) GetRegistries() []registry.Registry {
func (proto *registryProtocol) Refer(url *common.URL) protocol.Invoker {
registryUrl := url
serviceUrl := registryUrl.SubURL
- if registryUrl.Protocol == constant.REGISTRY_PROTOCOL {
- registryUrl.Protocol = registryUrl.GetParam(constant.REGISTRY_KEY, "")
+ if registryUrl.Protocol == constant.RegistryProtocol {
+ registryUrl.Protocol = registryUrl.GetParam(constant.RegistryKey, "")
}
var reg registry.Registry
@@ -163,7 +163,7 @@ func (proto *registryProtocol) Refer(url *common.URL) protocol.Invoker {
}
// new cluster invoker
- cluster := extension.GetCluster(serviceUrl.GetParam(constant.CLUSTER_KEY, constant.DEFAULT_CLUSTER))
+ cluster := extension.GetCluster(serviceUrl.GetParam(constant.ClusterKey, constant.DefaultCluster))
invoker := cluster.Join(directory)
proto.invokers = append(proto.invokers, invoker)
return invoker
@@ -245,7 +245,7 @@ func registerServiceMap(invoker protocol.Invoker) error {
providerUrl := getProviderUrl(invoker)
// the bean.name param of providerUrl is the ServiceConfig id property
// such as dubbo://:20000/org.apache.dubbo.UserProvider?bean.name=UserProvider&cluster=failfast...
- id := providerUrl.GetParam(constant.BEAN_NAME_KEY, "")
+ id := providerUrl.GetParam(constant.BeanNameKey, "")
serviceConfig := config.GetProviderConfig().Services[id]
if serviceConfig == nil {
@@ -329,51 +329,51 @@ func (nl *overrideSubscribeListener) doOverrideIfNecessary() {
func isMatched(providerUrl *common.URL, consumerUrl *common.URL) bool {
// Compatible with the 2.6.x
- if len(providerUrl.GetParam(constant.CATEGORY_KEY, "")) == 0 &&
- providerUrl.Protocol == constant.OVERRIDE_PROTOCOL {
- providerUrl.AddParam(constant.CATEGORY_KEY, constant.CONFIGURATORS_CATEGORY)
+ if len(providerUrl.GetParam(constant.CategoryKey, "")) == 0 &&
+ providerUrl.Protocol == constant.OverrideProtocol {
+ providerUrl.AddParam(constant.CategoryKey, constant.ConfiguratorsCategory)
}
- consumerInterface := consumerUrl.GetParam(constant.INTERFACE_KEY, consumerUrl.Path)
- providerInterface := providerUrl.GetParam(constant.INTERFACE_KEY, providerUrl.Path)
+ consumerInterface := consumerUrl.GetParam(constant.InterfaceKey, consumerUrl.Path)
+ providerInterface := providerUrl.GetParam(constant.InterfaceKey, providerUrl.Path)
- if !(constant.ANY_VALUE == consumerInterface ||
- constant.ANY_VALUE == providerInterface ||
+ if !(constant.AnyValue == consumerInterface ||
+ constant.AnyValue == providerInterface ||
providerInterface == consumerInterface) {
return false
}
- if !isMatchCategory(providerUrl.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY),
- consumerUrl.GetParam(constant.CATEGORY_KEY, constant.DEFAULT_CATEGORY)) {
+ if !isMatchCategory(providerUrl.GetParam(constant.CategoryKey, constant.DefaultCategory),
+ consumerUrl.GetParam(constant.CategoryKey, constant.DefaultCategory)) {
return false
}
- if !providerUrl.GetParamBool(constant.ENABLED_KEY, true) &&
- consumerUrl.GetParam(constant.ENABLED_KEY, "") != constant.ANY_VALUE {
+ if !providerUrl.GetParamBool(constant.EnabledKey, true) &&
+ consumerUrl.GetParam(constant.EnabledKey, "") != constant.AnyValue {
return false
}
- consumerGroup := consumerUrl.GetParam(constant.GROUP_KEY, "")
- consumerVersion := consumerUrl.GetParam(constant.VERSION_KEY, "")
- consumerClassifier := consumerUrl.GetParam(constant.CLASSIFIER_KEY, "")
+ consumerGroup := consumerUrl.GetParam(constant.GroupKey, "")
+ consumerVersion := consumerUrl.GetParam(constant.VersionKey, "")
+ consumerClassifier := consumerUrl.GetParam(constant.ClassifierKey, "")
- providerGroup := providerUrl.GetParam(constant.GROUP_KEY, "")
- providerVersion := providerUrl.GetParam(constant.VERSION_KEY, "")
- providerClassifier := providerUrl.GetParam(constant.CLASSIFIER_KEY, "")
+ providerGroup := providerUrl.GetParam(constant.GroupKey, "")
+ providerVersion := providerUrl.GetParam(constant.VersionKey, "")
+ providerClassifier := providerUrl.GetParam(constant.ClassifierKey, "")
// todo: public static boolean isContains(String values, String value) {
- // return isNotEmpty(values) && isContains(COMMA_SPLIT_PATTERN.split(values), value);
+ // return isNotEmpty(values) && isContains(CommaSplitPattern.split(values), value);
// }
- return (consumerGroup == constant.ANY_VALUE || consumerGroup == providerGroup ||
- strings.Contains(consumerGroup, providerGroup)) && (consumerVersion == constant.ANY_VALUE ||
+ return (consumerGroup == constant.AnyValue || consumerGroup == providerGroup ||
+ strings.Contains(consumerGroup, providerGroup)) && (consumerVersion == constant.AnyValue ||
consumerVersion == providerVersion) && (len(consumerClassifier) == 0 ||
- consumerClassifier == constant.ANY_VALUE || consumerClassifier == providerClassifier)
+ consumerClassifier == constant.AnyValue || consumerClassifier == providerClassifier)
}
func isMatchCategory(category string, categories string) bool {
if len(categories) == 0 {
- return category == constant.DEFAULT_CATEGORY
- } else if strings.Contains(categories, constant.ANY_VALUE) {
+ return category == constant.DefaultCategory
+ } else if strings.Contains(categories, constant.AnyValue) {
return true
- } else if strings.Contains(categories, constant.REMOVE_VALUE_PREFIX) {
- return !strings.Contains(categories, constant.REMOVE_VALUE_PREFIX+category)
+ } else if strings.Contains(categories, constant.RemoveValuePrefix) {
+ return !strings.Contains(categories, constant.RemoveValuePrefix+category)
} else {
return strings.Contains(categories, category)
}
@@ -381,9 +381,9 @@ func isMatchCategory(category string, categories string) bool {
func getSubscribedOverrideUrl(providerUrl *common.URL) *common.URL {
newUrl := providerUrl.Clone()
- newUrl.Protocol = constant.PROVIDER_PROTOCOL
- newUrl.SetParam(constant.CATEGORY_KEY, constant.CONFIGURATORS_CATEGORY)
- newUrl.SetParam(constant.CHECK_KEY, "false")
+ newUrl.Protocol = constant.ProviderProtocol
+ newUrl.SetParam(constant.CategoryKey, constant.ConfiguratorsCategory)
+ newUrl.SetParam(constant.CheckKey, "false")
return newUrl
}
@@ -411,8 +411,8 @@ func getRegistryUrl(invoker protocol.Invoker) *common.URL {
// here add * for return a new url
url := invoker.GetURL()
// if the protocol == registry, set protocol the registry value in url.params
- if url.Protocol == constant.REGISTRY_PROTOCOL {
- url.Protocol = url.GetParam(constant.REGISTRY_KEY, "")
+ if url.Protocol == constant.RegistryProtocol {
+ url.Protocol = url.GetParam(constant.RegistryKey, "")
}
return url
}
diff --git a/registry/protocol/protocol_test.go b/registry/protocol/protocol_test.go
index 8c57db0..0bef773 100644
--- a/registry/protocol/protocol_test.go
+++ b/registry/protocol/protocol_test.go
@@ -58,7 +58,7 @@ func referNormal(t *testing.T, regProtocol *registryProtocol) {
url, _ := common.NewURL("mock://127.0.0.1:1111")
suburl, _ := common.NewURL(
"dubbo://127.0.0.1:20000//",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
+ common.WithParamsValue(constant.ClusterKey, "mock"),
)
url.SubURL = suburl
@@ -82,7 +82,7 @@ func TestMultiRegRefer(t *testing.T) {
url2, _ := common.NewURL("mock://127.0.0.1:2222")
suburl2, _ := common.NewURL(
"dubbo://127.0.0.1:20000//",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
+ common.WithParamsValue(constant.ClusterKey, "mock"),
)
url2.SubURL = suburl2
@@ -103,7 +103,7 @@ func TestOneRegRefer(t *testing.T) {
url2, _ := common.NewURL("mock://127.0.0.1:1111")
suburl2, _ := common.NewURL(
"dubbo://127.0.0.1:20000//",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
+ common.WithParamsValue(constant.ClusterKey, "mock"),
)
url2.SubURL = suburl2
@@ -124,9 +124,9 @@ func exporterNormal(t *testing.T, regProtocol *registryProtocol) *common.URL {
url, _ := common.NewURL("mock://127.0.0.1:1111")
suburl, _ := common.NewURL(
"dubbo://127.0.0.1:20000/org.apache.dubbo-go.mockService",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
- common.WithParamsValue(constant.GROUP_KEY, "group"),
- common.WithParamsValue(constant.VERSION_KEY, "1.0.0"),
+ common.WithParamsValue(constant.ClusterKey, "mock"),
+ common.WithParamsValue(constant.GroupKey, "group"),
+ common.WithParamsValue(constant.VersionKey, "1.0.0"),
)
url.SubURL = suburl
@@ -150,7 +150,7 @@ func TestMultiRegAndMultiProtoExporter(t *testing.T) {
url2, _ := common.NewURL("mock://127.0.0.1:2222")
suburl2, _ := common.NewURL(
"jsonrpc://127.0.0.1:20000//",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
+ common.WithParamsValue(constant.ClusterKey, "mock"),
)
url2.SubURL = suburl2
@@ -179,9 +179,9 @@ func TestOneRegAndProtoExporter(t *testing.T) {
url2, _ := common.NewURL("mock://127.0.0.1:1111")
suburl2, _ := common.NewURL(
"dubbo://127.0.0.1:20000/org.apache.dubbo-go.mockService",
- common.WithParamsValue(constant.CLUSTER_KEY, "mock"),
- common.WithParamsValue(constant.GROUP_KEY, "group"),
- common.WithParamsValue(constant.VERSION_KEY, "1.0.0"),
+ common.WithParamsValue(constant.ClusterKey, "mock"),
+ common.WithParamsValue(constant.GroupKey, "group"),
+ common.WithParamsValue(constant.VersionKey, "1.0.0"),
)
url2.SubURL = suburl2
@@ -245,7 +245,7 @@ func TestExportWithOverrideListener(t *testing.T) {
reg.MockEvent(event)
time.Sleep(1e9)
newUrl := url.SubURL.Clone()
- newUrl.SetParam(constant.CLUSTER_KEY, "mock1")
+ newUrl.SetParam(constant.ClusterKey, "mock1")
delKeys := gxset.NewSet("dynamic", "enabled")
key := newUrl.CloneExceptParams(delKeys).String()
v2, _ := regProtocol.bounds.Load(key)
@@ -266,7 +266,7 @@ func TestExportWithServiceConfig(t *testing.T) {
dc.(*config_center.MockDynamicConfiguration).MockServiceConfigEvent()
newUrl := url.SubURL.Clone()
- newUrl.SetParam(constant.CLUSTER_KEY, "mock1")
+ newUrl.SetParam(constant.ClusterKey, "mock1")
delKeys := gxset.NewSet("dynamic", "enabled")
key := newUrl.CloneExceptParams(delKeys).String()
@@ -289,7 +289,7 @@ func TestExportWithApplicationConfig(t *testing.T) {
dc.(*config_center.MockDynamicConfiguration).MockApplicationConfigEvent()
newUrl := url.SubURL.Clone()
- newUrl.SetParam(constant.CLUSTER_KEY, "mock1")
+ newUrl.SetParam(constant.ClusterKey, "mock1")
delKeys := gxset.NewSet("dynamic", "enabled")
key := newUrl.CloneExceptParams(delKeys).String()
v2, _ := regProtocol.bounds.Load(key)
diff --git a/registry/service_instance.go b/registry/service_instance.go
index 12cc350..b329da5 100644
--- a/registry/service_instance.go
+++ b/registry/service_instance.go
@@ -155,7 +155,7 @@ func (d *DefaultServiceInstance) ToURLs() []*common.URL {
// GetEndPoints get end points from metadata
func (d *DefaultServiceInstance) GetEndPoints() []*Endpoint {
- rawEndpoints := d.Metadata[constant.SERVICE_INSTANCE_ENDPOINTS]
+ rawEndpoints := d.Metadata[constant.ServiceInstanceEndpoints]
if len(rawEndpoints) == 0 {
return nil
}
diff --git a/registry/servicediscovery/service_discovery_registry.go b/registry/servicediscovery/service_discovery_registry.go
index c1d9839..fcd2d2b 100644
--- a/registry/servicediscovery/service_discovery_registry.go
+++ b/registry/servicediscovery/service_discovery_registry.go
@@ -45,7 +45,7 @@ import (
)
func init() {
- extension.SetRegistry(constant.SERVICE_REGISTRY_PROTOCOL, newServiceDiscoveryRegistry)
+ extension.SetRegistry(constant.ServiceRegistryProtocol, newServiceDiscoveryRegistry)
}
// serviceDiscoveryRegistry is the implementation of application-level registry.
@@ -71,7 +71,7 @@ func newServiceDiscoveryRegistry(url *common.URL) (registry.Registry, error) {
if err != nil {
return nil, err
}
- subscribedServices := parseServices(url.GetParam(constant.SUBSCRIBED_SERVICE_NAMES_KEY, ""))
+ subscribedServices := parseServices(url.GetParam(constant.SubscribedServiceNamesKey, ""))
subscribedURLsSynthesizers := synthesizer.GetAllSynthesizer()
serviceNameMapping := extension.GetGlobalServiceNameMapping()
metaDataService, err := local.GetLocalMetadataService()
@@ -118,7 +118,7 @@ func (s *serviceDiscoveryRegistry) UnSubscribe(url *common.URL, listener registr
}
func creatServiceDiscovery(url *common.URL) (registry.ServiceDiscovery, error) {
- sdcName := url.GetParam(constant.REGISTRY_KEY, "")
+ sdcName := url.GetParam(constant.RegistryKey, "")
originServiceDiscovery, err := extension.GetServiceDiscovery(sdcName)
if err != nil {
return nil, perrors.WithMessage(err, "Create service discovery fialed")
@@ -180,8 +180,8 @@ func (s *serviceDiscoveryRegistry) Register(url *common.URL) error {
}
func shouldRegister(url *common.URL) bool {
- side := url.GetParam(constant.SIDE_KEY, "")
- if side == constant.PROVIDER_PROTOCOL {
+ side := url.GetParam(constant.SideKey, "")
+ if side == constant.ProviderProtocol {
return true
}
logger.Debugf("The URL should not be register.", url.String())
@@ -245,9 +245,9 @@ func getUrlKey(url *common.URL) string {
bf.WriteString(url.Path)
}
bf.WriteString("?")
- appendParam(bf, constant.VERSION_KEY, url)
- appendParam(bf, constant.GROUP_KEY, url)
- appendParam(bf, constant.NACOS_PROTOCOL_KEY, url)
+ appendParam(bf, constant.VersionKey, url)
+ appendParam(bf, constant.GroupKey, url)
+ appendParam(bf, constant.NacosProtocolKey, url)
return bf.String()
}
@@ -273,7 +273,7 @@ func shouldSubscribe(url *common.URL) bool {
func (s *serviceDiscoveryRegistry) getServices(url *common.URL) *gxset.HashSet {
services := gxset.NewSet()
- serviceNames := url.GetParam(constant.PROVIDED_BY, "")
+ serviceNames := url.GetParam(constant.ProvidedBy, "")
if len(serviceNames) > 0 {
services = parseServices(serviceNames)
}
diff --git a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
index aa4c84a..6823662 100644
--- a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
+++ b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
@@ -45,11 +45,11 @@ func (r RestSubscribedURLsSynthesizer) Synthesize(subscribedURL *common.URL, ser
for i, s := range serviceInstances {
splitHost := strings.Split(s.GetHost(), ":")
u := common.NewURLWithOptions(common.WithProtocol(subscribedURL.Protocol), common.WithIp(splitHost[0]),
- common.WithPort(splitHost[1]), common.WithPath(subscribedURL.GetParam(constant.INTERFACE_KEY, subscribedURL.Path)),
+ common.WithPort(splitHost[1]), common.WithPath(subscribedURL.GetParam(constant.InterfaceKey, subscribedURL.Path)),
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.SIDE_KEY, constant.PROVIDER_PROTOCOL),
- common.WithParamsValue(constant.APPLICATION_KEY, s.GetServiceName()),
- common.WithParamsValue(constant.REGISTRY_KEY, "true"),
+ common.WithParamsValue(constant.SideKey, constant.ProviderProtocol),
+ common.WithParamsValue(constant.ApplicationKey, s.GetServiceName()),
+ common.WithParamsValue(constant.RegistryKey, "true"),
)
urls[i] = u
}
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 3a20fdf..5d809a4 100644
--- a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer_test.go
+++ b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer_test.go
@@ -60,15 +60,15 @@ func TestRestSubscribedURLsSynthesizer_Synthesize(t *testing.T) {
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{}),
- common.WithParamsValue(constant.SIDE_KEY, constant.PROVIDER_PROTOCOL),
- common.WithParamsValue(constant.APPLICATION_KEY, "test1"),
- common.WithParamsValue(constant.REGISTRY_KEY, "true"))
+ common.WithParamsValue(constant.SideKey, constant.ProviderProtocol),
+ common.WithParamsValue(constant.ApplicationKey, "test1"),
+ common.WithParamsValue(constant.RegistryKey, "true"))
u2 := common.NewURLWithOptions(common.WithProtocol("rest"), common.WithIp("127.0.0.2"),
common.WithPort("8081"), common.WithPath("org.apache.dubbo-go.mockService"),
common.WithParams(url.Values{}),
- common.WithParamsValue(constant.SIDE_KEY, constant.PROVIDER_PROTOCOL),
- common.WithParamsValue(constant.APPLICATION_KEY, "test2"),
- common.WithParamsValue(constant.REGISTRY_KEY, "true"))
+ common.WithParamsValue(constant.SideKey, constant.ProviderProtocol),
+ common.WithParamsValue(constant.ApplicationKey, "test2"),
+ common.WithParamsValue(constant.RegistryKey, "true"))
expectUrls = append(expectUrls, u1, u2)
result := syn.Synthesize(subUrl, instances)
assert.Equal(t, expectUrls, result)
diff --git a/registry/zookeeper/registry.go b/registry/zookeeper/registry.go
index 029654d..b6c64b9 100644
--- a/registry/zookeeper/registry.go
+++ b/registry/zookeeper/registry.go
@@ -139,7 +139,7 @@ func (r *zkRegistry) InitListeners() {
regConfigListener.Close()
}
newDataListener.SubscribeURL(regConfigListener.subscribeURL, NewRegistryConfigurationListener(r.client, r, regConfigListener.subscribeURL))
- go r.listener.ListenServiceEvent(regConfigListener.subscribeURL, fmt.Sprintf("/dubbo/%s/"+constant.DEFAULT_CATEGORY, url.QueryEscape(regConfigListener.subscribeURL.Service())), newDataListener)
+ go r.listener.ListenServiceEvent(regConfigListener.subscribeURL, fmt.Sprintf("/dubbo/%s/"+constant.DefaultCategory, url.QueryEscape(regConfigListener.subscribeURL.Service())), newDataListener)
}
}
@@ -244,8 +244,8 @@ func (r *zkRegistry) registerTempZookeeperNode(root string, node string) error {
func (r *zkRegistry) getListener(conf *common.URL) (*RegistryConfigurationListener, error) {
var zkListener *RegistryConfigurationListener
dataListener := r.dataListener
- ttl := r.GetParam(constant.REGISTRY_TTL_KEY, constant.DEFAULT_REG_TTL)
- conf.SetParam(constant.REGISTRY_TTL_KEY, ttl)
+ ttl := r.GetParam(constant.RegistryTTLKey, constant.DefaultRegTTL)
+ conf.SetParam(constant.RegistryTTLKey, ttl)
dataListener.mutex.Lock()
defer dataListener.mutex.Unlock()
if r.dataListener.subscribed[conf.ServiceKey()] != nil {
@@ -281,7 +281,7 @@ func (r *zkRegistry) getListener(conf *common.URL) (*RegistryConfigurationListen
// Interested register to dataconfig.
r.dataListener.SubscribeURL(conf, zkListener)
- go r.listener.ListenServiceEvent(conf, fmt.Sprintf("/dubbo/%s/"+constant.DEFAULT_CATEGORY, url.QueryEscape(conf.Service())), r.dataListener)
+ go r.listener.ListenServiceEvent(conf, fmt.Sprintf("/dubbo/%s/"+constant.DefaultCategory, url.QueryEscape(conf.Service())), r.dataListener)
return zkListener, nil
}
diff --git a/registry/zookeeper/service_discovery.go b/registry/zookeeper/service_discovery.go
index 6ea4082..b2b1391 100644
--- a/registry/zookeeper/service_discovery.go
+++ b/registry/zookeeper/service_discovery.go
@@ -45,7 +45,7 @@ import (
// init will put the service discovery into extension
func init() {
- extension.SetServiceDiscovery(constant.ZOOKEEPER_KEY, newZookeeperServiceDiscovery)
+ extension.SetServiceDiscovery(constant.ZookeeperKey, newZookeeperServiceDiscovery)
}
type zookeeperServiceDiscovery struct {
@@ -70,7 +70,7 @@ func newZookeeperServiceDiscovery() (registry.ServiceDiscovery, error) {
common.WithParams(make(url.Values)),
common.WithPassword(metadataReportConfig.Password),
common.WithUsername(metadataReportConfig.Username),
- common.WithParamsValue(constant.REGISTRY_TIMEOUT_KEY, metadataReportConfig.Timeout))
+ common.WithParamsValue(constant.RegistryTimeoutKey, metadataReportConfig.Timeout))
url.Location = metadataReportConfig.Address
zksd := &zookeeperServiceDiscovery{
url: url,
@@ -274,9 +274,9 @@ func (zksd *zookeeperServiceDiscovery) AddListener(listener registry.ServiceInst
// to resolve event to do DispatchEventByServiceName
func (zksd *zookeeperServiceDiscovery) DataChange(eventType remoting.Event) bool {
path := strings.TrimPrefix(eventType.Path, zksd.rootPath)
- path = strings.TrimPrefix(path, constant.PATH_SEPARATOR)
+ path = strings.TrimPrefix(path, constant.PathSeparator)
// get service name in zk path
- serviceName := strings.Split(path, constant.PATH_SEPARATOR)[0]
+ serviceName := strings.Split(path, constant.PathSeparator)[0]
var err error
instances := zksd.GetInstances(serviceName)
diff --git a/remoting/getty/dubbo_codec_for_test.go b/remoting/getty/dubbo_codec_for_test.go
index b7bd064..39abebd 100644
--- a/remoting/getty/dubbo_codec_for_test.go
+++ b/remoting/getty/dubbo_codec_for_test.go
@@ -58,12 +58,12 @@ func (c *DubboTestCodec) EncodeRequest(request *remoting.Request) (*bytes.Buffer
tmpInvocation := invoc
svc := impl.Service{}
- 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.Path = tmpInvocation.AttachmentsByKey(constant.PathKey, "")
+ svc.Interface = tmpInvocation.AttachmentsByKey(constant.InterfaceKey, "")
+ svc.Version = tmpInvocation.AttachmentsByKey(constant.VersionKey, "")
+ svc.Group = tmpInvocation.AttachmentsByKey(constant.GroupKey, "")
svc.Method = tmpInvocation.MethodName()
- timeout, err := strconv.Atoi(tmpInvocation.AttachmentsByKey(constant.TIMEOUT_KEY, strconv.Itoa(constant.DEFAULT_REMOTING_TIMEOUT)))
+ timeout, err := strconv.Atoi(tmpInvocation.AttachmentsByKey(constant.TimeoutKey, strconv.Itoa(constant.DefaultRemotingTimeout)))
if err != nil {
// it will be wrapped in readwrite.Write .
return nil, perrors.WithStack(err)
@@ -71,11 +71,11 @@ func (c *DubboTestCodec) EncodeRequest(request *remoting.Request) (*bytes.Buffer
svc.Timeout = time.Duration(timeout)
header := impl.DubboHeader{}
- serialization := tmpInvocation.AttachmentsByKey(constant.SERIALIZATION_KEY, constant.HESSIAN2_SERIALIZATION)
- if serialization == constant.PROTOBUF_SERIALIZATION {
- header.SerialID = constant.S_Proto
+ serialization := tmpInvocation.AttachmentsByKey(constant.SerializationKey, constant.Hessian2Serialization)
+ if serialization == constant.ProtobufSerialization {
+ header.SerialID = constant.SProto
} else {
- header.SerialID = constant.S_Hessian2
+ header.SerialID = constant.SHessian2
}
header.ID = request.ID
if request.TwoWay {
@@ -103,7 +103,7 @@ func (c *DubboTestCodec) EncodeRequest(request *remoting.Request) (*bytes.Buffer
func (c *DubboTestCodec) encodeHeartbeartReqeust(request *remoting.Request) (*bytes.Buffer, error) {
header := impl.DubboHeader{
Type: impl.PackageHeartbeat,
- SerialID: constant.S_Hessian2,
+ SerialID: constant.SHessian2,
ID: request.ID,
}
@@ -208,9 +208,9 @@ func (c *DubboTestCodec) decodeRequest(data []byte) (*remoting.Request, int, err
request.Version = req[impl.DubboVersionKey].(string)
}
// path
- attachments[constant.PATH_KEY] = pkg.Service.Path
+ attachments[constant.PathKey] = pkg.Service.Path
// version
- attachments[constant.VERSION_KEY] = pkg.Service.Version
+ attachments[constant.VersionKey] = pkg.Service.Version
// method
methodName = pkg.Service.Method
args = req[impl.ArgsKey].([]interface{})
diff --git a/remoting/getty/getty_client.go b/remoting/getty/getty_client.go
index d6ca10d..9931194 100644
--- a/remoting/getty/getty_client.go
+++ b/remoting/getty/getty_client.go
@@ -161,7 +161,7 @@ func (c *Client) SetExchangeClient(client *remoting.ExchangeClient) {
func (c *Client) Connect(url *common.URL) error {
initClient(url.Protocol)
c.conf = *clientConf
- c.sslEnabled = url.GetParamBool(constant.SSL_ENABLED_KEY, false)
+ c.sslEnabled = url.GetParamBool(constant.SslEnabledKey, false)
// codec
c.codec = remoting.GetCodec(url.Protocol)
c.addr = url.Location
diff --git a/remoting/getty/getty_client_test.go b/remoting/getty/getty_client_test.go
index 2820681..346bd7c 100644
--- a/remoting/getty/getty_client_test.go
+++ b/remoting/getty/getty_client_test.go
@@ -58,7 +58,7 @@ func testRequestOneWay(t *testing.T, client *Client) {
request := remoting.NewRequest("2.0.2")
invocation := createInvocation("GetUser", nil, nil, []interface{}{"1", "username"},
[]reflect.Value{reflect.ValueOf("1"), reflect.ValueOf("username")})
- attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
+ attachment := map[string]string{InterfaceKey: "com.ikurento.user.UserProvider"}
setAttachment(invocation, attachment)
request.Data = invocation
request.Event = false
@@ -109,7 +109,7 @@ func testGetBigPkg(t *testing.T, c *Client) {
request := remoting.NewRequest("2.0.2")
invocation := createInvocation("GetBigPkg", nil, nil, []interface{}{[]interface{}{nil}, user},
[]reflect.Value{reflect.ValueOf([]interface{}{nil}), reflect.ValueOf(user)})
- attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
+ attachment := map[string]string{InterfaceKey: "com.ikurento.user.UserProvider"}
setAttachment(invocation, attachment)
request.Data = invocation
request.Event = false
@@ -128,7 +128,7 @@ func testGetUser(t *testing.T, c *Client) {
request := remoting.NewRequest("2.0.2")
invocation := createInvocation("GetUser", nil, nil, []interface{}{"1", "username"},
[]reflect.Value{reflect.ValueOf("1"), reflect.ValueOf("username")})
- attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
+ attachment := map[string]string{InterfaceKey: "com.ikurento.user.UserProvider"}
setAttachment(invocation, attachment)
request.Data = invocation
request.Event = false
@@ -150,7 +150,7 @@ func testGetUser0(t *testing.T, c *Client) {
request := remoting.NewRequest("2.0.2")
invocation := createInvocation("GetUser0", nil, nil, []interface{}{"1", nil, "username"},
[]reflect.Value{reflect.ValueOf("1"), reflect.ValueOf(nil), reflect.ValueOf("username")})
- attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
+ attachment := map[string]string{InterfaceKey: "com.ikurento.user.UserProvider"}
setAttachment(invocation, attachment)
request.Data = invocation
request.Event = false
@@ -169,7 +169,7 @@ func testGetUser1(t *testing.T, c *Client) {
request := remoting.NewRequest("2.0.2")
invocation := createInvocation("GetUser1", nil, nil, []interface{}{},
[]reflect.Value{})
- attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
+ attachment := map[string]string{InterfaceKey: "com.ikurento.user.UserProvider"}
setAttachment(invocation, attachment)
request.Data = invocation
request.Event = false
@@ -187,7 +187,7 @@ func testGetUser2(t *testing.T, c *Client) {
request := remoting.NewRequest("2.0.2")
invocation := createInvocation("GetUser2", nil, nil, []interface{}{},
[]reflect.Value{})
- attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
+ attachment := map[string]string{InterfaceKey: "com.ikurento.user.UserProvider"}
setAttachment(invocation, attachment)
request.Data = invocation
request.Event = false
@@ -204,7 +204,7 @@ func testGetUser3(t *testing.T, c *Client) {
invocation := createInvocation("GetUser3", nil, nil, []interface{}{},
[]reflect.Value{})
attachment := map[string]string{
- INTERFACE_KEY: "com.ikurento.user.UserProvider",
+ InterfaceKey: "com.ikurento.user.UserProvider",
}
setAttachment(invocation, attachment)
request.Data = invocation
@@ -223,7 +223,7 @@ func testGetUser4(t *testing.T, c *Client) {
var err error
request := remoting.NewRequest("2.0.2")
invocation := invocation.NewRPCInvocation("GetUser4", []interface{}{[]interface{}{"1", "username"}}, nil)
- attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
+ attachment := map[string]string{InterfaceKey: "com.ikurento.user.UserProvider"}
setAttachment(invocation, attachment)
request.Data = invocation
request.Event = false
@@ -241,7 +241,7 @@ func testGetUser5(t *testing.T, c *Client) {
var err error
request := remoting.NewRequest("2.0.2")
invocation := invocation.NewRPCInvocation("GetUser5", []interface{}{map[interface{}]interface{}{"id": "1", "name": "username"}}, nil)
- attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
+ attachment := map[string]string{InterfaceKey: "com.ikurento.user.UserProvider"}
setAttachment(invocation, attachment)
request.Data = invocation
request.Event = false
@@ -264,7 +264,7 @@ func testGetUser6(t *testing.T, c *Client) {
user = &User{}
request := remoting.NewRequest("2.0.2")
invocation := invocation.NewRPCInvocation("GetUser6", []interface{}{0}, nil)
- attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
+ attachment := map[string]string{InterfaceKey: "com.ikurento.user.UserProvider"}
setAttachment(invocation, attachment)
request.Data = invocation
request.Event = false
@@ -285,7 +285,7 @@ func testGetUser61(t *testing.T, c *Client) {
user = &User{}
request := remoting.NewRequest("2.0.2")
invocation := invocation.NewRPCInvocation("GetUser6", []interface{}{1}, nil)
- attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
+ attachment := map[string]string{InterfaceKey: "com.ikurento.user.UserProvider"}
setAttachment(invocation, attachment)
request.Data = invocation
request.Event = false
@@ -304,7 +304,7 @@ func testClient_AsyncCall(t *testing.T, client *Client) {
request := remoting.NewRequest("2.0.2")
invocation := createInvocation("GetUser0", nil, nil, []interface{}{"4", nil, "username"},
[]reflect.Value{reflect.ValueOf("4"), reflect.ValueOf(nil), reflect.ValueOf("username")})
- attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
+ attachment := map[string]string{InterfaceKey: "com.ikurento.user.UserProvider"}
setAttachment(invocation, attachment)
request.Data = invocation
request.Event = false
diff --git a/remoting/getty/getty_server.go b/remoting/getty/getty_server.go
index e53f0d4..d1f0a5f 100644
--- a/remoting/getty/getty_server.go
+++ b/remoting/getty/getty_server.go
@@ -117,7 +117,7 @@ func NewServer(url *common.URL, handlers func(*invocation.RPCInvocation) protoco
// init
initServer(url.Protocol)
- srvConf.SSLEnabled = url.GetParamBool(constant.SSL_ENABLED_KEY, false)
+ srvConf.SSLEnabled = url.GetParamBool(constant.SslEnabledKey, false)
s := &Server{
conf: *srvConf,
diff --git a/remoting/getty/listener.go b/remoting/getty/listener.go
index fc9d2f4..78b0f61 100644
--- a/remoting/getty/listener.go
+++ b/remoting/getty/listener.go
@@ -300,8 +300,8 @@ func (h *RpcServerHandler) OnMessage(session getty.Session, pkg interface{}) {
panic("create invocation occur some exception for the type is not suitable one.")
}
attachments := invoc.Attachments()
- attachments[constant.LOCAL_ADDR] = session.LocalAddr()
- attachments[constant.REMOTE_ADDR] = session.RemoteAddr()
+ attachments[constant.LocalAddr] = session.LocalAddr()
+ attachments[constant.RemoteAddr] = session.RemoteAddr()
result := h.server.requestHandler(invoc)
if !req.TwoWay {
diff --git a/remoting/getty/listener_test.go b/remoting/getty/listener_test.go
index 6d22e37..d5adc48 100644
--- a/remoting/getty/listener_test.go
+++ b/remoting/getty/listener_test.go
@@ -38,14 +38,14 @@ import (
func TestRebuildCtx(t *testing.T) {
opentracing.SetGlobalTracer(mocktracer.New())
attach := make(map[string]interface{}, 10)
- attach[constant.VERSION_KEY] = "1.0"
- attach[constant.GROUP_KEY] = "MyGroup"
+ attach[constant.VersionKey] = "1.0"
+ attach[constant.GroupKey] = "MyGroup"
inv := invocation.NewRPCInvocation("MethodName", []interface{}{"OK", "Hello"}, attach)
// attachment doesn't contains any tracing key-value pair,
ctx := rebuildCtx(inv)
assert.NotNil(t, ctx)
- assert.Nil(t, ctx.Value(constant.TRACING_REMOTE_SPAN_CTX))
+ assert.Nil(t, ctx.Value(constant.TracingRemoteSpanCtx))
span, ctx := opentracing.StartSpanFromContext(ctx, "Test-Client")
assert.NotNil(t, ctx)
@@ -57,7 +57,7 @@ func TestRebuildCtx(t *testing.T) {
ctx = rebuildCtx(inv)
span.Finish()
assert.NotNil(t, ctx)
- assert.NotNil(t, ctx.Value(constant.TRACING_REMOTE_SPAN_CTX))
+ assert.NotNil(t, ctx.Value(constant.TracingRemoteSpanCtx))
}
// rebuildCtx rebuild the context by attachment.
@@ -70,7 +70,7 @@ func rebuildCtx(inv *invocation.RPCInvocation) context.Context {
spanCtx, err := opentracing.GlobalTracer().Extract(opentracing.TextMap,
opentracing.TextMapCarrier(filterContext(inv.Attachments())))
if err == nil {
- ctx = context.WithValue(ctx, constant.TRACING_REMOTE_SPAN_CTX, spanCtx)
+ ctx = context.WithValue(ctx, constant.TracingRemoteSpanCtx, spanCtx)
}
return ctx
}
diff --git a/remoting/getty/readwriter_test.go b/remoting/getty/readwriter_test.go
index e9be67d..0990292 100644
--- a/remoting/getty/readwriter_test.go
+++ b/remoting/getty/readwriter_test.go
@@ -52,9 +52,9 @@ func testDecodeTCPPackage(t *testing.T, svr *Server, client *Client) {
rpcInvocation := createInvocation("GetAdmin", nil, nil, []interface{}{[]interface{}{"1", "username"}},
[]reflect.Value{reflect.ValueOf([]interface{}{"1", "username"}), reflect.ValueOf(ap)})
attachment := map[string]string{
- constant.INTERFACE_KEY: "com.ikurento.user.AdminProvider",
- constant.PATH_KEY: "AdminProvider",
- constant.VERSION_KEY: "1.0.0",
+ constant.InterfaceKey: "com.ikurento.user.AdminProvider",
+ constant.PathKey: "AdminProvider",
+ constant.VersionKey: "1.0.0",
}
setAttachment(rpcInvocation, attachment)
request.Data = rpcInvocation
diff --git a/remoting/kubernetes/client.go b/remoting/kubernetes/client.go
index 976dd44..b2fac83 100644
--- a/remoting/kubernetes/client.go
+++ b/remoting/kubernetes/client.go
@@ -51,7 +51,7 @@ type Client struct {
// NewClient returns Client instance for registry
func NewClient(url *common.URL) (*Client, error) {
// read type
- r, err := strconv.Atoi(url.GetParams().Get(constant.ROLE_KEY))
+ r, err := strconv.Atoi(url.GetParams().Get(constant.RoleKey))
if err != nil {
return nil, perrors.WithMessage(err, "atoi role")
}
diff --git a/remoting/kubernetes/facade_test.go b/remoting/kubernetes/facade_test.go
index 7abf736..11bf274 100644
--- a/remoting/kubernetes/facade_test.go
+++ b/remoting/kubernetes/facade_test.go
@@ -60,7 +60,7 @@ func (r *mockFacade) IsAvailable() bool {
func Test_Facade(t *testing.T) {
regUrl, err := common.NewURL("registry://127.0.0.1:443",
- common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER)))
+ common.WithParamsValue(constant.RoleKey, strconv.Itoa(common.CONSUMER)))
if err != nil {
t.Fatal(err)
}
diff --git a/remoting/nacos/builder.go b/remoting/nacos/builder.go
index 34f63a8..ef440fb 100644
--- a/remoting/nacos/builder.go
+++ b/remoting/nacos/builder.go
@@ -72,25 +72,25 @@ func GetNacosConfig(url *common.URL) ([]nacosConstant.ServerConfig, nacosConstan
serverConfigs = append(serverConfigs, nacosConstant.ServerConfig{IpAddr: ip, Port: uint64(port)})
}
- timeout := url.GetParamDuration(constant.CONFIG_TIMEOUT_KEY, constant.DEFAULT_REG_TIMEOUT)
+ timeout := url.GetParamDuration(constant.ConfigTimeoutKey, constant.DefaultRegTimeout)
clientConfig := nacosConstant.ClientConfig{
TimeoutMs: uint64(int32(timeout / time.Millisecond)),
- BeatInterval: url.GetParamInt(constant.NACOS_BEAT_INTERVAL_KEY, 5000),
- NamespaceId: url.GetParam(constant.NACOS_NAMESPACE_ID, ""),
- AppName: url.GetParam(constant.NACOS_APP_NAME_KEY, ""),
- Endpoint: url.GetParam(constant.NACOS_ENDPOINT, ""),
- RegionId: url.GetParam(constant.NACOS_REGION_ID_KEY, ""),
- AccessKey: url.GetParam(constant.NACOS_ACCESS_KEY, ""),
- SecretKey: url.GetParam(constant.NACOS_SECRET_KEY, ""),
- OpenKMS: url.GetParamBool(constant.NACOS_OPEN_KMS_KEY, false),
- CacheDir: url.GetParam(constant.NACOS_CACHE_DIR_KEY, ""),
- UpdateThreadNum: url.GetParamByIntValue(constant.NACOS_UPDATE_THREAD_NUM_KEY, 20),
- NotLoadCacheAtStart: url.GetParamBool(constant.NACOS_NOT_LOAD_LOCAL_CACHE, true),
- Username: url.GetParam(constant.NACOS_USERNAME, ""),
- Password: url.GetParam(constant.NACOS_PASSWORD, ""),
- LogDir: url.GetParam(constant.NACOS_LOG_DIR_KEY, ""),
- LogLevel: url.GetParam(constant.NACOS_LOG_LEVEL_KEY, "info"),
+ BeatInterval: url.GetParamInt(constant.NacosBeatIntervalKey, 5000),
+ NamespaceId: url.GetParam(constant.NacosNamespaceID, ""),
+ AppName: url.GetParam(constant.NacosAppNameKey, ""),
+ Endpoint: url.GetParam(constant.NacosEndpoint, ""),
+ RegionId: url.GetParam(constant.NacosRegionIDKey, ""),
+ AccessKey: url.GetParam(constant.NacosAccessKey, ""),
+ SecretKey: url.GetParam(constant.NacosSecretKey, ""),
+ OpenKMS: url.GetParamBool(constant.NacosOpenKmsKey, false),
+ CacheDir: url.GetParam(constant.NacosCacheDirKey, ""),
+ UpdateThreadNum: url.GetParamByIntValue(constant.NacosUpdateThreadNumKey, 20),
+ NotLoadCacheAtStart: url.GetParamBool(constant.NacosNotLoadLocalCache, true),
+ Username: url.GetParam(constant.NacosUsername, ""),
+ Password: url.GetParam(constant.NacosPassword, ""),
+ LogDir: url.GetParam(constant.NacosLogDirKey, ""),
+ LogLevel: url.GetParam(constant.NacosLogLevelKey, "info"),
}
return serverConfigs, clientConfig, nil
}
diff --git a/remoting/nacos/builder_test.go b/remoting/nacos/builder_test.go
index eb4c1a6..74eba4f 100644
--- a/remoting/nacos/builder_test.go
+++ b/remoting/nacos/builder_test.go
@@ -85,10 +85,10 @@ func TestNewNacosClientByUrl(t *testing.T) {
func TestTimeoutConfig(t *testing.T) {
regurlMap := url.Values{}
- regurlMap.Set(constant.NACOS_NOT_LOAD_LOCAL_CACHE, "true")
- // regurlMap.Set(constant.NACOS_USERNAME, "nacos")
- // regurlMap.Set(constant.NACOS_PASSWORD, "nacos")
- regurlMap.Set(constant.NACOS_NAMESPACE_ID, "nacos")
+ regurlMap.Set(constant.NacosNotLoadLocalCache, "true")
+ // regurlMap.Set(constant.NacosUsername, "nacos")
+ // regurlMap.Set(constant.NacosPassword, "nacos")
+ regurlMap.Set(constant.NacosNamespaceID, "nacos")
t.Run("default timeout", func(t *testing.T) {
newURL, _ := common.NewURL("registry://console.nacos.io:80", common.WithParams(regurlMap))
@@ -101,7 +101,7 @@ func TestTimeoutConfig(t *testing.T) {
t.Run("right timeout", func(t *testing.T) {
- regurlMap.Set(constant.CONFIG_TIMEOUT_KEY, "5s")
+ regurlMap.Set(constant.ConfigTimeoutKey, "5s")
newURL, _ := common.NewURL("registry://console.nacos.io:80", common.WithParams(regurlMap))
@@ -112,7 +112,7 @@ func TestTimeoutConfig(t *testing.T) {
})
t.Run("invalid timeout", func(t *testing.T) {
- regurlMap.Set(constant.CONFIG_TIMEOUT_KEY, "5ab")
+ regurlMap.Set(constant.ConfigTimeoutKey, "5ab")
newURL, _ := common.NewURL("registry://console.nacos.io:80", common.WithParams(regurlMap))
_, cc, err := GetNacosConfig(newURL)
@@ -126,11 +126,11 @@ func TestTimeoutConfig(t *testing.T) {
func getRegUrl() *common.URL {
regurlMap := url.Values{}
- regurlMap.Set(constant.NACOS_NOT_LOAD_LOCAL_CACHE, "true")
- // regurlMap.Set(constant.NACOS_USERNAME, "nacos")
- // regurlMap.Set(constant.NACOS_PASSWORD, "nacos")
- regurlMap.Set(constant.NACOS_NAMESPACE_ID, "nacos")
- regurlMap.Set(constant.CONFIG_TIMEOUT_KEY, "5s")
+ regurlMap.Set(constant.NacosNotLoadLocalCache, "true")
+ // regurlMap.Set(constant.NacosUsername, "nacos")
+ // regurlMap.Set(constant.NacosPassword, "nacos")
+ regurlMap.Set(constant.NacosNamespaceID, "nacos")
+ regurlMap.Set(constant.ConfigTimeoutKey, "5s")
regurl, _ := common.NewURL("registry://console.nacos.io:80", common.WithParams(regurlMap))
diff --git a/remoting/zookeeper/client.go b/remoting/zookeeper/client.go
index cf0b572..9c639d6 100644
--- a/remoting/zookeeper/client.go
+++ b/remoting/zookeeper/client.go
@@ -55,7 +55,7 @@ func ValidateZookeeperClient(container ZkClientFacade, zkName string) error {
if container.ZkClient() == nil {
// in dubbo, every registry only connect one node, so this is []string{r.Address}
- timeout := url.GetParamDuration(constant.CONFIG_TIMEOUT_KEY, constant.DEFAULT_REG_TIMEOUT)
+ timeout := url.GetParamDuration(constant.ConfigTimeoutKey, constant.DefaultRegTimeout)
zkAddresses := strings.Split(url.Location, ",")
newClient, cltErr := gxzookeeper.NewZookeeperClient(zkName, zkAddresses, true, gxzookeeper.WithZkTimeOut(timeout))
diff --git a/remoting/zookeeper/curator_discovery/service_discovery.go b/remoting/zookeeper/curator_discovery/service_discovery.go
index efa0a40..582a2e2 100644
--- a/remoting/zookeeper/curator_discovery/service_discovery.go
+++ b/remoting/zookeeper/curator_discovery/service_discovery.go
@@ -259,8 +259,8 @@ func (sd *ServiceDiscovery) DataChange(eventType remoting.Event) bool {
// getNameAndID get service name and instance id by path
func (sd *ServiceDiscovery) getNameAndID(path string) (string, string, error) {
path = strings.TrimPrefix(path, sd.basePath)
- path = strings.TrimPrefix(path, constant.PATH_SEPARATOR)
- pathSlice := strings.Split(path, constant.PATH_SEPARATOR)
+ path = strings.TrimPrefix(path, constant.PathSeparator)
+ pathSlice := strings.Split(path, constant.PathSeparator)
if len(pathSlice) < 2 {
return "", "", perrors.Errorf("[ServiceDiscovery] path{%s} dont contain name and id", path)
}
diff --git a/remoting/zookeeper/listener.go b/remoting/zookeeper/listener.go
index 3fdfec3..8bfe743 100644
--- a/remoting/zookeeper/listener.go
+++ b/remoting/zookeeper/listener.go
@@ -224,7 +224,7 @@ func (l *ZkEventListener) listenDirEvent(conf *common.URL, zkRootPath string, li
event = make(chan struct{}, 4)
ttl = defaultTTL
if conf != nil {
- timeout, err := time.ParseDuration(conf.GetParam(constant.REGISTRY_TTL_KEY, constant.DEFAULT_REG_TTL))
+ timeout, err := time.ParseDuration(conf.GetParam(constant.RegistryTTLKey, constant.DefaultRegTTL))
if err == nil {
ttl = timeout
} else {
@@ -276,7 +276,7 @@ func (l *ZkEventListener) listenDirEvent(conf *common.URL, zkRootPath string, li
failTimes = 0
for _, c := range children {
// Only need to compare Path when subscribing to provider
- if strings.LastIndex(zkRootPath, constant.PROVIDER_CATEGORY) != -1 {
+ if strings.LastIndex(zkRootPath, constant.ProviderCategory) != -1 {
provider, _ := common.NewURL(c)
if provider.ServiceKey() != conf.ServiceKey() {
continue
@@ -329,8 +329,8 @@ func (l *ZkEventListener) listenDirEvent(conf *common.URL, zkRootPath string, li
// listen sub path recursive
// if zkPath is end of "providers/ & consumers/" we do not listen children dir
- if strings.LastIndex(zkRootPath, constant.PROVIDER_CATEGORY) == -1 &&
- strings.LastIndex(zkRootPath, constant.CONSUMER_CATEGORY) == -1 {
+ if strings.LastIndex(zkRootPath, constant.ProviderCategory) == -1 &&
+ strings.LastIndex(zkRootPath, constant.ConsumerCategory) == -1 {
l.wg.Add(1)
go func(zkPath string, listener remoting.DataListener) {
l.listenDirEvent(conf, zkPath, listener)