diff --git a/dubbogo/config_center/configuration_listener.go b/dubbogo/config_center/configuration_listener.go deleted file mode 100644 index e6b8f9d..0000000 --- a/dubbogo/config_center/configuration_listener.go +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxConfigCenter - -import ( - "fmt" -) - -import ( - "github.com/dubbogo/gost/dubbogo/remoting" -) - -// ConfigurationListener for changing listener's event -type ConfigurationListener interface { - // Process the notification event once there's any change happens on the config - Process(*ConfigChangeEvent) -} - -// ConfigChangeEvent for changing listener's event -type ConfigChangeEvent struct { - Key string - Value interface{} - ConfigType gxremoting.EventType -} - -func (c ConfigChangeEvent) String() string { - return fmt.Sprintf("ConfigChangeEvent{key = %v , value = %v , changeType = %v}", - c.Key, c.Value, c.ConfigType) -} diff --git a/dubbogo/constant/cluster.go b/dubbogo/constant/cluster.go deleted file mode 100644 index ed6a622..0000000 --- a/dubbogo/constant/cluster.go +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxconstant - -// nolint -const ( - FAILOVER_CLUSTER_NAME = "failover" - ZONEAWARE_CLUSTER_NAME = "zoneAware" -) diff --git a/dubbogo/constant/default.go b/dubbogo/constant/default.go deleted file mode 100644 index ac70a5d..0000000 --- a/dubbogo/constant/default.go +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxconstant - -const ( - DUBBO = "dubbo" - PROVIDER_PROTOCOL = "provider" - // compatible with 2.6.x - OVERRIDE_PROTOCOL = "override" - EMPTY_PROTOCOL = "empty" - ROUTER_PROTOCOL = "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 -) - -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_SERIALIZATION = HESSIAN2_SERIALIZATION -) - -const ( - DEFAULT_KEY = "default" - PREFIX_DEFAULT_KEY = "default." - DEFAULT_SERVICE_FILTERS = "echo,token,accesslog,tps,generic_service,execute,pshutdown" - DEFAULT_REFERENCE_FILTERS = "cshutdown" - GENERIC_REFERENCE_FILTERS = "generic" - GENERIC = "$invoke" - ECHO = "$echo" -) - -const ( - ANY_VALUE = "*" - ANYHOST_VALUE = "0.0.0.0" - LOCAL_HOST_VALUE = "192.168.1.1" - REMOVE_VALUE_PREFIX = "-" -) - -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" -) - -const ( - COMMA_SPLIT_PATTERN = "\\s*[,]+\\s*" -) - -const ( - SIMPLE_METADATA_SERVICE_NAME = "MetadataService" - DEFAULT_REVISION = "N/A" -) - -const ( - SERVICE_DISCOVERY_DEFAULT_GROUP = "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" -) diff --git a/dubbogo/constant/env.go b/dubbogo/constant/env.go deleted file mode 100644 index c9b7127..0000000 --- a/dubbogo/constant/env.go +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxconstant - -// nolint -const ( - // CONF_CONSUMER_FILE_PATH ... - CONF_CONSUMER_FILE_PATH = "CONF_CONSUMER_FILE_PATH" - // CONF_PROVIDER_FILE_PATH ... - CONF_PROVIDER_FILE_PATH = "CONF_PROVIDER_FILE_PATH" - // APP_LOG_CONF_FILE ... - APP_LOG_CONF_FILE = "APP_LOG_CONF_FILE" - // CONF_ROUTER_FILE_PATH Specify Path variable of router config file - CONF_ROUTER_FILE_PATH = "CONF_ROUTER_FILE_PATH" - // CONF_VIRTUAL_SERVICE_FILE_PATH Specify path to Virtual service of uniform router config file - CONF_VIRTUAL_SERVICE_FILE_PATH = "CONF_VIRTUAL_SERVICE_FILE_PATH" - // CONF_DEST_RULE_FILE_PATH Specify path to destination rule of uniform router config file - CONF_DEST_RULE_FILE_PATH = "CONF_DEST_RULE_FILE_PATH" -) diff --git a/dubbogo/constant/key.go b/dubbogo/constant/key.go deleted file mode 100644 index 1de5099..0000000 --- a/dubbogo/constant/key.go +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxconstant - -type DubboCtxKey string - -const ( - ASYNC_KEY = "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 = "/" - // 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" -) - -const ( - SERVICE_FILTER_KEY = "service.filter" - REFERENCE_FILTER_KEY = "reference.filter" -) - -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 - ACCESS_LOG_KEY = "accesslog" - 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" - PROVIDER_SHUTDOWN_FILTER = "pshutdown" - CONSUMER_SHUTDOWN_FILTER = "cshutdown" - 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 -) - -const ( - DUBBOGO_CTX_KEY = DubboCtxKey("dubbogo-ctx") -) - -const ( - REGISTRY_KEY = "registry" - REGISTRY_PROTOCOL = "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" -) - -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" -) - -const ( - CONFIG_NAMESPACE_KEY = "config.namespace" - CONFIG_GROUP_KEY = "config.group" - CONFIG_APP_ID_KEY = "config.appId" - CONFIG_CLUSTER_KEY = "config.cluster" - CONFIG_CHECK_KEY = "config.check" - CONFIG_TIMEOUT_KET = "config.timeout" - CONFIG_LOG_DIR_KEY = "config.logDir" - CONFIG_VERSION_KEY = "configVersion" - COMPATIBLE_CONFIG_KEY = "compatible_config" -) - -const ( - RegistryConfigPrefix = "dubbo.registries." - SingleRegistryConfigPrefix = "dubbo.registry." - ReferenceConfigPrefix = "dubbo.reference." - ServiceConfigPrefix = "dubbo.service." - ProtocolConfigPrefix = "dubbo.protocols." - ProviderConfigPrefix = "dubbo.provider." - ConsumerConfigPrefix = "dubbo.consumer." - ShutdownConfigPrefix = "dubbo.shutdown." - MetadataReportPrefix = "dubbo.metadata-report." - RouterConfigPrefix = "dubbo.router." -) - -const ( - CONFIGURATORS_SUFFIX = ".configurators" -) - -const ( - NACOS_KEY = "nacos" - NACOS_DEFAULT_ROLETYPE = 3 - NACOS_CACHE_DIR_KEY = "cacheDir" - NACOS_LOG_DIR_KEY = "logDir" - 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" -) - -const ( - FILE_KEY = "file" -) - -const ( - ZOOKEEPER_KEY = "zookeeper" -) - -const ( - ETCDV3_KEY = "etcdv3" -) - -const ( - CONSUL_KEY = "consul" - CHECK_PASS_INTERVAL = "consul-check-pass-interval" - // default time-to-live in millisecond - DEFAULT_CHECK_PASS_INTERVAL = 16000 - QUERY_TAG = "consul_query_tag" - ACL_TOKEN = "acl-token" - // default deregister critical server after - DEFAULT_DEREGISTER_TIME = "20s" - DEREGISTER_AFTER = "consul-deregister-critical-service-after" - // PassThroughProxyFactoryKey is key of proxy factory with raw data input service - PassThroughProxyFactoryKey = "dubbo-raw" -) - -const ( - TRACING_REMOTE_SPAN_CTX = DubboCtxKey("tracing.remote.span.ctx") -) - -// Use for router module -const ( - // UniformRouterName Specifythe name of UniformRouter - UniformRouterName = "uniform" - // TagRouterName Specify the name of TagRouter - TagRouterName = "tag" - // TagRouterRuleSuffix Specify tag router suffix - TagRouterRuleSuffix = ".tag-router" - RemoteApplicationKey = "remote.application" - // ConditionRouterRuleSuffix Specify condition router suffix - ConditionRouterRuleSuffix = ".condition-router" - - // RouterScope Scope key in router module - RouterScope = "scope" - // RouterApplicationScope Scope key in router module - RouterApplicationScope = "application" - // RouterServiceScope Scope key in router module - RouterServiceScope = "service" - // RouterRuleKey defines the key of the router, service's/application's name - RouterRuleKey = "key" - // ForceUseTag is the tag in attachment - ForceUseTag = "dubbo.force.tag" - Tagkey = "dubbo.tag" - // HEALTH_ROUTE_ENABLED_KEY defines if use health router - HEALTH_ROUTE_ENABLED_KEY = "health.route.enabled" - // AttachmentKey in context in invoker - AttachmentKey = DubboCtxKey("attachment") -) - -const ( - // name of consumer sign filter - CONSUMER_SIGN_FILTER = "sign" - // name of consumer sign filter - PROVIDER_AUTH_FILTER = "auth" - // name of service filter - SERVICE_AUTH_KEY = "auth" - // key of authenticator - AUTHENTICATOR_KEY = "authenticator" - // name of default authenticator - DEFAULT_AUTHENTICATOR = "accesskeys" - // name of default url storage - DEFAULT_ACCESS_KEY_STORAGE = "urlstorage" - // key of storage - ACCESS_KEY_STORAGE_KEY = "accessKey.storage" - // key of request timestamp - REQUEST_TIMESTAMP_KEY = "timestamp" - // key of request signature - REQUEST_SIGNATURE_KEY = "signature" - // AK key - AK_KEY = "ak" - // signature format - SIGNATURE_STRING_FORMAT = "%s#%s#%s#%s" - // key whether enable signature - PARAMETER_SIGNATURE_ENABLE_KEY = "param.sign" - // consumer - CONSUMER = "consumer" - // key of access key id - ACCESS_KEY_ID_KEY = ".accessKeyId" - // key of secret access key - SECRET_ACCESS_KEY_KEY = ".secretAccessKey" -) - -// metadata report - -const ( - METACONFIG_REMOTE = "remote" - METACONFIG_LOCAL = "local" - KEY_SEPARATOR = ":" - DEFAULT_PATH_TAG = "metadata" - KEY_REVISON_PREFIX = "revision" - - // metadata service - METADATA_SERVICE_NAME = "org.apache.dubbo.metadata.MetadataService" -) - -// HealthCheck Router -const ( - // The key of HealthCheck SPI - HEALTH_CHECKER = "health.checker" - // The name of the default implementation of HealthChecker - DEFAULT_HEALTH_CHECKER = "default" - // The name of the default implementation of C - DEFAULT_CONN_CHECKER = "default" - // The key of outstanding-request-limit\ - OUTSTANDING_REQUEST_COUNT_LIMIT_KEY = "outstanding.request.limit" - // The key of successive-failed-request's threshold - SUCCESSIVE_FAILED_REQUEST_THRESHOLD_KEY = "successive.failed.threshold" - // The key of circuit-tripped timeout factor - CIRCUIT_TRIPPED_TIMEOUT_FACTOR_KEY = "circuit.tripped.timeout.factor" - // The default threshold of successive-failed-request if not specfied - DEFAULT_SUCCESSIVE_FAILED_THRESHOLD = 5 - // The default maximum diff between successive-failed-request's threshold and actual successive-failed-request's count - DEFAULT_SUCCESSIVE_FAILED_REQUEST_MAX_DIFF = 5 - // The default factor of circuit-tripped timeout if not specfied - DEFAULT_CIRCUIT_TRIPPED_TIMEOUT_FACTOR = 1000 - // The default time window of circuit-tripped in millisecond if not specfied - MAX_CIRCUIT_TRIPPED_TIMEOUT_IN_MS = 30000 -) - -// service discovery -const ( - SUBSCRIBED_SERVICE_NAMES_KEY = "subscribed-services" - PROVIDER_BY = "provided-by" - EXPORTED_SERVICES_REVISION_PROPERTY_NAME = "dubbo.exported-services.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" - 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" - - // SERVICE_DISCOVERY_KEY indicate which service discovery instance will be used - SERVICE_DISCOVERY_KEY = "service_discovery" -) diff --git a/dubbogo/constant/serializtion.go b/dubbogo/constant/serializtion.go deleted file mode 100644 index ae2e57b..0000000 --- a/dubbogo/constant/serializtion.go +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxconstant - -const ( - S_Hessian2 byte = 2 - S_Proto byte = 21 -) - -const ( - HESSIAN2_SERIALIZATION = "hessian2" - PROTOBUF_SERIALIZATION = "protobuf" -) diff --git a/dubbogo/constant/time.go b/dubbogo/constant/time.go deleted file mode 100644 index 163fd12..0000000 --- a/dubbogo/constant/time.go +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxconstant - -import ( - "time" -) - -// The value will be 10^6 -// 1ms = 10^6ns -var MsToNanoRate = int64(time.Millisecond / time.Nanosecond) diff --git a/dubbogo/doc.go b/dubbogo/doc.go deleted file mode 100644 index 8ee4a7a..0000000 --- a/dubbogo/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// same as https://github.com/golang/go/blob/master/src/go -// refer from github.com/apache/dubbo-go common -package gxdubbogo diff --git a/dubbogo/host_util.go b/dubbogo/host_util.go deleted file mode 100644 index 7da1a2e..0000000 --- a/dubbogo/host_util.go +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxdubbogo - -import gxnet "github.com/dubbogo/gost/net" - -var localIp string - -func GetLocalIp() string { - if len(localIp) != 0 { - return localIp - } - localIp, _ = gxnet.GetLocalIP() - return localIp -} diff --git a/dubbogo/host_util_test.go b/dubbogo/host_util_test.go deleted file mode 100644 index e98d800..0000000 --- a/dubbogo/host_util_test.go +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxdubbogo - -import ( - "testing" -) - -import ( - "github.com/stretchr/testify/assert" -) - -func TestGetLocalIp(t *testing.T) { - assert.NotNil(t, GetLocalIp()) -} diff --git a/dubbogo/logger/logger.go b/dubbogo/logger/logger.go deleted file mode 100644 index 240ccb8..0000000 --- a/dubbogo/logger/logger.go +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxlogger - -var logger Logger - -// Logger is the interface for Logger types -type Logger interface { - Info(args ...interface{}) - Warn(args ...interface{}) - Error(args ...interface{}) - Debug(args ...interface{}) - - Infof(fmt string, args ...interface{}) - Warnf(fmt string, args ...interface{}) - Errorf(fmt string, args ...interface{}) - Debugf(fmt string, args ...interface{}) -} diff --git a/dubbogo/logger/logging.go b/dubbogo/logger/logging.go deleted file mode 100644 index 9da91dc..0000000 --- a/dubbogo/logger/logging.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxlogger - -// Info is info level -func Info(args ...interface{}) { - logger.Info(args...) -} - -// Warn is warning level -func Warn(args ...interface{}) { - logger.Warn(args...) -} - -// Error is error level -func Error(args ...interface{}) { - logger.Error(args...) -} - -// Debug is debug level -func Debug(args ...interface{}) { - logger.Debug(args...) -} - -// Infof is format info level -func Infof(fmt string, args ...interface{}) { - logger.Infof(fmt, args...) -} - -// Warnf is format warning level -func Warnf(fmt string, args ...interface{}) { - logger.Warnf(fmt, args...) -} - -// Errorf is format error level -func Errorf(fmt string, args ...interface{}) { - logger.Errorf(fmt, args...) -} - -// Debugf is format debug level -func Debugf(fmt string, args ...interface{}) { - logger.Debugf(fmt, args...) -} diff --git a/dubbogo/node.go b/dubbogo/node.go deleted file mode 100644 index ef3bc9c..0000000 --- a/dubbogo/node.go +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxdubbogo - -// Node use for process dubbo node -type Node interface { - GetURL() *URL - IsAvailable() bool - Destroy() -} diff --git a/dubbogo/protocol/invocation.go b/dubbogo/protocol/invocation.go deleted file mode 100644 index f92015e..0000000 --- a/dubbogo/protocol/invocation.go +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxprotocol - -import ( - "reflect" -) - -// Invocation is a invocation for each remote method. -type Invocation interface { - // MethodName gets invocation method name. - MethodName() string - // ParameterTypeNames gets invocation parameter type names. - ParameterTypeNames() []string - // ParameterTypes gets invocation parameter types. - ParameterTypes() []reflect.Type - // ParameterValues gets invocation parameter values. - ParameterValues() []reflect.Value - // Arguments gets arguments. - Arguments() []interface{} - // Reply gets response of request - Reply() interface{} - // Attachments gets all attachments - Attachments() map[string]interface{} - // AttachmentsByKey gets attachment by key , if nil then return default value. (It will be deprecated in the future) - AttachmentsByKey(string, string) string - Attachment(string) interface{} - // Attributes refers to dubbo 2.7.6. It is different from attachment. It is used in internal process. - Attributes() map[string]interface{} - // AttributeByKey gets attribute by key , if nil then return default value - AttributeByKey(string, interface{}) interface{} - // SetAttachments sets attribute by @key and @value. - SetAttachments(key string, value interface{}) - // Invoker gets the invoker in current context. - Invoker() Invoker -} diff --git a/dubbogo/protocol/invoker.go b/dubbogo/protocol/invoker.go deleted file mode 100644 index b220de5..0000000 --- a/dubbogo/protocol/invoker.go +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxprotocol - -import ( - "context" -) - -import ( - "github.com/dubbogo/gost/dubbogo" -) - -// Invoker the service invocation interface for the consumer -//go:generate mockgen -source invoker.go -destination mock/mock_invoker.go -self_package github.com/apache/dubbo-go/protocol/mock --package mock Invoker -// Extension - Invoker -type Invoker interface { - gxdubbogo.Node - // Invoke the invocation and return result. - Invoke(context.Context, Invocation) Result -} diff --git a/dubbogo/protocol/result.go b/dubbogo/protocol/result.go deleted file mode 100644 index fb53d91..0000000 --- a/dubbogo/protocol/result.go +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxprotocol - -// Result is a RPC result -type Result interface { - // SetError sets error. - SetError(error) - // Error gets error. - Error() error - // SetResult sets invoker result. - SetResult(interface{}) - // Result gets invoker result. - Result() interface{} - // SetAttachments replaces the existing attachments with the specified param. - SetAttachments(map[string]interface{}) - // Attachments gets all attachments - Attachments() map[string]interface{} - - // AddAttachment adds the specified map to existing attachments in this instance. - AddAttachment(string, interface{}) - // Attachment gets attachment by key with default value. - Attachment(string, interface{}) interface{} -} diff --git a/dubbogo/remoting/event_type.go b/dubbogo/remoting/event_type.go deleted file mode 100644 index 0440a93..0000000 --- a/dubbogo/remoting/event_type.go +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxremoting - -////////////////////////////////////////// -// event type -////////////////////////////////////////// - -// EventType means SourceObjectEventType -type EventType int - -const ( - // EventTypeAdd means add event - EventTypeAdd = iota - // EventTypeDel means del event - EventTypeDel - // EventTypeUpdate means update event - EventTypeUpdate -) - -var serviceEventTypeStrings = [...]string{ - "add", - "delete", - "update", -} - -// nolint -func (t EventType) String() string { - return serviceEventTypeStrings[t] -} diff --git a/dubbogo/rpc_service.go b/dubbogo/rpc_service.go deleted file mode 100644 index 660c62e..0000000 --- a/dubbogo/rpc_service.go +++ /dev/null @@ -1,387 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxdubbogo - -import ( - "context" - "reflect" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -import ( - perrors "github.com/pkg/errors" -) - -// RPCService -// rpc service interface -type RPCService interface { - // Reference: - // rpc service id or reference id - Reference() string -} - -// AsyncCallbackService callback interface for async -type AsyncCallbackService interface { - // Callback: callback - CallBack(response CallbackResponse) -} - -// CallbackResponse for different protocol -type CallbackResponse interface{} - -// AsyncCallback async callback method -type AsyncCallback func(response CallbackResponse) - -// for lowercase func -// func MethodMapper() map[string][string] { -// return map[string][string]{} -// } -const ( - METHOD_MAPPER = "MethodMapper" -) - -var ( - // Precompute the reflect type for error. Can't use error directly - // because Typeof takes an empty interface value. This is annoying. - typeOfError = reflect.TypeOf((*error)(nil)).Elem() - - // ServiceMap store description of service. - ServiceMap = &serviceMap{ - serviceMap: make(map[string]map[string]*Service), - interfaceMap: make(map[string][]*Service), - } -) - -////////////////////////// -// info of method -////////////////////////// - -// MethodType is description of service method. -type MethodType struct { - method reflect.Method - ctxType reflect.Type // request context - argsType []reflect.Type // args except ctx, include replyType if existing - replyType reflect.Type // return value, otherwise it is nil -} - -// Method gets @m.method. -func (m *MethodType) Method() reflect.Method { - return m.method -} - -// CtxType gets @m.ctxType. -func (m *MethodType) CtxType() reflect.Type { - return m.ctxType -} - -// ArgsType gets @m.argsType. -func (m *MethodType) ArgsType() []reflect.Type { - return m.argsType -} - -// ReplyType gets @m.replyType. -func (m *MethodType) ReplyType() reflect.Type { - return m.replyType -} - -// SuiteContext transfers @ctx to reflect.Value type or get it from @m.ctxType. -func (m *MethodType) SuiteContext(ctx context.Context) reflect.Value { - if ctxV := reflect.ValueOf(ctx); ctxV.IsValid() { - return ctxV - } - return reflect.Zero(m.ctxType) -} - -////////////////////////// -// info of service interface -////////////////////////// - -// Service is description of service -type Service struct { - name string - rcvr reflect.Value - rcvrType reflect.Type - methods map[string]*MethodType -} - -// Method gets @s.methods. -func (s *Service) Method() map[string]*MethodType { - return s.methods -} - -// Name will return service name -func (s *Service) Name() string { - return s.name -} - -// RcvrType gets @s.rcvrType. -func (s *Service) RcvrType() reflect.Type { - return s.rcvrType -} - -// Rcvr gets @s.rcvr. -func (s *Service) Rcvr() reflect.Value { - return s.rcvr -} - -////////////////////////// -// serviceMap -////////////////////////// - -type serviceMap struct { - mutex sync.RWMutex // protects the serviceMap - serviceMap map[string]map[string]*Service // protocol -> service name -> service - interfaceMap map[string][]*Service // interface -> service -} - -// GetService gets a service definition by protocol and name -func (sm *serviceMap) GetService(protocol, interfaceName, group, version string) *Service { - serviceKey := ServiceKey(interfaceName, group, version) - return sm.GetServiceByServiceKey(protocol, serviceKey) -} - -// GetService gets a service definition by protocol and service key -func (sm *serviceMap) GetServiceByServiceKey(protocol, serviceKey string) *Service { - sm.mutex.RLock() - defer sm.mutex.RUnlock() - if s, ok := sm.serviceMap[protocol]; ok { - if srv, ok := s[serviceKey]; ok { - return srv - } - return nil - } - return nil -} - -// GetInterface gets an interface definition by interface name -func (sm *serviceMap) GetInterface(interfaceName string) []*Service { - sm.mutex.RLock() - defer sm.mutex.RUnlock() - if s, ok := sm.interfaceMap[interfaceName]; ok { - return s - } - return nil -} - -// Register registers a service by @interfaceName and @protocol -func (sm *serviceMap) Register(interfaceName, protocol, group, version string, rcvr RPCService) (string, error) { - if sm.serviceMap[protocol] == nil { - sm.serviceMap[protocol] = make(map[string]*Service) - } - if sm.interfaceMap[interfaceName] == nil { - sm.interfaceMap[interfaceName] = make([]*Service, 0, 16) - } - - s := new(Service) - s.rcvrType = reflect.TypeOf(rcvr) - s.rcvr = reflect.ValueOf(rcvr) - sname := reflect.Indirect(s.rcvr).Type().Name() - if sname == "" { - s := "no service name for type " + s.rcvrType.String() - return "", perrors.New(s) - } - if !isExported(sname) { - s := "type " + sname + " is not exported" - return "", perrors.New(s) - } - - sname = ServiceKey(interfaceName, group, version) - if server := sm.GetService(protocol, interfaceName, group, version); server != nil { - return "", perrors.New("service already defined: " + sname) - } - s.name = sname - s.methods = make(map[string]*MethodType) - - // Install the methods - methods := "" - methods, s.methods = suitableMethods(s.rcvrType) - - if len(s.methods) == 0 { - s := "type " + sname + " has no exported methods of suitable type" - return "", perrors.New(s) - } - sm.mutex.Lock() - sm.serviceMap[protocol][s.name] = s - sm.interfaceMap[interfaceName] = append(sm.interfaceMap[interfaceName], s) - sm.mutex.Unlock() - - return strings.TrimSuffix(methods, ","), nil -} - -// UnRegister cancels a service by @interfaceName, @protocol and @serviceId -func (sm *serviceMap) UnRegister(interfaceName, protocol, serviceKey string) error { - if protocol == "" || serviceKey == "" { - return perrors.New("protocol or serviceKey is nil") - } - - var ( - err error - index = -1 - svcs map[string]*Service - svrs []*Service - ok bool - ) - - f := func() error { - sm.mutex.RLock() - defer sm.mutex.RUnlock() - svcs, ok = sm.serviceMap[protocol] - if !ok { - return perrors.New("no services for " + protocol) - } - s, ok := svcs[serviceKey] - if !ok { - return perrors.New("no service for " + serviceKey) - } - svrs, ok = sm.interfaceMap[interfaceName] - if !ok { - return perrors.New("no service for " + interfaceName) - } - for i, svr := range svrs { - if svr == s { - index = i - } - } - return nil - } - - if err = f(); err != nil { - return err - } - - sm.mutex.Lock() - defer sm.mutex.Unlock() - sm.interfaceMap[interfaceName] = make([]*Service, 0, len(svrs)) - for i := range svrs { - if i != index { - sm.interfaceMap[interfaceName] = append(sm.interfaceMap[interfaceName], svrs[i]) - } - } - delete(svcs, serviceKey) - if len(sm.serviceMap[protocol]) == 0 { - delete(sm.serviceMap, protocol) - } - - return nil -} - -// Is this an exported - upper case - name -func isExported(name string) bool { - s, _ := utf8.DecodeRuneInString(name) - return unicode.IsUpper(s) -} - -// Is this type exported or a builtin? -func isExportedOrBuiltinType(t reflect.Type) bool { - for t.Kind() == reflect.Ptr { - t = t.Elem() - } - // PkgPath will be non-empty even for an exported type, - // so we need to check the type name as well. - return isExported(t.Name()) || t.PkgPath() == "" -} - -// suitableMethods returns suitable Rpc methods of typ -func suitableMethods(typ reflect.Type) (string, map[string]*MethodType) { - methods := make(map[string]*MethodType) - var mts []string - method, ok := typ.MethodByName(METHOD_MAPPER) - var methodMapper map[string]string - if ok && method.Type.NumIn() == 1 && method.Type.NumOut() == 1 && method.Type.Out(0).String() == "map[string]string" { - methodMapper = method.Func.Call([]reflect.Value{reflect.New(typ.Elem())})[0].Interface().(map[string]string) - } - - for m := 0; m < typ.NumMethod(); m++ { - method = typ.Method(m) - if mt := suiteMethod(method); mt != nil { - methodName, ok := methodMapper[method.Name] - if !ok { - methodName = method.Name - } - methods[methodName] = mt - mts = append(mts, methodName) - } - } - return strings.Join(mts, ","), methods -} - -// suiteMethod returns a suitable Rpc methodType -func suiteMethod(method reflect.Method) *MethodType { - mtype := method.Type - mname := method.Name - inNum := mtype.NumIn() - outNum := mtype.NumOut() - - // Method must be exported. - if method.PkgPath != "" { - return nil - } - - var ( - replyType, ctxType reflect.Type - argsType []reflect.Type - ) - - // this method is in RPCService - // we force users must implement RPCService interface in their provider - // and RPCService has only one method "Reference" - // In general, this method should not be exported to client - // so we ignore this method - // see RPCService - if mname == "Reference" { - return nil - } - - if outNum != 1 && outNum != 2 { - return nil - } - - // The latest return type of the method must be error. - if returnType := mtype.Out(outNum - 1); returnType != typeOfError { - return nil - } - - // replyType - if outNum == 2 { - replyType = mtype.Out(0) - if !isExportedOrBuiltinType(replyType) { - return nil - } - } - - index := 1 - - // ctxType - if inNum > 1 && mtype.In(1).String() == "context.Context" { - ctxType = mtype.In(1) - index = 2 - } - - for ; index < inNum; index++ { - argsType = append(argsType, mtype.In(index)) - // need not be a pointer. - if !isExportedOrBuiltinType(mtype.In(index)) { - return nil - } - } - - return &MethodType{method: method, argsType: argsType, replyType: replyType, ctxType: ctxType} -} diff --git a/dubbogo/rpc_service_test.go b/dubbogo/rpc_service_test.go deleted file mode 100644 index 6bf54b3..0000000 --- a/dubbogo/rpc_service_test.go +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxdubbogo - -import ( - "context" - "reflect" - "testing" -) - -import ( - "github.com/stretchr/testify/assert" -) - -import ( - constant "github.com/dubbogo/gost/dubbogo/constant" -) - -const ( - referenceTestPath = "com.test.Path" - referenceTestPathDistinct = "com.test.Path1" - testInterfaceName = "testService" - testProtocol = "testprotocol" - testSuiteMethodExpectedString = "interface {}" -) - -type TestService struct{} - -func (s *TestService) MethodOne(ctx context.Context, arg1, arg2, arg3 interface{}) error { - return nil -} - -func (s *TestService) MethodTwo(arg1, arg2, arg3 interface{}) (interface{}, error) { - return struct{}{}, nil -} - -func (s *TestService) MethodThree() error { - return nil -} - -func (s *TestService) Reference() string { - return referenceTestPath -} - -func (s *TestService) MethodMapper() map[string]string { - return map[string]string{ - "MethodTwo": "methodTwo", - } -} - -type testService struct{} - -func (s *testService) Method1(ctx context.Context, args testService, rsp *struct{}) error { - return nil -} - -func (s *testService) Method2(ctx context.Context, args []interface{}) (testService, error) { - return testService{}, nil -} - -func (s *testService) Method3(ctx context.Context, args []interface{}, rsp *struct{}) { -} - -func (s *testService) Method4(ctx context.Context, args []interface{}, rsp *struct{}) *testService { - return nil -} - -func (s *testService) Reference() string { - return referenceTestPath -} - -type TestService1 struct{} - -func (s *TestService1) Reference() string { - return referenceTestPathDistinct -} - -func TestServiceMapRegister(t *testing.T) { - // lowercase - s0 := &testService{} - // methods, err := ServiceMap.Register("testporotocol", s0) - _, err := ServiceMap.Register(testInterfaceName, "testporotocol", "", "v0", s0) - assert.EqualError(t, err, "type testService is not exported") - - // succ - s := &TestService{} - methods, err := ServiceMap.Register(testInterfaceName, "testporotocol", "", "v1", s) - assert.NoError(t, err) - assert.Equal(t, "MethodOne,MethodThree,methodTwo", methods) - - // repeat - _, err = ServiceMap.Register(testInterfaceName, "testporotocol", "", "v1", s) - assert.EqualError(t, err, "service already defined: testService:v1") - - // no method - s1 := &TestService1{} - _, err = ServiceMap.Register(testInterfaceName, "testporotocol", "", "v2", s1) - assert.EqualError(t, err, "type testService:v2 has no exported methods of suitable type") - - ServiceMap = &serviceMap{ - serviceMap: make(map[string]map[string]*Service), - interfaceMap: make(map[string][]*Service), - } -} - -func TestServiceMapUnRegister(t *testing.T) { - s := &TestService{} - _, err := ServiceMap.Register("TestService", testProtocol, "", "v1", s) - assert.NoError(t, err) - assert.NotNil(t, ServiceMap.GetService(testProtocol, "TestService", "", "v1")) - assert.Equal(t, 1, len(ServiceMap.GetInterface("TestService"))) - - err = ServiceMap.UnRegister("", "", ServiceKey("TestService", "", "v1")) - assert.EqualError(t, err, "protocol or serviceKey is nil") - - err = ServiceMap.UnRegister("", "protocol", ServiceKey("TestService", "", "v1")) - assert.EqualError(t, err, "no services for protocol") - - err = ServiceMap.UnRegister("", testProtocol, ServiceKey("TestService", "", "v0")) - assert.EqualError(t, err, "no service for TestService:v0") - - // success - err = ServiceMap.UnRegister("TestService", testProtocol, ServiceKey("TestService", "", "v1")) - assert.NoError(t, err) -} - -func TestMethodTypeSuiteContext(t *testing.T) { - mt := &MethodType{ctxType: reflect.TypeOf(context.TODO())} - ctx := context.Background() - key := constant.DubboCtxKey("key") - ctx = context.WithValue(ctx, key, "value") - assert.Equal(t, reflect.ValueOf(ctx), mt.SuiteContext(ctx)) -} - -func TestSuiteMethod(t *testing.T) { - s := &TestService{} - method, ok := reflect.TypeOf(s).MethodByName("MethodOne") - assert.True(t, ok) - methodType := suiteMethod(method) - method = methodType.Method() - assert.Equal(t, "func(*gxdubbogo.TestService, context.Context, interface {}, interface {}, interface {}) error", method.Type.String()) - at := methodType.ArgsType() - assert.Equal(t, testSuiteMethodExpectedString, at[0].String()) - assert.Equal(t, testSuiteMethodExpectedString, at[1].String()) - assert.Equal(t, testSuiteMethodExpectedString, at[2].String()) - ct := methodType.CtxType() - assert.Equal(t, "context.Context", ct.String()) - rt := methodType.ReplyType() - assert.Nil(t, rt) - - method, ok = reflect.TypeOf(s).MethodByName("MethodTwo") - assert.True(t, ok) - methodType = suiteMethod(method) - method = methodType.Method() - assert.Equal(t, "func(*gxdubbogo.TestService, interface {}, interface {}, interface {}) (interface {}, error)", method.Type.String()) - at = methodType.ArgsType() - assert.Equal(t, testSuiteMethodExpectedString, at[0].String()) - assert.Equal(t, testSuiteMethodExpectedString, at[1].String()) - assert.Equal(t, testSuiteMethodExpectedString, at[2].String()) - assert.Nil(t, methodType.CtxType()) - rt = methodType.ReplyType() - assert.Equal(t, testSuiteMethodExpectedString, rt.String()) - - method, ok = reflect.TypeOf(s).MethodByName("MethodThree") - assert.True(t, ok) - methodType = suiteMethod(method) - method = methodType.Method() - assert.Equal(t, "func(*gxdubbogo.TestService) error", method.Type.String()) - at = methodType.ArgsType() - assert.Equal(t, 0, len(at)) - assert.Nil(t, methodType.CtxType()) - rt = methodType.ReplyType() - assert.Nil(t, rt) - - // wrong number of in return - s1 := &testService{} - method, ok = reflect.TypeOf(s1).MethodByName("Reference") - assert.True(t, ok) - methodType = suiteMethod(method) - assert.Nil(t, methodType) - - // args not exported - method, ok = reflect.TypeOf(s1).MethodByName("Method1") - assert.True(t, ok) - methodType = suiteMethod(method) - assert.Nil(t, methodType) - - // Reply not exported - method, ok = reflect.TypeOf(s1).MethodByName("Method2") - assert.True(t, ok) - methodType = suiteMethod(method) - assert.Nil(t, methodType) - - // no return - method, ok = reflect.TypeOf(s1).MethodByName("Method3") - assert.True(t, ok) - methodType = suiteMethod(method) - assert.Nil(t, methodType) - - // return value is not error - method, ok = reflect.TypeOf(s1).MethodByName("Method4") - assert.True(t, ok) - methodType = suiteMethod(method) - assert.Nil(t, methodType) -} diff --git a/dubbogo/url.go b/dubbogo/url.go deleted file mode 100644 index 7a677a7..0000000 --- a/dubbogo/url.go +++ /dev/null @@ -1,837 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxdubbogo - -import ( - "bytes" - "encoding/base64" - "fmt" - "math" - "net" - "net/url" - "strconv" - "strings" - "sync" -) - -import ( - cm "github.com/Workiva/go-datastructures/common" - "github.com/jinzhu/copier" - perrors "github.com/pkg/errors" - "github.com/satori/go.uuid" -) - -import ( - gxset "github.com/dubbogo/gost/container/set" - constant "github.com/dubbogo/gost/dubbogo/constant" -) - -// /////////////////////////////// -// dubbo role type -// /////////////////////////////// - -// role constant -const ( - // CONSUMER is consumer role - CONSUMER = iota - // CONFIGURATOR is configurator role - CONFIGURATOR - // ROUTER is router role - ROUTER - // PROVIDER is provider role - PROVIDER - PROTOCOL = "protocol" -) - -var ( - // DubboNodes Dubbo service node - DubboNodes = [...]string{"consumers", "configurators", "routers", "providers"} - // DubboRole Dubbo service role - DubboRole = [...]string{"consumer", "", "routers", "provider"} - // CompareURLEqualFunc compare two url is equal - compareURLEqualFunc CompareURLEqualFunc -) - -func init() { - compareURLEqualFunc = defaultCompareURLEqual -} - -// nolint -type RoleType int - -func (t RoleType) String() string { - return DubboNodes[t] -} - -// Role returns role by @RoleType -func (t RoleType) Role() string { - return DubboRole[t] -} - -type baseUrl struct { - Protocol string - Location string // ip+port - Ip string - Port string - - PrimitiveURL string -} - -// noCopy may be embedded into structs which must not be copied -// after the first use. -// -// See https://golang.org/issues/8005#issuecomment-190753527 -// for details. -type noCopy struct{} - -// Lock is a no-op used by -copylocks checker from `go vet`. -func (*noCopy) Lock() {} -func (*noCopy) Unlock() {} - -// URL thread-safe. but this url should not be copied. -// we fail to define this struct to be immutable object. -// but, those method which will update the URL, including SetParam, SetParams -// are only allowed to be invoked in creating URL instance -// Please keep in mind that this struct is immutable after it has been created and initialized. -type URL struct { - noCopy noCopy - - baseUrl - // url.Values is not safe map, add to avoid concurrent map read and map write error - paramsLock sync.RWMutex - params url.Values - - Path string // like /com.ikurento.dubbo.UserProvider - Username string - Password string - Methods []string - // special for registry - SubURL *URL -} - -// Option accepts url -// Option will define a function of handling URL -type Option func(*URL) - -// WithUsername sets username for url -func WithUsername(username string) Option { - return func(url *URL) { - url.Username = username - } -} - -// WithPassword sets password for url -func WithPassword(pwd string) Option { - return func(url *URL) { - url.Password = pwd - } -} - -// WithMethods sets methods for url -func WithMethods(methods []string) Option { - return func(url *URL) { - url.Methods = methods - } -} - -// WithParams sets params for url -func WithParams(params url.Values) Option { - return func(url *URL) { - url.params = params - } -} - -// WithParamsValue sets params field for url -func WithParamsValue(key, val string) Option { - return func(url *URL) { - url.SetParam(key, val) - } -} - -// WithProtocol sets protocol for url -func WithProtocol(proto string) Option { - return func(url *URL) { - url.Protocol = proto - } -} - -// WithIp sets ip for url -func WithIp(ip string) Option { - return func(url *URL) { - url.Ip = ip - } -} - -// WithPort sets port for url -func WithPort(port string) Option { - return func(url *URL) { - url.Port = port - } -} - -// WithPath sets path for url -func WithPath(path string) Option { - return func(url *URL) { - url.Path = "/" + strings.TrimPrefix(path, "/") - } -} - -// WithLocation sets location for url -func WithLocation(location string) Option { - return func(url *URL) { - url.Location = location - } -} - -// WithToken sets token for url -func WithToken(token string) Option { - return func(url *URL) { - if len(token) > 0 { - value := token - if strings.ToLower(token) == "true" || strings.ToLower(token) == "default" { - u, err := uuid.NewV4() - if err != nil { - return - } - value = u.String() - } - url.SetParam(constant.TOKEN_KEY, value) - } - } -} - -// NewURLWithOptions will create a new url with options -func NewURLWithOptions(opts ...Option) *URL { - newURL := &URL{} - for _, opt := range opts { - opt(newURL) - } - newURL.Location = newURL.Ip + ":" + newURL.Port - return newURL -} - -// NewURL will create a new url -// the urlString should not be empty -func NewURL(urlString string, opts ...Option) (*URL, error) { - s := URL{baseUrl: baseUrl{}} - if urlString == "" { - return &s, nil - } - - rawUrlString, err := url.QueryUnescape(urlString) - if err != nil { - return &s, perrors.Errorf("url.QueryUnescape(%s), error{%v}", urlString, err) - } - - // rawUrlString = "//" + rawUrlString - if !strings.Contains(rawUrlString, "//") { - t := URL{baseUrl: baseUrl{}} - for _, opt := range opts { - opt(&t) - } - rawUrlString = t.Protocol + "://" + rawUrlString - } - - serviceUrl, urlParseErr := url.Parse(rawUrlString) - if urlParseErr != nil { - return &s, perrors.Errorf("url.Parse(url string{%s}), error{%v}", rawUrlString, err) - } - - s.params, err = url.ParseQuery(serviceUrl.RawQuery) - if err != nil { - return &s, perrors.Errorf("url.ParseQuery(raw url string{%s}), error{%v}", serviceUrl.RawQuery, err) - } - - s.PrimitiveURL = urlString - s.Protocol = serviceUrl.Scheme - s.Username = serviceUrl.User.Username() - s.Password, _ = serviceUrl.User.Password() - s.Location = serviceUrl.Host - s.Path = serviceUrl.Path - if strings.Contains(s.Location, ":") { - s.Ip, s.Port, err = net.SplitHostPort(s.Location) - if err != nil { - return &s, perrors.Errorf("net.SplitHostPort(url.Host{%s}), error{%v}", s.Location, err) - } - } - for _, opt := range opts { - opt(&s) - } - return &s, nil -} - -// URLEqual judge @url and @c is equal or not. -func (c *URL) URLEqual(url *URL) bool { - tmpC := c.Clone() - tmpC.Ip = "" - tmpC.Port = "" - - tmpUrl := url.Clone() - tmpUrl.Ip = "" - tmpUrl.Port = "" - - cGroup := tmpC.GetParam(constant.GROUP_KEY, "") - urlGroup := tmpUrl.GetParam(constant.GROUP_KEY, "") - cKey := tmpC.Key() - urlKey := tmpUrl.Key() - - if cGroup == constant.ANY_VALUE { - cKey = strings.Replace(cKey, "group=*", "group="+urlGroup, 1) - } else if urlGroup == constant.ANY_VALUE { - urlKey = strings.Replace(urlKey, "group=*", "group="+cGroup, 1) - } - - // 1. protocol, username, password, ip, port, service name, group, version should be equal - if cKey != urlKey { - return false - } - - // 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 { - 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)) -} - -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 true - } else if strings.Contains(category2, constant.REMOVE_VALUE_PREFIX) { - return !strings.Contains(category2, constant.REMOVE_VALUE_PREFIX+category1) - } else { - return strings.Contains(category2, category1) - } -} - -func (c *URL) String() string { - c.paramsLock.Lock() - defer c.paramsLock.Unlock() - var buf strings.Builder - if len(c.Username) == 0 && len(c.Password) == 0 { - buf.WriteString(fmt.Sprintf("%s://%s:%s%s?", c.Protocol, c.Ip, c.Port, c.Path)) - } else { - buf.WriteString(fmt.Sprintf("%s://%s:%s@%s:%s%s?", c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Path)) - } - buf.WriteString(c.params.Encode()) - return buf.String() -} - -// Key gets key -func (c *URL) Key() string { - buildString := fmt.Sprintf("%s://%s:%s@%s:%s/?interface=%s&group=%s&version=%s", - c.Protocol, c.Username, c.Password, c.Ip, c.Port, c.Service(), c.GetParam(constant.GROUP_KEY, ""), c.GetParam(constant.VERSION_KEY, "")) - return buildString -} - -// ServiceKey gets a unique key of a service. -func (c *URL) ServiceKey() string { - return ServiceKey(c.GetParam(constant.INTERFACE_KEY, strings.TrimPrefix(c.Path, "/")), - c.GetParam(constant.GROUP_KEY, ""), c.GetParam(constant.VERSION_KEY, "")) -} - -func ServiceKey(intf string, group string, version string) string { - if intf == "" { - return "" - } - buf := &bytes.Buffer{} - if group != "" { - buf.WriteString(group) - buf.WriteString("/") - } - - buf.WriteString(intf) - - if version != "" && version != "0.0.0" { - buf.WriteString(":") - buf.WriteString(version) - } - - return buf.String() -} - -// ColonSeparatedKey -// The format is "{interface}:[version]:[group]" -func (c *URL) ColonSeparatedKey() string { - intf := c.GetParam(constant.INTERFACE_KEY, strings.TrimPrefix(c.Path, "/")) - if intf == "" { - return "" - } - var buf strings.Builder - buf.WriteString(intf) - buf.WriteString(":") - version := c.GetParam(constant.VERSION_KEY, "") - if version != "" && version != "0.0.0" { - buf.WriteString(version) - } - group := c.GetParam(constant.GROUP_KEY, "") - buf.WriteString(":") - if group != "" { - buf.WriteString(group) - } - return buf.String() -} - -// EncodedServiceKey encode the service key -func (c *URL) EncodedServiceKey() string { - serviceKey := c.ServiceKey() - return strings.Replace(serviceKey, "/", "*", 1) -} - -// Service gets service -func (c *URL) Service() string { - service := c.GetParam(constant.INTERFACE_KEY, strings.TrimPrefix(c.Path, "/")) - if service != "" { - return service - } else if c.SubURL != nil { - service = c.SubURL.GetParam(constant.INTERFACE_KEY, strings.TrimPrefix(c.Path, "/")) - if service != "" { // if url.path is "" then return suburl's path, special for registry url - return service - } - } - return "" -} - -// AddParam will add the key-value pair -func (c *URL) AddParam(key string, value string) { - c.paramsLock.Lock() - defer c.paramsLock.Unlock() - if c.params == nil { - c.params = url.Values{} - } - c.params.Add(key, value) -} - -// AddParamAvoidNil will add key-value pair -func (c *URL) AddParamAvoidNil(key string, value string) { - c.paramsLock.Lock() - defer c.paramsLock.Unlock() - if c.params == nil { - c.params = url.Values{} - } - c.params.Add(key, value) -} - -// SetParam will put the key-value pair into url -// usually it should only be invoked when you want to initialized an url -func (c *URL) SetParam(key string, value string) { - c.paramsLock.Lock() - defer c.paramsLock.Unlock() - if c.params == nil { - c.params = url.Values{} - } - c.params.Set(key, value) -} - -// DelParam will delete the given key from the url -func (c *URL) DelParam(key string) { - c.paramsLock.Lock() - defer c.paramsLock.Unlock() - if c.params != nil { - c.params.Del(key) - } -} - -// ReplaceParams will replace the URL.params -// usually it should only be invoked when you want to modify an url, such as MergeURL -func (c *URL) ReplaceParams(param url.Values) { - c.paramsLock.Lock() - defer c.paramsLock.Unlock() - c.params = param -} - -// RangeParams will iterate the params -func (c *URL) RangeParams(f func(key, value string) bool) { - c.paramsLock.RLock() - defer c.paramsLock.RUnlock() - for k, v := range c.params { - if !f(k, v[0]) { - break - } - } -} - -// GetParam gets value by key -func (c *URL) GetParam(s string, d string) string { - c.paramsLock.RLock() - defer c.paramsLock.RUnlock() - - var r string - if len(c.params) > 0 { - r = c.params.Get(s) - } - if len(r) == 0 { - r = d - } - - return r -} - -// GetParams gets values -func (c *URL) GetParams() url.Values { - return c.params -} - -// GetParamAndDecoded gets values and decode -func (c *URL) GetParamAndDecoded(key string) (string, error) { - ruleDec, err := base64.URLEncoding.DecodeString(c.GetParam(key, "")) - value := string(ruleDec) - return value, err -} - -// GetRawParam gets raw param -func (c *URL) GetRawParam(key string) string { - switch key { - case PROTOCOL: - return c.Protocol - case "username": - return c.Username - case "host": - return strings.Split(c.Location, ":")[0] - case "password": - return c.Password - case "port": - return c.Port - case "path": - return c.Path - default: - return c.GetParam(key, "") - } -} - -// GetParamBool judge whether @key exists or not -func (c *URL) GetParamBool(key string, d bool) bool { - r, err := strconv.ParseBool(c.GetParam(key, "")) - if err != nil { - return d - } - return r -} - -// GetParamInt gets int64 value by @key -func (c *URL) GetParamInt(key string, d int64) int64 { - r, err := strconv.ParseInt(c.GetParam(key, ""), 10, 64) - if err != nil { - return d - } - return r -} - -// GetParamInt32 gets int32 value by @key -func (c *URL) GetParamInt32(key string, d int32) int32 { - r, err := strconv.ParseInt(c.GetParam(key, ""), 10, 32) - if err != nil { - return d - } - return int32(r) -} - -// GetParamByIntValue gets int value by @key -func (c *URL) GetParamByIntValue(key string, d int) int { - r, err := strconv.ParseInt(c.GetParam(key, ""), 10, 0) - if err != nil { - return d - } - return int(r) -} - -// GetMethodParamInt gets int method param -func (c *URL) GetMethodParamInt(method string, key string, d int64) int64 { - r, err := strconv.ParseInt(c.GetParam("methods."+method+"."+key, ""), 10, 64) - if err != nil { - return d - } - return r -} - -// GetMethodParamIntValue gets int method param -func (c *URL) GetMethodParamIntValue(method string, key string, d int) int { - r, err := strconv.ParseInt(c.GetParam("methods."+method+"."+key, ""), 10, 0) - if err != nil { - return d - } - return int(r) -} - -// GetMethodParamInt64 gets int64 method param -func (c *URL) GetMethodParamInt64(method string, key string, d int64) int64 { - r := c.GetMethodParamInt(method, key, math.MinInt64) - if r == math.MinInt64 { - return c.GetParamInt(key, d) - } - return r -} - -// GetMethodParam gets method param -func (c *URL) GetMethodParam(method string, key string, d string) string { - r := c.GetParam("methods."+method+"."+key, "") - if r == "" { - r = d - } - return r -} - -// GetMethodParamBool judge whether @method param exists or not -func (c *URL) GetMethodParamBool(method string, key string, d bool) bool { - r := c.GetParamBool("methods."+method+"."+key, d) - return r -} - -// SetParams will put all key-value pair into url. -// 1. if there already has same key, the value will be override -// 2. it's not thread safe -// 3. think twice when you want to invoke this method -func (c *URL) SetParams(m url.Values) { - for k := range m { - c.SetParam(k, m.Get(k)) - } -} - -// ToMap transfer URL to Map -func (c *URL) ToMap() map[string]string { - paramsMap := make(map[string]string) - - c.RangeParams(func(key, value string) bool { - paramsMap[key] = value - return true - }) - - if c.Protocol != "" { - paramsMap[PROTOCOL] = c.Protocol - } - if c.Username != "" { - paramsMap["username"] = c.Username - } - if c.Password != "" { - paramsMap["password"] = c.Password - } - if c.Location != "" { - paramsMap["host"] = strings.Split(c.Location, ":")[0] - var port string - if strings.Contains(c.Location, ":") { - port = strings.Split(c.Location, ":")[1] - } else { - port = "0" - } - paramsMap["port"] = port - } - if c.Protocol != "" { - paramsMap[PROTOCOL] = c.Protocol - } - if c.Path != "" { - paramsMap["path"] = c.Path - } - if len(paramsMap) == 0 { - return nil - } - return paramsMap -} - -// configuration > reference config >service config -// in this function we should merge the reference local url config into the service url from registry. -// TODO configuration merge, in the future , the configuration center's config should merge too. - -// MergeURL will merge those two url -// the result is based on serviceUrl, and the key which si only contained in referenceUrl -// will be added into result. -// for example, if serviceUrl contains params (a1->v1, b1->v2) and referenceUrl contains params(a2->v3, b1 -> v4) -// the params of result will be (a1->v1, b1->v2, a2->v3). -// You should notice that the value of b1 is v2, not v4. -// due to URL is not thread-safe, so this method is not thread-safe -func MergeURL(serviceUrl *URL, referenceUrl *URL) *URL { - // After Clone, it is a new url that there is no thread safe issue. - mergedUrl := serviceUrl.Clone() - params := mergedUrl.GetParams() - // iterator the referenceUrl if serviceUrl not have the key ,merge in - // referenceUrl usually will not changed. so change RangeParams to GetParams to avoid the string value copy. - for key, value := range referenceUrl.GetParams() { - if v := mergedUrl.GetParam(key, ""); len(v) == 0 { - if len(value) > 0 { - params[key] = value - } - } - } - - // loadBalance,cluster,retries strategy config - methodConfigMergeFcn := mergeNormalParam(params, referenceUrl, []string{constant.LOADBALANCE_KEY, constant.CLUSTER_KEY, constant.RETRIES_KEY, constant.TIMEOUT_KEY}) - - // 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, "")} - } - - // finally execute methodConfigMergeFcn - for _, method := range referenceUrl.Methods { - for _, fcn := range methodConfigMergeFcn { - fcn("methods." + method) - } - } - // In this way, we will raise some performance. - mergedUrl.ReplaceParams(params) - return mergedUrl -} - -// Clone will copy the url -func (c *URL) Clone() *URL { - newURL := &URL{} - if err := copier.Copy(newURL, c); err != nil { - // this is impossible - return newURL - } - newURL.params = url.Values{} - c.RangeParams(func(key, value string) bool { - newURL.SetParam(key, value) - return true - }) - - return newURL -} - -func (c *URL) CloneExceptParams(excludeParams *gxset.HashSet) *URL { - newURL := &URL{} - if err := copier.Copy(newURL, c); err != nil { - // this is impossible - return newURL - } - newURL.params = url.Values{} - c.RangeParams(func(key, value string) bool { - if !excludeParams.Contains(key) { - newURL.SetParam(key, value) - } - return true - }) - return newURL -} - -func (c *URL) Compare(comp cm.Comparator) int { - a := c.String() - b := comp.(*URL).String() - switch { - case a > b: - return 1 - case a < b: - return -1 - default: - return 0 - } -} - -// Copy url based on the reserved parameter's keys. -func (c *URL) CloneWithParams(reserveParams []string) *URL { - params := url.Values{} - for _, reserveParam := range reserveParams { - v := c.GetParam(reserveParam, "") - if len(v) != 0 { - params.Set(reserveParam, v) - } - } - - return NewURLWithOptions( - WithProtocol(c.Protocol), - WithUsername(c.Username), - WithPassword(c.Password), - WithIp(c.Ip), - WithPort(c.Port), - WithPath(c.Path), - WithMethods(c.Methods), - WithParams(params), - ) -} - -// IsEquals compares if two URLs equals with each other. Excludes are all parameter keys which should ignored. -func IsEquals(left *URL, right *URL, excludes ...string) bool { - if (left == nil && right != nil) || (right == nil && left != nil) { - return false - } - if left.Ip != right.Ip || left.Port != right.Port { - return false - } - - leftMap := left.ToMap() - rightMap := right.ToMap() - for _, exclude := range excludes { - delete(leftMap, exclude) - delete(rightMap, exclude) - } - - if len(leftMap) != len(rightMap) { - return false - } - - for lk, lv := range leftMap { - if rv, ok := rightMap[lk]; !ok { - return false - } else if lv != rv { - return false - } - } - - return true -} - -func mergeNormalParam(params url.Values, referenceUrl *URL, paramKeys []string) []func(method string) { - methodConfigMergeFcn := make([]func(method string), 0, len(paramKeys)) - for _, paramKey := range paramKeys { - if v := referenceUrl.GetParam(paramKey, ""); len(v) > 0 { - params[paramKey] = []string{v} - } - methodConfigMergeFcn = append(methodConfigMergeFcn, func(method string) { - if v := referenceUrl.GetParam(method+"."+paramKey, ""); len(v) > 0 { - params[method+"."+paramKey] = []string{v} - } - }) - } - return methodConfigMergeFcn -} - -// URLSlice will be used to sort URL instance -// Instances will be order by URL.String() -type URLSlice []*URL - -// nolint -func (s URLSlice) Len() int { - return len(s) -} - -// nolint -func (s URLSlice) Less(i, j int) bool { - return s[i].String() < s[j].String() -} - -// nolint -func (s URLSlice) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -type CompareURLEqualFunc func(l *URL, r *URL, excludeParam ...string) bool - -func defaultCompareURLEqual(l *URL, r *URL, excludeParam ...string) bool { - return IsEquals(l, r, excludeParam...) -} - -func SetCompareURLEqualFunc(f CompareURLEqualFunc) { - compareURLEqualFunc = f -} - -func GetCompareURLEqualFunc() CompareURLEqualFunc { - return compareURLEqualFunc -} diff --git a/dubbogo/url_test.go b/dubbogo/url_test.go deleted file mode 100644 index f7400e7..0000000 --- a/dubbogo/url_test.go +++ /dev/null @@ -1,423 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package gxdubbogo - -import ( - "encoding/base64" - "net/url" - "testing" -) - -import ( - "github.com/stretchr/testify/assert" -) - -import ( - constant "github.com/dubbogo/gost/dubbogo/constant" -) - -const ( - userName = "username" - password = "password" - loopbackAddress = "127.0.0.1" -) - -func TestNewURLWithOptions(t *testing.T) { - methods := []string{"Methodone,methodtwo"} - params := url.Values{} - params.Set("key", "value") - u := NewURLWithOptions(WithPath("com.test.Service"), - WithUsername(userName), - WithPassword(password), - WithProtocol("testprotocol"), - WithIp(loopbackAddress), - WithPort("8080"), - WithMethods(methods), - WithParams(params), - WithParamsValue("key2", "value2")) - assert.Equal(t, "/com.test.Service", u.Path) - assert.Equal(t, userName, u.Username) - assert.Equal(t, password, u.Password) - assert.Equal(t, "testprotocol", u.Protocol) - assert.Equal(t, loopbackAddress, u.Ip) - assert.Equal(t, "8080", u.Port) - assert.Equal(t, methods, u.Methods) - assert.Equal(t, params, u.params) -} - -func TestURL(t *testing.T) { - u, err := 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&" + - "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=1556509797245") - assert.NoError(t, err) - - urlInst := URL{} - urlInst.noCopy.Lock() - urlInst.SetParam("hello", "world") - urlInst.noCopy.Unlock() - - assert.Equal(t, "/com.ikurento.user.UserProvider", u.Path) - assert.Equal(t, "127.0.0.1:20000", u.Location) - assert.Equal(t, "dubbo", u.Protocol) - assert.Equal(t, loopbackAddress, u.Ip) - assert.Equal(t, "20000", u.Port) - assert.Equal(t, urlInst.Methods, u.Methods) - assert.Equal(t, "", u.Username) - assert.Equal(t, "", u.Password) - assert.Equal(t, "anyhost=true&application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-"+ - "provider-golang-1.0.0&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&t"+ - "imestamp=1556509797245", u.params.Encode()) - - assert.Equal(t, "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&application=BDTServi"+ - "ce&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&environment=dev&interface=com.ikure"+ - "nto.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=1556509797245", u.String()) -} - -func TestURLWithoutSchema(t *testing.T) { - u, err := NewURL("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&"+ - "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=1556509797245", WithProtocol("dubbo")) - assert.NoError(t, err) - - assert.Equal(t, "/com.ikurento.user.UserProvider", u.Path) - assert.Equal(t, "127.0.0.1:20000", u.Location) - assert.Equal(t, "dubbo", u.Protocol) - assert.Equal(t, loopbackAddress, u.Ip) - assert.Equal(t, "20000", u.Port) - assert.Equal(t, URL{}.Methods, u.Methods) - assert.Equal(t, "", u.Username) - assert.Equal(t, "", u.Password) - assert.Equal(t, "anyhost=true&application=BDTService&category=providers&default.timeout=10000&dubbo=dubbo-"+ - "provider-golang-1.0.0&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&t"+ - "imestamp=1556509797245", u.params.Encode()) - - assert.Equal(t, "dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?anyhost=true&application=BDTServi"+ - "ce&category=providers&default.timeout=10000&dubbo=dubbo-provider-golang-1.0.0&environment=dev&interface=com.ikure"+ - "nto.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=1556509797245", u.String()) -} - -func TestURLEqual(t *testing.T) { - u1, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0") - assert.NoError(t, err) - u2, err := NewURL("dubbo://127.0.0.2:20001/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0") - assert.NoError(t, err) - assert.True(t, u1.URLEqual(u2)) - - u3, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=gg&version=2.6.0") - assert.NoError(t, err) - assert.False(t, u1.URLEqual(u3)) - - // urlGroupAnyValue's group is * - urlGroupAnyValue, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=*&version=2.6.0") - assert.NoError(t, err) - assert.True(t, u3.URLEqual(urlGroupAnyValue)) - - // test for enabled - urlEnabledEmpty, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=*&version=2.6.0&enabled=") - assert.NoError(t, err) - assert.True(t, u3.URLEqual(urlEnabledEmpty)) - - urlEnabledFalse, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=*&version=2.6.0&enabled=1") - assert.NoError(t, err) - assert.False(t, u3.URLEqual(urlEnabledFalse)) - - urlEnabledTrue, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=*&version=2.6.0&enabled=true") - assert.NoError(t, err) - assert.True(t, u3.URLEqual(urlEnabledTrue)) - - urlEnabledAny, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=*&version=2.6.0&enabled=*") - assert.NoError(t, err) - assert.True(t, u3.URLEqual(urlEnabledAny)) - - // test for category - categoryAny, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=*&version=2.6.0&enabled=*&category=*") - assert.NoError(t, err) - assert.True(t, categoryAny.URLEqual(u3)) -} - -func TestURLGetParam(t *testing.T) { - params := url.Values{} - params.Set("key", "value") - - u := URL{} - u.SetParams(params) - - v := u.GetParam("key", "default") - assert.Equal(t, "value", v) - - u = URL{} - v = u.GetParam("key", "default") - assert.Equal(t, "default", v) -} - -func TestURLGetParamInt(t *testing.T) { - params := url.Values{} - params.Set("key", "value") - - u := URL{} - u.SetParams(params) - - v := u.GetParamInt("key", 1) - assert.Equal(t, int64(1), v) - - u = URL{} - v = u.GetParamInt("key", 1) - assert.Equal(t, int64(1), v) -} - -func TestURLGetParamIntValue(t *testing.T) { - params := url.Values{} - params.Set("key", "0") - - u := URL{} - u.SetParams(params) - - v := u.GetParamInt("key", 1) - assert.Equal(t, int64(0), v) - - u = URL{} - v = u.GetParamInt("key", 1) - assert.Equal(t, int64(1), v) -} - -func TestURLGetParamBool(t *testing.T) { - params := url.Values{} - params.Set("force", "true") - - u := URL{} - u.SetParams(params) - - v := u.GetParamBool("force", false) - assert.Equal(t, true, v) - - u = URL{} - v = u.GetParamBool("force", false) - assert.Equal(t, false, v) -} - -func TestURLGetParamAndDecoded(t *testing.T) { - rule := "host = 2.2.2.2,1.1.1.1,3.3.3.3 & host !=1.1.1.1 => host = 1.2.3.4" - params := url.Values{} - params.Set("rule", base64.URLEncoding.EncodeToString([]byte(rule))) - - u := URL{} - u.SetParams(params) - - v, _ := u.GetParamAndDecoded("rule") - assert.Equal(t, rule, v) -} - -func TestURLGetRawParam(t *testing.T) { - u, _ := NewURL("condition://0.0.0.0:8080/com.foo.BarService?serialization=fastjson") - u.Username = "test" - u.Password = "test" - assert.Equal(t, "condition", u.GetRawParam("protocol")) - assert.Equal(t, "0.0.0.0", u.GetRawParam("host")) - assert.Equal(t, "8080", u.GetRawParam("port")) - assert.Equal(t, "test", u.GetRawParam(userName)) - assert.Equal(t, "test", u.GetRawParam(password)) - assert.Equal(t, "/com.foo.BarService", u.GetRawParam("path")) - assert.Equal(t, "fastjson", u.GetRawParam("serialization")) -} - -func TestURLToMap(t *testing.T) { - u, _ := NewURL("condition://0.0.0.0:8080/com.foo.BarService?serialization=fastjson") - u.Username = "test" - u.Password = "test" - - m := u.ToMap() - assert.Equal(t, 7, len(m)) - assert.Equal(t, "condition", m["protocol"]) - assert.Equal(t, "0.0.0.0", m["host"]) - assert.Equal(t, "8080", m["port"]) - assert.Equal(t, "test", m[userName]) - assert.Equal(t, "test", m[password]) - assert.Equal(t, "/com.foo.BarService", m["path"]) - assert.Equal(t, "fastjson", m["serialization"]) -} - -func TestURLGetMethodParamInt(t *testing.T) { - params := url.Values{} - params.Set("methods.GetValue.timeout", "3") - - u := URL{} - u.SetParams(params) - - v := u.GetMethodParamInt("GetValue", "timeout", 1) - assert.Equal(t, int64(3), v) - - u = URL{} - v = u.GetMethodParamInt("GetValue", "timeout", 1) - assert.Equal(t, int64(1), v) -} - -func TestURLGetMethodParam(t *testing.T) { - params := url.Values{} - params.Set("methods.GetValue.timeout", "3s") - - u := URL{} - u.SetParams(params) - - v := u.GetMethodParam("GetValue", "timeout", "1s") - assert.Equal(t, "3s", v) - - u = URL{} - v = u.GetMethodParam("GetValue", "timeout", "1s") - assert.Equal(t, "1s", v) -} - -func TestURLGetMethodParamBool(t *testing.T) { - params := url.Values{} - params.Set("methods.GetValue.async", "true") - - u := URL{} - u.SetParams(params) - - v := u.GetMethodParamBool("GetValue", "async", false) - assert.Equal(t, true, v) - - u = URL{} - v = u.GetMethodParamBool("GetValue2", "async", false) - assert.Equal(t, false, v) -} - -func TestMergeUrl(t *testing.T) { - referenceUrlParams := url.Values{} - referenceUrlParams.Set(constant.CLUSTER_KEY, "random") - referenceUrlParams.Set(constant.RETRIES_KEY, "1") - referenceUrlParams.Set("test3", "1") - referenceUrlParams.Set("methods.testMethod."+constant.RETRIES_KEY, "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") - 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, "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, "")) -} - -func TestURLSetParams(t *testing.T) { - u1, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&configVersion=1.0") - assert.NoError(t, err) - params := url.Values{} - params.Set("key", "3") - u1.SetParams(params) - assert.Equal(t, "3", u1.GetParam("key", "")) - assert.Equal(t, "2.6.0", u1.GetParam("version", "")) -} - -func TestURLReplaceParams(t *testing.T) { - u1, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&configVersion=1.0") - assert.NoError(t, err) - params := url.Values{} - params.Set("key", "3") - u1.ReplaceParams(params) - assert.Equal(t, "3", u1.GetParam("key", "")) - assert.Equal(t, "", u1.GetParam("version", "")) -} - -func TestClone(t *testing.T) { - u1, err := NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider?interface=com.ikurento.user.UserProvider&group=&version=2.6.0&configVersion=1.0") - assert.NoError(t, err) - u2 := u1.Clone() - assert.Equal(t, u2.Protocol, "dubbo") - assert.Equal(t, "1.0", u2.GetParam("configVersion", "")) - u2.Protocol = "provider" - assert.Equal(t, u1.Protocol, "dubbo") - assert.Equal(t, u2.Protocol, "provider") -} - -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") -} - -func TestCompareURLEqualFunc(t *testing.T) { - // test Default - 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&" + - "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=1556509797245") - url2, _ := 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&" + - "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.False(t, GetCompareURLEqualFunc()(url1, url2)) - assert.True(t, GetCompareURLEqualFunc()(url1, url2, constant.TIMESTAMP_KEY, constant.REMOTE_TIMESTAMP_KEY)) - - // test custom - 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&" + - "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=1556509797245") - url2, _ = 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&" + - "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)) - SetCompareURLEqualFunc(CustomCompareURLEqual) - assert.False(t, GetCompareURLEqualFunc()(url1, url2)) - assert.False(t, GetCompareURLEqualFunc()(url1, url2, constant.TIMESTAMP_KEY, constant.REMOTE_TIMESTAMP_KEY)) - - 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&" + - "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") - url2, _ = 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&" + - "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") - assert.True(t, GetCompareURLEqualFunc()(url1, url2)) - assert.True(t, GetCompareURLEqualFunc()(url1, url2, constant.TIMESTAMP_KEY, constant.REMOTE_TIMESTAMP_KEY)) - SetCompareURLEqualFunc(CustomCompareURLEqual) - assert.True(t, GetCompareURLEqualFunc()(url1, url2)) - assert.True(t, GetCompareURLEqualFunc()(url1, url2, constant.TIMESTAMP_KEY, constant.REMOTE_TIMESTAMP_KEY)) -} - -func CustomCompareURLEqual(l *URL, r *URL, execludeParam ...string) bool { - return l.PrimitiveURL == r.PrimitiveURL -} diff --git a/go.mod b/go.mod index 11fbc0e..6b69524 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,6 @@ module github.com/dubbogo/gost require ( github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect - github.com/Workiva/go-datastructures v1.0.52 github.com/coreos/go-semver v0.3.0 // indirect github.com/davecgh/go-spew v1.1.1 github.com/dubbogo/go-zookeeper v1.0.3 @@ -15,7 +14,6 @@ require ( github.com/gorilla/websocket v1.4.2 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.2.2 // indirect github.com/grpc-ecosystem/grpc-gateway v1.14.6 // indirect - github.com/jinzhu/copier v0.0.0-20190625015134-976e0346caa8 github.com/jonboulle/clockwork v0.2.2 // indirect github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect github.com/k0kubun/pp v3.0.1+incompatible @@ -25,7 +23,6 @@ require ( github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.9.0 // indirect - github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b github.com/shirou/gopsutil v3.20.11+incompatible github.com/stretchr/testify v1.7.0 github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802 // indirect diff --git a/go.sum b/go.sum index 4637c42..a188adc 100644 --- a/go.sum +++ b/go.sum @@ -10,8 +10,6 @@ github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMx github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk= github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= -github.com/Workiva/go-datastructures v1.0.52 h1:PLSK6pwn8mYdaoaCZEMsXBpBotr4HHn9abU0yMQt0NI= -github.com/Workiva/go-datastructures v1.0.52/go.mod h1:Z+F2Rca0qCsVYDS8z7bAGm8f3UkzuWYS/oBZz5a7VVA= github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= @@ -171,8 +169,6 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= -github.com/jinzhu/copier v0.0.0-20190625015134-976e0346caa8 h1:mGIXW/lubQ4B+3bXTLxcTMTjUNDqoF6T/HUW9LbFx9s= -github.com/jinzhu/copier v0.0.0-20190625015134-976e0346caa8/go.mod h1:yL958EeXv8Ylng6IfnvG4oflryUi3vgA3xPs9hmII1s= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ= @@ -303,8 +299,6 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= -github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b h1:gQZ0qzfKHQIybLANtM3mBXNUtOfsCFXeTsnBqCsx1KM= -github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/shirou/gopsutil v3.20.11+incompatible h1:LJr4ZQK4mPpIV5gOa4jCOKOGb4ty4DZO54I4FGqIpto= github.com/shirou/gopsutil v3.20.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=