diff --git a/cluster/cluster_impl/failback_cluster_invoker.go b/cluster/cluster_impl/failback_cluster_invoker.go index 7654e42ecb874a73bb3f00427fa38cb18ea480a3..5e0d133a670160df4acf321ea05356cb2a45a8b5 100644 --- a/cluster/cluster_impl/failback_cluster_invoker.go +++ b/cluster/cluster_impl/failback_cluster_invoker.go @@ -77,8 +77,7 @@ func (invoker *failbackClusterInvoker) tryTimerTaskProc(ctx context.Context, ret invoked = append(invoked, retryTask.lastInvoker) retryInvoker := invoker.doSelect(retryTask.loadbalance, retryTask.invocation, retryTask.invokers, invoked) - var result protocol.Result - result = retryInvoker.Invoke(ctx, retryTask.invocation) + result := retryInvoker.Invoke(ctx, retryTask.invocation) if result.Error() != nil { retryTask.lastInvoker = retryInvoker invoker.checkRetry(retryTask, result.Error()) diff --git a/cluster/router/chain/chain.go b/cluster/router/chain/chain.go index 8b98acb5821f257a129e8e5455af074a32a7257b..fccce838bb3f6750b72b83c4991ad78e8b49f138 100644 --- a/cluster/router/chain/chain.go +++ b/cluster/router/chain/chain.go @@ -195,7 +195,7 @@ func (c *RouterChain) copyInvokerIfNecessary(cache *InvokerCache) []protocol.Inv func (c *RouterChain) buildCache() { origin := c.loadCache() invokers := c.copyInvokerIfNecessary(origin) - if invokers == nil || len(invokers) == 0 { + if len(invokers) == 0 { return } diff --git a/cluster/router/chain/chain_test.go b/cluster/router/chain/chain_test.go index 92c59d76d5e46d5e20ffb0d274ecfc5c7a9fb3e3..a2b5642b806c7179017be0dd9c0bccc6123ba48c 100644 --- a/cluster/router/chain/chain_test.go +++ b/cluster/router/chain/chain_test.go @@ -238,6 +238,7 @@ conditions: func TestRouterChainRouteNoRoute(t *testing.T) { ts, z, _, err := zookeeper.NewMockZookeeperClient("test", 15*time.Second) + assert.Nil(t, err) defer func() { err := ts.Stop() assert.NoError(t, err) @@ -247,6 +248,7 @@ func TestRouterChainRouteNoRoute(t *testing.T) { zkUrl, _ := common.NewURL(fmt.Sprintf(zkFormat, localIP, ts.Servers[0].Port)) configuration, err := extension.GetConfigCenterFactory(zk).GetDynamicConfiguration(zkUrl) config.GetEnvInstance().SetDynamicConfiguration(configuration) + assert.Nil(t, err) chain, err := NewRouterChain(getConditionNoRouteUrl(applicationKey)) assert.Nil(t, err) diff --git a/cluster/router/condition/listenable_router.go b/cluster/router/condition/listenable_router.go index 0b47310dbfe9987a593bc2d0d949a76f08052114..102d766a8a787b460c878c42e8327c1a57ea9588 100644 --- a/cluster/router/condition/listenable_router.go +++ b/cluster/router/condition/listenable_router.go @@ -47,8 +47,8 @@ type listenableRouter struct { conditionRouters []*ConditionRouter routerRule *RouterRule url *common.URL - force bool - priority int64 + //force bool + priority int64 } // RouterRule Get RouterRule instance from listenableRouter diff --git a/cluster/router/tag/file.go b/cluster/router/tag/file.go index 94daf1508eb7b3f4d8a8cacdbd6ed634be6852da..a51ae69cf26fa6e7d10444a23cbff339a5a99b3e 100644 --- a/cluster/router/tag/file.go +++ b/cluster/router/tag/file.go @@ -41,7 +41,7 @@ type FileTagRouter struct { router *tagRouter routerRule *RouterRule url *common.URL - force bool + //force bool } // NewFileTagRouter Create file tag router instance with content (from config file) diff --git a/cluster/router/tag/router_rule.go b/cluster/router/tag/router_rule.go index c0a2d763ae7396ae41694f558f443d46084c3357..512d8f10795b04a18947396be8ae7fa6c4f49d4a 100644 --- a/cluster/router/tag/router_rule.go +++ b/cluster/router/tag/router_rule.go @@ -84,9 +84,9 @@ func (t *RouterRule) getTagNames() []string { return result } -func (t *RouterRule) hasTag(tag string) bool { - return len(t.TagNameToAddresses[tag]) > 0 -} +//func (t *RouterRule) hasTag(tag string) bool { +// return len(t.TagNameToAddresses[tag]) > 0 +//} func (t *RouterRule) getAddressToTagNames() map[string][]string { return t.AddressToTagNames @@ -96,10 +96,10 @@ func (t *RouterRule) getTagNameToAddresses() map[string][]string { return t.TagNameToAddresses } -func (t *RouterRule) getTags() []Tag { - return t.Tags -} +//func (t *RouterRule) getTags() []Tag { +// return t.Tags +//} -func (t *RouterRule) setTags(tags []Tag) { - t.Tags = tags -} +//func (t *RouterRule) setTags(tags []Tag) { +// t.Tags = tags +//} diff --git a/cluster/router/tag/tag_router.go b/cluster/router/tag/tag_router.go index c7f53047c1e2beee4545a10302e9f307f06c33d8..984ecb4eeff71dd692cbda8db5e3b87dbdde4254 100644 --- a/cluster/router/tag/tag_router.go +++ b/cluster/router/tag/tag_router.go @@ -53,7 +53,7 @@ type addrMetadata struct { // application name application string // is rule a runtime rule - ruleRuntime bool + //ruleRuntime bool // is rule a force rule ruleForce bool // is rule a valid rule @@ -227,7 +227,7 @@ func (c *tagRouter) Pool(invokers []protocol.Invoker) (router.AddrPool, router.A // fetchRuleIfNecessary fetches, parses rule and register listener for the further change func (c *tagRouter) fetchRuleIfNecessary(invokers []protocol.Invoker) { - if invokers == nil || len(invokers) == 0 { + if len(invokers) == 0 { return } diff --git a/cluster/router/tag/tag_router_test.go b/cluster/router/tag/tag_router_test.go index 20b511ddbd38dcca344f2a5cb7a662cebc37e39b..26c4b8352ba1fce4f6204628f6c09309e3b607d3 100644 --- a/cluster/router/tag/tag_router_test.go +++ b/cluster/router/tag/tag_router_test.go @@ -237,7 +237,7 @@ func TestRouteBeijingInvoker(t *testing.T) { type DynamicTagRouter struct { suite.Suite - rule *RouterRule + //rule *RouterRule route *tagRouter zkClient *zookeeper.ZookeeperClient diff --git a/common/config/environment.go b/common/config/environment.go index 44cdd1fca18bfed306b135fe38ef536779e148aa..c5651a335444e06f12eb5af831d878ffdbbaeb9f 100644 --- a/common/config/environment.go +++ b/common/config/environment.go @@ -34,8 +34,8 @@ import ( // We just have config center configuration which can override configuration in consumer.yaml & provider.yaml. // But for add these features in future ,I finish the environment struct following Environment class in java. type Environment struct { - configCenterFirst bool - externalConfigs sync.Map + configCenterFirst bool + //externalConfigs sync.Map externalConfigMap sync.Map appExternalConfigMap sync.Map dynamicConfiguration config_center.DynamicConfiguration diff --git a/common/constant/key.go b/common/constant/key.go index d020b9d40bbfd195345d1d24487d66cbe43ad5a3..12e3096e5af7f3075de8cd71fcb72061fb37ad0c 100644 --- a/common/constant/key.go +++ b/common/constant/key.go @@ -17,6 +17,8 @@ package constant +type DubboCtxKey string + const ( ASYNC_KEY = "async" // it's value should be "true" or "false" of string type ) @@ -47,8 +49,8 @@ const ( PORT_KEY = "port" PROTOCOL_KEY = "protocol" PATH_SEPARATOR = "/" - DUBBO_KEY = "dubbo" - SSL_ENABLED_KEY = "ssl-enabled" + //DUBBO_KEY = "dubbo" + SSL_ENABLED_KEY = "ssl-enabled" ) const ( @@ -92,7 +94,7 @@ const ( ) const ( - DUBBOGO_CTX_KEY = "dubbogo-ctx" + DUBBOGO_CTX_KEY = DubboCtxKey("dubbogo-ctx") ) const ( @@ -201,8 +203,6 @@ const ( TRACING_REMOTE_SPAN_CTX = "tracing.remote.span.ctx" ) -type AttachmentCtxKey string - // Use for router module const ( // ConditionRouterName Specify file condition router name @@ -240,7 +240,7 @@ const ( Tagkey = "dubbo.tag" // Attachment key in context in invoker - AttachmentKey = AttachmentCtxKey("attachment") + AttachmentKey = DubboCtxKey("attachment") ) const ( diff --git a/common/rpc_service_test.go b/common/rpc_service_test.go index 048e623c64db4a56cbb1cb202601d650a47c366c..e8bd3933da89b0a6c607f776eae1bb8603f8f467 100644 --- a/common/rpc_service_test.go +++ b/common/rpc_service_test.go @@ -27,6 +27,10 @@ import ( "github.com/stretchr/testify/assert" ) +import ( + "github.com/apache/dubbo-go/common/constant" +) + const ( referenceTestPath = "com.test.Path" referenceTestPathDistinct = "com.test.Path1" @@ -125,7 +129,7 @@ func TestServiceMapUnRegister(t *testing.T) { err = ServiceMap.UnRegister("", testProtocol, ServiceKey("TestService", "", "v0")) assert.EqualError(t, err, "no service for TestService:v0") - // succ + // success err = ServiceMap.UnRegister("TestService", testProtocol, ServiceKey("TestService", "", "v1")) assert.NoError(t, err) } @@ -133,16 +137,12 @@ func TestServiceMapUnRegister(t *testing.T) { func TestMethodTypeSuiteContext(t *testing.T) { mt := &MethodType{ctxType: reflect.TypeOf(context.TODO())} ctx := context.Background() - type ctxKey string - key := ctxKey("key") + key := constant.DubboCtxKey("key") ctx = context.WithValue(ctx, key, "value") assert.Equal(t, reflect.ValueOf(ctx), mt.SuiteContext(ctx)) - - assert.Equal(t, reflect.Zero(mt.ctxType), mt.SuiteContext(nil)) } func TestSuiteMethod(t *testing.T) { - s := &TestService{} method, ok := reflect.TypeOf(s).MethodByName("MethodOne") assert.True(t, ok) diff --git a/common/url.go b/common/url.go index 8faa0f08ce004441619898e8cc451102c7ddc796..87cacfd7fb68bd061c2d18c0b3216fc336f7228a 100644 --- a/common/url.go +++ b/common/url.go @@ -415,6 +415,9 @@ func (c *URL) Service() string { 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) } @@ -433,6 +436,9 @@ func (c *URL) AddParamAvoidNil(key string, value string) { 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) } @@ -440,7 +446,9 @@ func (c *URL) SetParam(key string, value string) { func (c *URL) DelParam(key string) { c.paramsLock.Lock() defer c.paramsLock.Unlock() - c.params.Del(key) + if c.params != nil { + c.params.Del(key) + } } // ReplaceParams will replace the URL.params @@ -466,10 +474,15 @@ func (c *URL) RangeParams(f func(key, value string) bool) { func (c *URL) GetParam(s string, d string) string { c.paramsLock.RLock() defer c.paramsLock.RUnlock() - r := c.params.Get(s) + + var r string + if len(c.params) > 0 { + r = c.params.Get(s) + } if len(r) == 0 { r = d } + return r } diff --git a/common/url_test.go b/common/url_test.go index 1f5c40937d3d4aee5e93133a82c8067c7a62de4c..4008f6a3d3ab7d4131cf767ccc835b69c248f0fe 100644 --- a/common/url_test.go +++ b/common/url_test.go @@ -70,9 +70,8 @@ func TestURL(t *testing.T) { urlInst := URL{} urlInst.noCopy.Lock() + urlInst.SetParam("hello", "world") urlInst.noCopy.Unlock() - urlInst.baseUrl.paramsLock.Lock() - urlInst.baseUrl.paramsLock.Unlock() assert.Equal(t, "/com.ikurento.user.UserProvider", u.Path) assert.Equal(t, "127.0.0.1:20000", u.Location) diff --git a/config/base_config.go b/config/base_config.go index 0cc6eec26c51cb7dfc164a3d43545f6b22658ca0..7cb25a50793b94f2ec2fd8c60e6b93a50b8e77ab 100644 --- a/config/base_config.go +++ b/config/base_config.go @@ -45,7 +45,7 @@ type BaseConfig struct { // application config ApplicationConfig *ApplicationConfig `yaml:"application" json:"application,omitempty" property:"application"` - prefix string + //prefix string fatherConfig interface{} EventDispatcherType string `default:"direct" yaml:"event_dispatcher_type" json:"event_dispatcher_type,omitempty"` MetricConfig *MetricConfig `yaml:"metrics" json:"metrics,omitempty"` diff --git a/config/base_config_test.go b/config/base_config_test.go index 9e5565fc115e45b6dd0e598bd4ff5a67394ebc99..566b49bea7df8a14543347a196d136a8c059a0b5 100644 --- a/config/base_config_test.go +++ b/config/base_config_test.go @@ -107,6 +107,7 @@ var baseMockRef = map[string]*ReferenceConfig{ func TestRefresh(t *testing.T) { c := &BaseConfig{} + c.fileStream = nil mockMap := getMockMap() mockMap["dubbo.shutdown.timeout"] = "12s" diff --git a/config/config_center_config.go b/config/config_center_config.go index 3bb856415d77344658055f03ccc4a6edd8c0f48a..940b7be951d83a041ebc8121e65a9bd2fd09594b 100644 --- a/config/config_center_config.go +++ b/config/config_center_config.go @@ -18,10 +18,8 @@ package config import ( - "context" "net/url" "reflect" - "time" ) import ( @@ -46,7 +44,7 @@ import ( // // ConfigCenter has currently supported Zookeeper, Nacos, Etcd, Consul, Apollo type ConfigCenterConfig struct { - context context.Context + //context context.Context Protocol string `required:"true" yaml:"protocol" json:"protocol,omitempty"` Address string `yaml:"address" json:"address,omitempty"` Cluster string `yaml:"cluster" json:"cluster,omitempty"` @@ -60,7 +58,7 @@ type ConfigCenterConfig struct { AppId string `default:"dubbo" yaml:"app_id" json:"app_id,omitempty"` TimeoutStr string `yaml:"timeout" json:"timeout,omitempty"` RemoteRef string `required:"false" yaml:"remote_ref" json:"remote_ref,omitempty"` - timeout time.Duration + //timeout time.Duration } // UnmarshalYAML unmarshals the ConfigCenterConfig by @unmarshal function diff --git a/config/config_loader.go b/config/config_loader.go index ec591aad6526e5841656465e71465413d01ad5ba..35910981d128bdca7d63973328e2752ecfef6933 100644 --- a/config/config_loader.go +++ b/config/config_loader.go @@ -406,9 +406,9 @@ func GetBaseConfig() *BaseConfig { baseConfig = &BaseConfig{ MetricConfig: &MetricConfig{}, ConfigCenterConfig: &ConfigCenterConfig{}, - Remotes: make(map[string]*RemoteConfig, 0), + Remotes: make(map[string]*RemoteConfig), ApplicationConfig: &ApplicationConfig{}, - ServiceDiscoveries: make(map[string]*ServiceDiscoveryConfig, 0), + ServiceDiscoveries: make(map[string]*ServiceDiscoveryConfig), } } } diff --git a/config_center/apollo/impl.go b/config_center/apollo/impl.go index c69fc2f66b23cd877b447fc78084fb9197c253aa..cb0f03d54a2ea180543ec528e3a46be45067179c 100644 --- a/config_center/apollo/impl.go +++ b/config_center/apollo/impl.go @@ -146,8 +146,7 @@ func (c *apolloConfiguration) getAddressWithProtocolPrefix(url *common.URL) stri address := url.Location converted := address if len(address) != 0 { - reg := regexp.MustCompile("\\s+") - address = reg.ReplaceAllString(address, "") + address := regexp.MustCompile(`\s+`).ReplaceAllString(address, "") parts := strings.Split(address, ",") addrs := make([]string, 0) for _, part := range parts { diff --git a/config_center/apollo/impl_test.go b/config_center/apollo/impl_test.go index 38ef0082fda5e741f091110bf3a09a4bcf6c0ff1..3b2cb168402534c1a8071e644827a0f948282f75 100644 --- a/config_center/apollo/impl_test.go +++ b/config_center/apollo/impl_test.go @@ -143,7 +143,7 @@ func serviceConfigResponse(rw http.ResponseWriter, _ *http.Request) { // run mock config server func runMockConfigServer(handlerMap map[string]func(http.ResponseWriter, *http.Request), notifyHandler func(http.ResponseWriter, *http.Request)) *httptest.Server { - uriHandlerMap := make(map[string]func(http.ResponseWriter, *http.Request), 0) + uriHandlerMap := make(map[string]func(http.ResponseWriter, *http.Request)) for namespace, handler := range handlerMap { uri := fmt.Sprintf("/configs/%s/%s/%s", mockAppId, mockCluster, namespace) uriHandlerMap[uri] = handler diff --git a/config_center/nacos/client.go b/config_center/nacos/client.go index c7d631c76fec07820d72a1f4065e51a018af0d29..1e96b36a4f19b8548d2ffc9818251ebfa96f365b 100644 --- a/config_center/nacos/client.go +++ b/config_center/nacos/client.go @@ -65,7 +65,7 @@ type option func(*options) type options struct { nacosName string - client *NacosClient + //client *NacosClient } // WithNacosName Set nacos name diff --git a/config_center/nacos/impl_test.go b/config_center/nacos/impl_test.go index 89917d14c2ed974c314c1d8a990fe2ac34a3fb0b..b7bd94bf96bfdafed1591e58f338fa23a0b96a6f 100644 --- a/config_center/nacos/impl_test.go +++ b/config_center/nacos/impl_test.go @@ -40,7 +40,7 @@ import ( // run mock config server func runMockConfigServer(configHandler func(http.ResponseWriter, *http.Request), configListenHandler func(http.ResponseWriter, *http.Request)) *httptest.Server { - uriHandlerMap := make(map[string]func(http.ResponseWriter, *http.Request), 0) + uriHandlerMap := make(map[string]func(http.ResponseWriter, *http.Request)) uriHandlerMap["/nacos/v1/cs/configs"] = configHandler uriHandlerMap["/nacos/v1/cs/configs/listener"] = configListenHandler diff --git a/config_center/zookeeper/impl.go b/config_center/zookeeper/impl.go index 17812e917f533d28c052c7cda3411de44b9aa7b5..f3b2235025c033cd125c9a87b2c277a5a3d70243 100644 --- a/config_center/zookeeper/impl.go +++ b/config_center/zookeeper/impl.go @@ -52,7 +52,7 @@ type zookeeperDynamicConfiguration struct { done chan struct{} client *zookeeper.ZookeeperClient - listenerLock sync.Mutex + //listenerLock sync.Mutex listener *zookeeper.ZkEventListener cacheListener *CacheListener parser parser.ConfigurationParser diff --git a/filter/filter_impl/active_filter_test.go b/filter/filter_impl/active_filter_test.go index 9f024fec34521b8445fa1a61295e4b3c0eb85e34..2397503dc8f46381a131bed6f924d465a71a9193 100644 --- a/filter/filter_impl/active_filter_test.go +++ b/filter/filter_impl/active_filter_test.go @@ -37,7 +37,7 @@ import ( ) func TestActiveFilterInvoke(t *testing.T) { - invoc := invocation.NewRPCInvocation("test", []interface{}{"OK"}, make(map[string]interface{}, 0)) + invoc := invocation.NewRPCInvocation("test", []interface{}{"OK"}, make(map[string]interface{})) url, _ := common.NewURL("dubbo://192.168.10.10:20000/com.ikurento.user.UserProvider") filter := ActiveFilter{} ctrl := gomock.NewController(t) diff --git a/filter/filter_impl/auth/sign_util.go b/filter/filter_impl/auth/sign_util.go index cb185376cb211fc415c6862c2aad19e5e3ba0cfa..4c12c762ed6715af551f6e37c251cf095bb43dc4 100644 --- a/filter/filter_impl/auth/sign_util.go +++ b/filter/filter_impl/auth/sign_util.go @@ -37,7 +37,7 @@ func Sign(metadata, key string) string { // SignWithParams returns a signature with giving params and metadata. func SignWithParams(params []interface{}, metadata, key string) (string, error) { - if params == nil || len(params) == 0 { + if len(params) == 0 { return Sign(metadata, key), nil } diff --git a/filter/filter_impl/execute_limit_filter_test.go b/filter/filter_impl/execute_limit_filter_test.go index 2aebcaa8fa62278da3092d6359d2a01571be37d0..682f8fa8b475348624a33d44d9a08190fe270fa8 100644 --- a/filter/filter_impl/execute_limit_filter_test.go +++ b/filter/filter_impl/execute_limit_filter_test.go @@ -36,7 +36,7 @@ import ( func TestExecuteLimitFilterInvokeIgnored(t *testing.T) { methodName := "hello" - invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]interface{}, 0)) + invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]interface{})) invokeUrl := common.NewURLWithOptions( common.WithParams(url.Values{}), @@ -51,7 +51,7 @@ func TestExecuteLimitFilterInvokeIgnored(t *testing.T) { func TestExecuteLimitFilterInvokeConfigureError(t *testing.T) { methodName := "hello1" - invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]interface{}, 0)) + invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]interface{})) invokeUrl := common.NewURLWithOptions( common.WithParams(url.Values{}), @@ -68,7 +68,7 @@ func TestExecuteLimitFilterInvokeConfigureError(t *testing.T) { func TestExecuteLimitFilterInvoke(t *testing.T) { methodName := "hello1" - invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]interface{}, 0)) + invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]interface{})) invokeUrl := common.NewURLWithOptions( common.WithParams(url.Values{}), diff --git a/filter/filter_impl/graceful_shutdown_filter_test.go b/filter/filter_impl/graceful_shutdown_filter_test.go index c2c1ef874d1696217b34b50fbbf66aa8faf7803d..b16956e01c85b52ec0009f96998a72e2a4314911 100644 --- a/filter/filter_impl/graceful_shutdown_filter_test.go +++ b/filter/filter_impl/graceful_shutdown_filter_test.go @@ -39,10 +39,8 @@ import ( ) func TestGenericFilterInvoke(t *testing.T) { - invoc := invocation.NewRPCInvocation("GetUser", []interface{}{"OK"}, make(map[string]interface{}, 0)) - - invokeUrl := common.NewURLWithOptions( - common.WithParams(url.Values{})) + invoc := invocation.NewRPCInvocation("GetUser", []interface{}{"OK"}, make(map[string]interface{})) + invokeUrl := common.NewURLWithOptions(common.WithParams(url.Values{})) shutdownFilter := extension.GetFilter(constant.PROVIDER_SHUTDOWN_FILTER).(*gracefulShutdownFilter) diff --git a/filter/filter_impl/seata_filter.go b/filter/filter_impl/seata_filter.go index 7722d2954f905ece4a1b48628c31c06debf45614..b7b7b0e94b4633dda10278e9674566a82701b7f6 100644 --- a/filter/filter_impl/seata_filter.go +++ b/filter/filter_impl/seata_filter.go @@ -23,6 +23,7 @@ import ( ) import ( + "github.com/apache/dubbo-go/common/constant" "github.com/apache/dubbo-go/common/extension" "github.com/apache/dubbo-go/common/logger" "github.com/apache/dubbo-go/filter" @@ -30,12 +31,12 @@ import ( ) const ( - SEATA = "seata" - SEATA_XID = "SEATA_XID" + SEATA = constant.DubboCtxKey("seata") + SEATA_XID = constant.DubboCtxKey("SEATA_XID") ) func init() { - extension.SetFilter(SEATA, getSeataFilter) + extension.SetFilter(string(SEATA), getSeataFilter) } // SeataFilter when use seata-golang, use this filter to transfer xid @@ -45,7 +46,7 @@ type SeataFilter struct{} // Invoke Get Xid by attachment key `SEATA_XID` func (sf *SeataFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result { logger.Infof("invoking seata filter.") - xid := invocation.AttachmentsByKey(SEATA_XID, "") + xid := invocation.AttachmentsByKey(string(SEATA_XID), "") if strings.TrimSpace(xid) != "" { logger.Debugf("Method: %v,Xid: %v", invocation.MethodName(), xid) return invoker.Invoke(context.WithValue(ctx, SEATA_XID, xid), invocation) diff --git a/filter/filter_impl/seata_filter_test.go b/filter/filter_impl/seata_filter_test.go index 45817e95cbd2eaa7365adc8a299523af8310f797..1705eba787f5569064841d6a713ed2f2e428314c 100644 --- a/filter/filter_impl/seata_filter_test.go +++ b/filter/filter_impl/seata_filter_test.go @@ -50,7 +50,7 @@ func TestSeataFilter_Invoke(t *testing.T) { filter := getSeataFilter() result := filter.Invoke(context.Background(), &testMockSeataInvoker{}, invocation.NewRPCInvocation("$echo", []interface{}{"OK"}, map[string]interface{}{ - SEATA_XID: "10.30.21.227:8091:2000047792", + string(SEATA_XID): "10.30.21.227:8091:2000047792", })) assert.Equal(t, "10.30.21.227:8091:2000047792", result.Result()) } diff --git a/filter/filter_impl/sentinel_filter.go b/filter/filter_impl/sentinel_filter.go index b5f8b45876717551cecd3639579a07a825a74d40..f662db35637593f4ab92a2b12e50d5a9e4305730 100644 --- a/filter/filter_impl/sentinel_filter.go +++ b/filter/filter_impl/sentinel_filter.go @@ -204,8 +204,8 @@ const ( DefaultProviderPrefix = "dubbo:provider:" DefaultConsumerPrefix = "dubbo:consumer:" - MethodEntryKey = "$$sentinelMethodEntry" - InterfaceEntryKey = "$$sentinelInterfaceEntry" + MethodEntryKey = constant.DubboCtxKey("$$sentinelMethodEntry") + InterfaceEntryKey = constant.DubboCtxKey("$$sentinelInterfaceEntry") ) func getResourceName(invoker protocol.Invoker, invocation protocol.Invocation, prefix string) (interfaceResourceName, methodResourceName string) { diff --git a/filter/filter_impl/token_filter_test.go b/filter/filter_impl/token_filter_test.go index 9ef8c98d6868c3d545fe963ab13eb3f27bb88cd0..024ae2ae3142b1e193d6a24001f51f00badf537a 100644 --- a/filter/filter_impl/token_filter_test.go +++ b/filter/filter_impl/token_filter_test.go @@ -40,7 +40,7 @@ func TestTokenFilterInvoke(t *testing.T) { url := common.NewURLWithOptions( common.WithParams(url.Values{}), common.WithParamsValue(constant.TOKEN_KEY, "ori_key")) - attch := make(map[string]interface{}, 0) + attch := make(map[string]interface{}) attch[constant.TOKEN_KEY] = "ori_key" result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(url), @@ -54,7 +54,7 @@ func TestTokenFilterInvokeEmptyToken(t *testing.T) { filter := GetTokenFilter() testUrl := common.URL{} - attch := make(map[string]interface{}, 0) + attch := make(map[string]interface{}) attch[constant.TOKEN_KEY] = "ori_key" result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(&testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) assert.Nil(t, result.Error()) @@ -67,7 +67,7 @@ func TestTokenFilterInvokeEmptyAttach(t *testing.T) { testUrl := common.NewURLWithOptions( common.WithParams(url.Values{}), common.WithParamsValue(constant.TOKEN_KEY, "ori_key")) - attch := make(map[string]interface{}, 0) + attch := make(map[string]interface{}) result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) assert.NotNil(t, result.Error()) } @@ -78,7 +78,7 @@ func TestTokenFilterInvokeNotEqual(t *testing.T) { testUrl := common.NewURLWithOptions( common.WithParams(url.Values{}), common.WithParamsValue(constant.TOKEN_KEY, "ori_key")) - attch := make(map[string]interface{}, 0) + attch := make(map[string]interface{}) attch[constant.TOKEN_KEY] = "err_key" result := filter.Invoke(context.Background(), protocol.NewBaseInvoker(testUrl), invocation.NewRPCInvocation("MethodName", []interface{}{"OK"}, attch)) diff --git a/filter/filter_impl/tps/tps_limiter_method_service_test.go b/filter/filter_impl/tps/tps_limiter_method_service_test.go index 7435d9b92ac8270de0244c8a257aec82f9acc9a1..a70287eabd8dc362c4f2acc970eb9eea32ed5e2a 100644 --- a/filter/filter_impl/tps/tps_limiter_method_service_test.go +++ b/filter/filter_impl/tps/tps_limiter_method_service_test.go @@ -36,7 +36,7 @@ import ( func TestMethodServiceTpsLimiterImplIsAllowableOnlyServiceLevel(t *testing.T) { methodName := "hello" - invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]interface{}, 0)) + invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]interface{})) ctrl := gomock.NewController(t) defer ctrl.Finish() @@ -63,7 +63,7 @@ func TestMethodServiceTpsLimiterImplIsAllowableOnlyServiceLevel(t *testing.T) { func TestMethodServiceTpsLimiterImplIsAllowableNoConfig(t *testing.T) { methodName := "hello1" - invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]interface{}, 0)) + invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]interface{})) // ctrl := gomock.NewController(t) // defer ctrl.Finish() @@ -80,7 +80,7 @@ func TestMethodServiceTpsLimiterImplIsAllowableNoConfig(t *testing.T) { func TestMethodServiceTpsLimiterImplIsAllowableMethodLevelOverride(t *testing.T) { methodName := "hello2" methodConfigPrefix := "methods." + methodName + "." - invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]interface{}, 0)) + invoc := invocation.NewRPCInvocation(methodName, []interface{}{"OK"}, make(map[string]interface{})) ctrl := gomock.NewController(t) defer ctrl.Finish() diff --git a/filter/filter_impl/tps_limit_filter_test.go b/filter/filter_impl/tps_limit_filter_test.go index 88e778105081129463b68618804bd9204d2f7113..55a3a55fab28efc7c27d9f5ccc4a3ec454bb6d15 100644 --- a/filter/filter_impl/tps_limit_filter_test.go +++ b/filter/filter_impl/tps_limit_filter_test.go @@ -44,7 +44,7 @@ func TestTpsLimitFilterInvokeWithNoTpsLimiter(t *testing.T) { invokeUrl := common.NewURLWithOptions( common.WithParams(url.Values{}), common.WithParamsValue(constant.TPS_LIMITER_KEY, "")) - attch := make(map[string]interface{}, 0) + attch := make(map[string]interface{}) result := tpsFilter.Invoke(context.Background(), protocol.NewBaseInvoker(invokeUrl), @@ -68,7 +68,7 @@ func TestGenericFilterInvokeWithDefaultTpsLimiter(t *testing.T) { invokeUrl := common.NewURLWithOptions( common.WithParams(url.Values{}), common.WithParamsValue(constant.TPS_LIMITER_KEY, constant.DEFAULT_KEY)) - attch := make(map[string]interface{}, 0) + attch := make(map[string]interface{}) result := tpsFilter.Invoke(context.Background(), protocol.NewBaseInvoker(invokeUrl), @@ -99,7 +99,7 @@ func TestGenericFilterInvokeWithDefaultTpsLimiterNotAllow(t *testing.T) { invokeUrl := common.NewURLWithOptions( common.WithParams(url.Values{}), common.WithParamsValue(constant.TPS_LIMITER_KEY, constant.DEFAULT_KEY)) - attch := make(map[string]interface{}, 0) + attch := make(map[string]interface{}) result := tpsFilter.Invoke(context.Background(), protocol.NewBaseInvoker( diff --git a/filter/filter_impl/tracing_filter_test.go b/filter/filter_impl/tracing_filter_test.go index e159b7400d46069018a00a849319423285072dc2..bf96a7d064b3919825d26c505b637f5ea539d9d6 100644 --- a/filter/filter_impl/tracing_filter_test.go +++ b/filter/filter_impl/tracing_filter_test.go @@ -57,6 +57,6 @@ func TestTracingFilterInvoke(t *testing.T) { tf.Invoke(ctx, invoker, inv) // has remote ctx - ctx = context.WithValue(context.Background(), constant.TRACING_REMOTE_SPAN_CTX, span.Context()) + ctx = context.WithValue(context.Background(), constant.DubboCtxKey(constant.TRACING_REMOTE_SPAN_CTX), span.Context()) tf.Invoke(ctx, invoker, inv) } diff --git a/metadata/mapping/dynamic/service_name_mapping_test.go b/metadata/mapping/dynamic/service_name_mapping_test.go index 2896b0fd4aa4fb6bada132c276c70a1653e59f99..af21704b69c674a2cd1b8963bb252ac73c0abf1e 100644 --- a/metadata/mapping/dynamic/service_name_mapping_test.go +++ b/metadata/mapping/dynamic/service_name_mapping_test.go @@ -39,6 +39,7 @@ func TestDynamicConfigurationServiceNameMapping(t *testing.T) { dc, err := (&config_center.MockDynamicConfigurationFactory{ Content: appName, }).GetDynamicConfiguration(nil) + assert.NoError(t, err) config.GetApplicationConfig().Name = appName mapping := &DynamicConfigurationServiceNameMapping{dc: dc} diff --git a/metadata/report/delegate/delegate_report_test.go b/metadata/report/delegate/delegate_report_test.go index 9c30ed9ffdb8424be38d273fd0a78f3351d6e0d5..f60acf6e117c866cba716c538806f278d77363f0 100644 --- a/metadata/report/delegate/delegate_report_test.go +++ b/metadata/report/delegate/delegate_report_test.go @@ -46,13 +46,10 @@ func TestMetadataReport_MetadataReportRetry(t *testing.T) { }) assert.NoError(t, err) retry.startRetryTask() - itsTime := time.After(2500 * time.Millisecond) - select { - case <-itsTime: - retry.scheduler.Clear() - assert.Equal(t, counter.Load(), int64(3)) - logger.Info("over") - } + <-time.After(2500 * time.Millisecond) + retry.scheduler.Clear() + assert.Equal(t, counter.Load(), int64(3)) + logger.Info("over") } func TestMetadataReport_MetadataReportRetryWithLimit(t *testing.T) { @@ -64,13 +61,10 @@ func TestMetadataReport_MetadataReportRetryWithLimit(t *testing.T) { }) assert.NoError(t, err) retry.startRetryTask() - itsTime := time.After(2500 * time.Millisecond) - select { - case <-itsTime: - retry.scheduler.Clear() - assert.Equal(t, counter.Load(), int64(2)) - logger.Info("over") - } + <-time.After(2500 * time.Millisecond) + retry.scheduler.Clear() + assert.Equal(t, counter.Load(), int64(2)) + logger.Info("over") } func mockNewMetadataReport(t *testing.T) *MetadataReport { diff --git a/metadata/service/inmemory/service_proxy.go b/metadata/service/inmemory/service_proxy.go index 7e14293a6766492c1c1b02eef9429d1adeb539ae..8b93aab9accfd8375ded971c27f898069e73e231 100644 --- a/metadata/service/inmemory/service_proxy.go +++ b/metadata/service/inmemory/service_proxy.go @@ -39,8 +39,8 @@ import ( // this is the stub, or proxy // for now, only GetExportedURLs need to be implemented type MetadataServiceProxy struct { - invkr protocol.Invoker - golangServer bool + invkr protocol.Invoker + //golangServer bool } func (m *MetadataServiceProxy) GetExportedURLs(serviceInterface string, group string, version string, protocol string) ([]interface{}, error) { @@ -67,11 +67,7 @@ func (m *MetadataServiceProxy) GetExportedURLs(serviceInterface string, group st urlStrs := res.Result().(*[]interface{}) ret := make([]interface{}, 0, len(*urlStrs)) - - for _, s := range *urlStrs { - ret = append(ret, s) - } - return ret, nil + return append(ret, *urlStrs...), nil } func (m *MetadataServiceProxy) MethodMapper() map[string]string { diff --git a/metadata/service/remote/service.go b/metadata/service/remote/service.go index ae1c344d27a0c5be08739ab05f0c909bcc2b8fdb..d21cc88a3d31ec2920a78c608ed13a491fd6c634 100644 --- a/metadata/service/remote/service.go +++ b/metadata/service/remote/service.go @@ -188,7 +188,7 @@ func (mts *MetadataService) RefreshMetadata(exportedRevision string, subscribedR logger.Errorf("Error occur when execute remote.MetadataService.RefreshMetadata, error message is %v+", err) return false, err } - if urls != nil && len(urls) > 0 { + if len(urls) > 0 { id := &identifier.SubscriberMetadataIdentifier{ MetadataIdentifier: identifier.MetadataIdentifier{ Application: config.GetApplicationConfig().Name, diff --git a/metadata/service/remote/service_proxy.go b/metadata/service/remote/service_proxy.go index 3199aa6dfff6f5e8b6036c44f452d16480b0380c..d0caa182b2efdc709af11e4bc40f807e89276a56 100644 --- a/metadata/service/remote/service_proxy.go +++ b/metadata/service/remote/service_proxy.go @@ -146,7 +146,7 @@ func newMetadataServiceProxy(ins registry.ServiceInstance) service.MetadataServi } func parse(key string) []string { - arr := make([]string, 3, 3) + arr := make([]string, 3) tmp := strings.SplitN(key, "/", 2) if len(tmp) > 1 { arr[0] = tmp[0] diff --git a/metadata/service/remote/service_test.go b/metadata/service/remote/service_test.go index 71586cc1dcc87dc8644a25c9a89842bd84fe9f0a..d6028152ccb275238491accc055e67d0b903bc55 100644 --- a/metadata/service/remote/service_test.go +++ b/metadata/service/remote/service_test.go @@ -95,7 +95,7 @@ func (metadataReport) GetServiceDefinition(*identifier.MetadataIdentifier) (stri func TestMetadataService(t *testing.T) { extension.SetMetadataReportFactory("mock", getMetadataReportFactory) - u, err := common.NewURL(fmt.Sprintf("mock://127.0.0.1:20000/?sync.report=true")) + u, err := common.NewURL("mock://127.0.0.1:20000/?sync.report=true") assert.NoError(t, err) instance.GetMetadataReportInstance(u) mts, err := newMetadataService() diff --git a/protocol/dubbo/dubbo_codec.go b/protocol/dubbo/dubbo_codec.go index ccecbee2e2b04083cbda3118978da0f7450b4d3f..f92da4aa7f164fce131f9f869f9550b6e7168943 100644 --- a/protocol/dubbo/dubbo_codec.go +++ b/protocol/dubbo/dubbo_codec.go @@ -177,10 +177,7 @@ func (c *DubboCodec) Decode(data []byte) (remoting.DecodeResult, int, error) { } func (c *DubboCodec) isRequest(data []byte) bool { - if data[2]&byte(0x80) == 0x00 { - return false - } - return true + return data[2]&byte(0x80) != 0x00 } // decode request diff --git a/protocol/dubbo/dubbo_invoker_test.go b/protocol/dubbo/dubbo_invoker_test.go index c7a9a2697529d096e57585347b0a8b0a535451b0..fecb3b01ab286d4900cba4628cb80ea6d9920a9a 100644 --- a/protocol/dubbo/dubbo_invoker_test.go +++ b/protocol/dubbo/dubbo_invoker_test.go @@ -169,7 +169,7 @@ type ( } UserProvider struct { - user map[string]User + //user map[string]User } ) diff --git a/protocol/dubbo/dubbo_protocol.go b/protocol/dubbo/dubbo_protocol.go index 4f03b8aba061ea9b37b35d89142eb7bec80f3a97..1f7cd50187d14252ec7e4b2f5c78e8b5bd9228e2 100644 --- a/protocol/dubbo/dubbo_protocol.go +++ b/protocol/dubbo/dubbo_protocol.go @@ -222,13 +222,13 @@ func getExchangeClient(url *common.URL) *remoting.ExchangeClient { // Once we decided to transfer more context's key-value, we should change this. // now we only support rebuild the tracing context func rebuildCtx(inv *invocation.RPCInvocation) context.Context { - ctx := context.WithValue(context.Background(), "attachment", inv.Attachments()) + ctx := context.WithValue(context.Background(), constant.DubboCtxKey("attachment"), inv.Attachments()) // actually, if user do not use any opentracing framework, the err will not be nil. spanCtx, err := opentracing.GlobalTracer().Extract(opentracing.TextMap, opentracing.TextMapCarrier(filterContext(inv.Attachments()))) if err == nil { - ctx = context.WithValue(ctx, constant.TRACING_REMOTE_SPAN_CTX, spanCtx) + ctx = context.WithValue(ctx, constant.DubboCtxKey(constant.TRACING_REMOTE_SPAN_CTX), spanCtx) } return ctx } diff --git a/protocol/dubbo/hessian2/hessian_request.go b/protocol/dubbo/hessian2/hessian_request.go index 586476fdc6efe07a29185fc219ba1b4efc64c4c0..efcbd95d293fa84e8dfd6eddd9fdc14f05c3e6a2 100644 --- a/protocol/dubbo/hessian2/hessian_request.go +++ b/protocol/dubbo/hessian2/hessian_request.go @@ -43,7 +43,7 @@ func getArgType(v interface{}) string { return "V" } - switch v.(type) { + switch v := v.(type) { // Serialized tags for base types case nil: return "V" diff --git a/protocol/dubbo/impl/hessian.go b/protocol/dubbo/impl/hessian.go index c4efb97e4b75ea8e81218ceb8dfe4aa65c5d810b..e355276c37f9d1babc12f7e3b694ec7a193aed80 100644 --- a/protocol/dubbo/impl/hessian.go +++ b/protocol/dubbo/impl/hessian.go @@ -417,7 +417,7 @@ func getArgType(v interface{}) string { return "V" } - switch v.(type) { + switch v := v.(type) { // Serialized tags for base types case nil: return "V" diff --git a/protocol/grpc/protoc-gen-dubbo/plugin/dubbo/dubbo.go b/protocol/grpc/protoc-gen-dubbo/plugin/dubbo/dubbo.go index 78847282d5ff6c36a4fc15dee1f7bf16e8e9b8b3..ba84f36b74016f1495fa7d616315deda7c54bbcc 100644 --- a/protocol/grpc/protoc-gen-dubbo/plugin/dubbo/dubbo.go +++ b/protocol/grpc/protoc-gen-dubbo/plugin/dubbo/dubbo.go @@ -254,8 +254,8 @@ func (g *dubboGrpc) generateClientSignature(servName string, method *pb.MethodDe return fmt.Sprintf("%s func(ctx %s.Context%s, %s) error", methName, contextPkg, reqArg, respName) } -func (g *dubboGrpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) { -} +//func (g *dubboGrpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) { +//} func (g *dubboGrpc) generateServerMethod(servName, fullServName string, method *pb.MethodDescriptorProto) string { methName := generator.CamelCase(method.GetName()) diff --git a/protocol/jsonrpc/http.go b/protocol/jsonrpc/http.go index 7ab1a8942da62deba17df991c019fc4f71a69366..037744cf09c4aa229fd7d5f0a7444fd86e70f06f 100644 --- a/protocol/jsonrpc/http.go +++ b/protocol/jsonrpc/http.go @@ -49,14 +49,14 @@ import ( // Request is HTTP protocol request type Request struct { - ID int64 - group string - protocol string - version string - service string - method string - args interface{} - contentType string + ID int64 + group string + protocol string + version string + service string + method string + args interface{} + //contentType string } // //////////////////////////////////////////// diff --git a/protocol/jsonrpc/http_test.go b/protocol/jsonrpc/http_test.go index c4801c8db883353c82762162a7b658f964fc6ffa..5ef40649b1fcb209f29d9bbe871e47b1fcda8a59 100644 --- a/protocol/jsonrpc/http_test.go +++ b/protocol/jsonrpc/http_test.go @@ -44,7 +44,7 @@ type ( } UserProvider struct { - user map[string]User + //user map[string]User } ) diff --git a/protocol/protocolwrapper/mock_protocol_filter.go b/protocol/protocolwrapper/mock_protocol_filter.go index 18a4e1562107939e9c72090778422e0d8bb56a60..d1baba813416ff688c5f9ccccf05e276c55c2bba 100644 --- a/protocol/protocolwrapper/mock_protocol_filter.go +++ b/protocol/protocolwrapper/mock_protocol_filter.go @@ -45,5 +45,4 @@ func (pfw *mockProtocolFilter) Refer(url *common.URL) protocol.Invoker { // Destroy will do nothing func (pfw *mockProtocolFilter) Destroy() { - return } diff --git a/registry/base_registry.go b/registry/base_registry.go index ee0d340387a0d270d8254f5038db312977f1f001..e97cc1a4ed6c85fa464d3398b4706e99f7a7f535 100644 --- a/registry/base_registry.go +++ b/registry/base_registry.go @@ -18,7 +18,6 @@ package registry import ( - "context" "fmt" "net/url" "os" @@ -93,7 +92,7 @@ type FacadeBasedRegistry interface { // BaseRegistry is a common logic abstract for registry. It implement Registry interface. type BaseRegistry struct { - context context.Context + //context context.Context facadeBasedRegistry FacadeBasedRegistry *common.URL birth int64 // time of file birth, seconds since Epoch; 0 if unknown diff --git a/registry/consul/service_discovery.go b/registry/consul/service_discovery.go index a64fabb1b9edc9cd196c4d25f6659c499bca064b..6674909b15afc225515ff080fb341da65c17a05f 100644 --- a/registry/consul/service_discovery.go +++ b/registry/consul/service_discovery.go @@ -252,7 +252,7 @@ func (csd *consulServiceDiscovery) GetServices() *gxset.HashSet { return res } - for service, _ := range services { + for service := range services { res.Add(service) } return res diff --git a/registry/consul/service_discovery_test.go b/registry/consul/service_discovery_test.go index 348790cb120e63ce496d88e472269b390e5c46a7..3f97d841d56111746f396ba753142324ac4555d2 100644 --- a/registry/consul/service_discovery_test.go +++ b/registry/consul/service_discovery_test.go @@ -141,7 +141,8 @@ func TestConsulServiceDiscovery_CRUD(t *testing.T) { assert.Equal(t, 1, len(page.GetData())) instanceResult = page.GetData()[0].(*registry.DefaultServiceInstance) - v, _ := instanceResult.Metadata["aaa"] + v, ok := instanceResult.Metadata["aaa"] + assert.True(t, ok) assert.Equal(t, "bbb", v) // test dispatcher event diff --git a/registry/directory/directory.go b/registry/directory/directory.go index f55bd4abfdcd764cf908cae92564ca1d61229331..1b607351af0b527f9ace4fa77268e100aa8fa2dc 100644 --- a/registry/directory/directory.go +++ b/registry/directory/directory.go @@ -26,7 +26,6 @@ import ( import ( perrors "github.com/pkg/errors" - "go.uber.org/atomic" ) import ( @@ -64,9 +63,9 @@ type RegistryDirectory struct { configurators []config_center.Configurator consumerConfigurationListener *consumerConfigurationListener referenceConfigurationListener *referenceConfigurationListener - serviceKey string - forbidden atomic.Bool - registerLock sync.Mutex // this lock if for register + //serviceKey string + //forbidden atomic.Bool + registerLock sync.Mutex // this lock if for register } // NewRegistryDirectory will create a new RegistryDirectory @@ -154,7 +153,6 @@ func (dir *RegistryDirectory) refreshAllInvokers(events []*registry.ServiceEvent if event.Action != remoting.EventTypeUpdate { panic("Your implements of register center is wrong, " + "please check the Action of ServiceEvent should be EventTypeUpdate") - return } // Originally it will Merge URL many times, now we just execute once. // MergeUrl is executed once and put the result into Event. After this, the key will get from Event.Key(). @@ -297,11 +295,7 @@ func (dir *RegistryDirectory) toGroupInvokers() []protocol.Invoker { for _, invoker := range newInvokersList { group := invoker.GetUrl().GetParam(constant.GROUP_KEY, "") - if _, ok := groupInvokersMap[group]; ok { - groupInvokersMap[group] = append(groupInvokersMap[group], invoker) - } else { - groupInvokersMap[group] = []protocol.Invoker{invoker} - } + groupInvokersMap[group] = append(groupInvokersMap[group], invoker) } groupInvokersList := make([]protocol.Invoker, 0, len(groupInvokersMap)) if len(groupInvokersMap) == 1 { diff --git a/registry/etcdv3/service_discovery.go b/registry/etcdv3/service_discovery.go index 4d5b8781b5a654632cb3416033eab9ed139cad0b..b9d8b5f895cf8257fa75da87c5548c7a8bdad3b9 100644 --- a/registry/etcdv3/service_discovery.go +++ b/registry/etcdv3/service_discovery.go @@ -165,7 +165,7 @@ func (e *etcdV3ServiceDiscovery) GetInstances(serviceName string) []registry.Ser logger.Infof("could not getChildrenKVList the err is:%v", err) } - return make([]registry.ServiceInstance, 0, 0) + return make([]registry.ServiceInstance, 0) } // GetInstancesByPage will return a page containing instances of ServiceInstance with the serviceName @@ -322,5 +322,5 @@ func newEtcdV3ServiceDiscovery(name string) (registry.ServiceDiscovery, error) { descriptor := fmt.Sprintf("etcd-service-discovery[%s]", remoteConfig.Address) - return &etcdV3ServiceDiscovery{descriptor, client, nil, gxset.NewSet(), make(map[string]*etcdv3.EventListener, 0)}, nil + return &etcdV3ServiceDiscovery{descriptor, client, nil, gxset.NewSet(), make(map[string]*etcdv3.EventListener)}, nil } diff --git a/registry/file/service_discovery.go b/registry/file/service_discovery.go index d19d1f310ca94f66c3178b9733cc93836b6dae6e..21482d329e0e252a4af612e872c4153a5afdd25c 100644 --- a/registry/file/service_discovery.go +++ b/registry/file/service_discovery.go @@ -212,7 +212,7 @@ func (fssd *fileSystemServiceDiscovery) GetInstances(serviceName string) []regis if err != nil { logger.Errorf("[FileServiceDiscovery] Could not query the instances for service{%s}, error = err{%v} ", serviceName, err) - return make([]registry.ServiceInstance, 0, 0) + return make([]registry.ServiceInstance, 0) } res := make([]registry.ServiceInstance, 0, set.Size()) @@ -223,7 +223,7 @@ func (fssd *fileSystemServiceDiscovery) GetInstances(serviceName string) []regis logger.Errorf("[FileServiceDiscovery] Could not get the properties for id{%s}, service{%s}, "+ "error = err{%v} ", id, serviceName, err) - return make([]registry.ServiceInstance, 0, 0) + return make([]registry.ServiceInstance, 0) } dsi := ®istry.DefaultServiceInstance{} @@ -232,7 +232,7 @@ func (fssd *fileSystemServiceDiscovery) GetInstances(serviceName string) []regis logger.Errorf("[FileServiceDiscovery] Could not unmarshal the properties for id{%s}, service{%s}, "+ "error = err{%v} ", id, serviceName, err) - return make([]registry.ServiceInstance, 0, 0) + return make([]registry.ServiceInstance, 0) } res = append(res, dsi) diff --git a/registry/kubernetes/registry.go b/registry/kubernetes/registry.go index c1e559e48dcc64972c9405e15405d7e6febcc845..55be4c392abcc14557c60af15b92bc84855b4b31 100644 --- a/registry/kubernetes/registry.go +++ b/registry/kubernetes/registry.go @@ -19,7 +19,6 @@ package kubernetes import ( "fmt" - "os" "path" "sync" "time" @@ -40,10 +39,10 @@ import ( "github.com/apache/dubbo-go/remoting/kubernetes" ) -var ( - processID = "" - localIP = "" -) +//var ( +// processID = "" +// localIP = "" +//) const ( Name = "kubernetes" @@ -52,8 +51,8 @@ const ( ) func init() { - processID = fmt.Sprintf("%d", os.Getpid()) - localIP = common.GetLocalIp() + //processID = fmt.Sprintf("%d", os.Getpid()) + //localIP = common.GetLocalIp() extension.SetRegistry(Name, newKubernetesRegistry) } diff --git a/registry/mock_registry.go b/registry/mock_registry.go index 7c269c3a4044079d19c7c41b53a9ae04b9eab86b..6287bb0d168f18f166618b7c6505b2f8b012be04 100644 --- a/registry/mock_registry.go +++ b/registry/mock_registry.go @@ -137,10 +137,7 @@ type listener struct { } func (l *listener) Next() (*ServiceEvent, error) { - select { - case e := <-l.listenChan: - return e, nil - } + return <-l.listenChan, nil } func (*listener) Close() { diff --git a/registry/nacos/service_discovery.go b/registry/nacos/service_discovery.go index b38e150e51075ce47ee38c9c8c9c7280e4437c53..9a2e1f11729d33e6b22bcd2514d97ac5adc29888 100644 --- a/registry/nacos/service_discovery.go +++ b/registry/nacos/service_discovery.go @@ -143,7 +143,7 @@ func (n *nacosServiceDiscovery) GetInstances(serviceName string) []registry.Serv if err != nil { logger.Errorf("Could not query the instances for service: %+v, group: %+v . It happened err %+v", serviceName, n.group, err) - return make([]registry.ServiceInstance, 0, 0) + return make([]registry.ServiceInstance, 0) } res := make([]registry.ServiceInstance, 0, len(instances)) for _, ins := range instances { diff --git a/registry/nacos/service_discovery_test.go b/registry/nacos/service_discovery_test.go index 3b09136d2e273090bea339e0a15b25dde719b6ac..2af1d5b6f564b5389574cc9107ef912cd506db8a 100644 --- a/registry/nacos/service_discovery_test.go +++ b/registry/nacos/service_discovery_test.go @@ -151,7 +151,8 @@ func TestNacosServiceDiscovery_CRUD(t *testing.T) { assert.Equal(t, 1, len(page.GetData())) instance = page.GetData()[0].(*registry.DefaultServiceInstance) - v, _ := instance.Metadata["a"] + v, ok := instance.Metadata["a"] + assert.True(t, ok) assert.Equal(t, "b", v) // test dispatcher event diff --git a/registry/service_instance.go b/registry/service_instance.go index dbb458284d48aa350f2d5d3408b187b437ac81cd..43a1640eead7be1774556f25c9b8f97a75588801 100644 --- a/registry/service_instance.go +++ b/registry/service_instance.go @@ -91,7 +91,7 @@ func (d *DefaultServiceInstance) IsHealthy() bool { // GetMetadata will return the metadata, it will never return nil func (d *DefaultServiceInstance) GetMetadata() map[string]string { if d.Metadata == nil { - d.Metadata = make(map[string]string, 0) + d.Metadata = make(map[string]string) } return d.Metadata } diff --git a/registry/servicediscovery/service_discovery_registry.go b/registry/servicediscovery/service_discovery_registry.go index ad6ec981ded9e224cecc0fa37c8e7f8c0254a932..2ca4b8015bc8dbc51a47a46c1bec0301ac961339 100644 --- a/registry/servicediscovery/service_discovery_registry.go +++ b/registry/servicediscovery/service_discovery_registry.go @@ -462,7 +462,7 @@ func (s *serviceDiscoveryRegistry) initRevisionExportedURLsByInst(serviceInstanc } revisionExportedURLs := revisionExportedURLsMap[revision] firstGet := false - if revisionExportedURLs == nil || len(revisionExportedURLs) == 0 { + if len(revisionExportedURLs) == 0 { if len(revisionExportedURLsMap) > 0 { // The case is that current ServiceInstance with the different revision logger.Warnf("The ServiceInstance[id: %s, host : %s , port : %s] has different revision : %s"+ diff --git a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go index d1ab6113b31a779529cc7e33ffd0f14233dd9ad6..c6b3aeaad09ebfa01d832a92478b7638a6cff432 100644 --- a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go +++ b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go @@ -38,14 +38,11 @@ type RestSubscribedURLsSynthesizer struct { } func (r RestSubscribedURLsSynthesizer) Support(subscribedURL *common.URL) bool { - if "rest" == subscribedURL.Protocol { - return true - } - return false + return "rest" == subscribedURL.Protocol } func (r RestSubscribedURLsSynthesizer) Synthesize(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []*common.URL { - urls := make([]*common.URL, len(serviceInstances), len(serviceInstances)) + urls := make([]*common.URL, len(serviceInstances)) for i, s := range serviceInstances { splitHost := strings.Split(s.GetHost(), ":") u := common.NewURLWithOptions(common.WithProtocol(subscribedURL.Protocol), common.WithIp(splitHost[0]), diff --git a/registry/zookeeper/registry.go b/registry/zookeeper/registry.go index fe492c2b12712e0935ccd6fdd264e0fe8f24e213..8b61e8092ce5b0d8081095555ed49734db9a48b4 100644 --- a/registry/zookeeper/registry.go +++ b/registry/zookeeper/registry.go @@ -129,7 +129,7 @@ func (r *zkRegistry) InitListeners() { defer oldDataListener.mutex.Unlock() r.dataListener.closed = true recovered := r.dataListener.subscribed - if recovered != nil && len(recovered) > 0 { + if len(recovered) > 0 { // recover all subscribed url for _, oldListener := range recovered { var ( diff --git a/registry/zookeeper/registry_test.go b/registry/zookeeper/registry_test.go index 63f4b25025862ec620ab22eed6e7af026bd4d61b..5959a903bc883141f158c5462b0a775c711f8f51 100644 --- a/registry/zookeeper/registry_test.go +++ b/registry/zookeeper/registry_test.go @@ -57,11 +57,13 @@ func Test_UnRegister(t *testing.T) { _ = ts.Stop() }() err := reg.Register(url) + assert.NoError(t, err) children, _ := reg.client.GetChildren("/dubbo/com.ikurento.user.UserProvider/providers") assert.Regexp(t, ".*dubbo%3A%2F%2F127.0.0.1%3A20000%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26cluster%3Dmock%26.*.serviceid%3Dsoa.mock", children) assert.NoError(t, err) err = reg.UnRegister(url) + assert.NoError(t, err) children, err = reg.client.GetChildren("/dubbo/com.ikurento.user.UserProvider/providers") assert.Equal(t, 0, len(children)) assert.Error(t, err) @@ -71,7 +73,6 @@ func Test_UnRegister(t *testing.T) { children, _ = reg.client.GetChildren("/dubbo/com.ikurento.user.UserProvider/providers") assert.Regexp(t, ".*dubbo%3A%2F%2F127.0.0.1%3A20000%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26cluster%3Dmock%26.*.serviceid%3Dsoa.mock", children) assert.NoError(t, err) - } func Test_Subscribe(t *testing.T) { diff --git a/registry/zookeeper/service_discovery.go b/registry/zookeeper/service_discovery.go index 6d9582f33a7b2517c4edc96d00d00ad6b57a4835..a515e22d041859211a7a8dcb28bb94b32ed6ae42 100644 --- a/registry/zookeeper/service_discovery.go +++ b/registry/zookeeper/service_discovery.go @@ -60,9 +60,9 @@ func init() { } type zookeeperServiceDiscovery struct { - client *zookeeper.ZookeeperClient - csd *curator_discovery.ServiceDiscovery - listener *zookeeper.ZkEventListener + client *zookeeper.ZookeeperClient + csd *curator_discovery.ServiceDiscovery + //listener *zookeeper.ZkEventListener url *common.URL wg sync.WaitGroup cltLock sync.Mutex @@ -214,7 +214,7 @@ func (zksd *zookeeperServiceDiscovery) GetInstances(serviceName string) []regist if err != nil { logger.Errorf("[zkServiceDiscovery] Could not query the instances for service{%s}, error = err{%v} ", serviceName, err) - return make([]registry.ServiceInstance, 0, 0) + return make([]registry.ServiceInstance, 0) } iss := make([]registry.ServiceInstance, 0, len(criss)) for _, cris := range criss { diff --git a/registry/zookeeper/service_discovery_test.go b/registry/zookeeper/service_discovery_test.go index 60b3d137591b4c1c0cc4420b11c5e50d80f0769b..b7d4677deb4efc56f1d246dc1eabdb0033c94702 100644 --- a/registry/zookeeper/service_discovery_test.go +++ b/registry/zookeeper/service_discovery_test.go @@ -75,7 +75,9 @@ func TestNewZookeeperServiceDiscovery(t *testing.T) { func TestCURDZookeeperServiceDiscovery(t *testing.T) { ts := prepareData(t) - defer ts.Stop() + defer func() { + _ = ts.Stop() + }() sd, err := newZookeeperServiceDiscovery(testName) assert.Nil(t, err) defer func() { @@ -143,7 +145,9 @@ func TestCURDZookeeperServiceDiscovery(t *testing.T) { func TestAddListenerZookeeperServiceDiscovery(t *testing.T) { ts := prepareData(t) - defer ts.Stop() + defer func() { + _ = ts.Stop() + }() sd, err := newZookeeperServiceDiscovery(testName) assert.Nil(t, err) defer func() { @@ -176,7 +180,7 @@ func TestAddListenerZookeeperServiceDiscovery(t *testing.T) { extension.SetAndInitGlobalDispatcher("direct") extension.GetGlobalDispatcher().AddEventListener(sicl) err = sd.AddListener(sicl) - assert.Nil(t, err) + assert.NoError(t, err) err = sd.Update(®istry.DefaultServiceInstance{ Id: "testId", @@ -187,6 +191,7 @@ func TestAddListenerZookeeperServiceDiscovery(t *testing.T) { Healthy: true, Metadata: nil, }) + assert.NoError(t, err) tn.wg.Wait() } diff --git a/remoting/etcdv3/client_test.go b/remoting/etcdv3/client_test.go index 181f5c6c832e2189f6afef73e4d59e6309c769bd..787c24d45fba17584dbdd4cb6485cf31ad0e5d2c 100644 --- a/remoting/etcdv3/client_test.go +++ b/remoting/etcdv3/client_test.go @@ -108,7 +108,6 @@ func (suite *ClientTestSuite) SetupSuite() { } suite.etcd = e - return } // stop etcd server @@ -136,7 +135,6 @@ func (suite *ClientTestSuite) SetupTest() { err := c.CleanKV() suite.Nil(err) suite.client = c - return } func (suite *ClientTestSuite) TestClientClose() { diff --git a/remoting/getty/dubbo_codec_for_test.go b/remoting/getty/dubbo_codec_for_test.go index b33fb7422e6d0099d86cdf6410f4ea8daf626a0d..be6d9db07c681839485ddad65ce989d7235ec5af 100644 --- a/remoting/getty/dubbo_codec_for_test.go +++ b/remoting/getty/dubbo_codec_for_test.go @@ -171,10 +171,7 @@ func (c *DubboTestCodec) Decode(data []byte) (remoting.DecodeResult, int, error) } func (c *DubboTestCodec) isRequest(data []byte) bool { - if data[2]&byte(0x80) == 0x00 { - return false - } - return true + return data[2]&byte(0x80) != 0x00 } // decode request diff --git a/remoting/getty/getty_client_test.go b/remoting/getty/getty_client_test.go index 982c509b322b3bdaf6ea1c27f67c32d4612cce27..c32e0c23f4b3705c3400a96a8bb1247c7e3eae40 100644 --- a/remoting/getty/getty_client_test.go +++ b/remoting/getty/getty_client_test.go @@ -396,6 +396,7 @@ func InitTest(t *testing.T) (*Server, *common.URL) { "environment=dev&interface=com.ikurento.user.UserProvider&ip=127.0.0.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&bean.name=UserProvider") + assert.NoError(t, err) // init server userProvider := &UserProvider{} _, err = common.ServiceMap.Register("", url.Protocol, "", "0.0.1", userProvider) @@ -432,7 +433,7 @@ type ( } UserProvider struct { - user map[string]User + //user map[string]User } ) diff --git a/remoting/getty/pool.go b/remoting/getty/pool.go index c70aeea5160191a729d2ac3d91a177f299a5ba25..63c9c1a1fb4659ec2d4b07f14008acc99b9b9c3a 100644 --- a/remoting/getty/pool.go +++ b/remoting/getty/pool.go @@ -91,7 +91,7 @@ func newGettyRPCClientConn(pool *gettyRPCClientPool, addr string) (*gettyRPCClie break } - if time.Now().Sub(start) > connectTimeout { + if time.Since(start) > connectTimeout { c.gettyClient.Close() return nil, perrors.New(fmt.Sprintf("failed to create client connection to %s in %s", addr, connectTimeout)) } @@ -292,11 +292,7 @@ func (c *gettyRPCClient) getClientRpcSession(session getty.Session) (rpcSession, } func (c *gettyRPCClient) isAvailable() bool { - if c.selectSession() == nil { - return false - } - - return true + return c.selectSession() != nil } func (c *gettyRPCClient) close() error { @@ -314,9 +310,7 @@ func (c *gettyRPCClient) close() error { c.gettyClient = nil sessions = make([]*rpcSession, 0, len(c.sessions)) - for _, s := range c.sessions { - sessions = append(sessions, s) - } + sessions = append(sessions, c.sessions...) c.sessions = c.sessions[:0] }() diff --git a/remoting/kubernetes/client.go b/remoting/kubernetes/client.go index 5399e5f21b6acb70420bd054aa9b83a3d8ad98f0..ce6bcccea50643cd49f3f99fcf4b86e73309b28c 100644 --- a/remoting/kubernetes/client.go +++ b/remoting/kubernetes/client.go @@ -186,12 +186,12 @@ func ValidateClient(container clientFacade) error { // NewMockClient exports for registry package test func NewMockClient(podList *v1.PodList) (*Client, error) { - ctx, cancel := context.WithCancel(context.Background()) controller, err := newDubboRegistryController(ctx, common.CONSUMER, func() (kubernetes.Interface, error) { return fake.NewSimpleClientset(podList), nil }) if err != nil { + cancel() return nil, perrors.WithMessage(err, "new dubbo-registry controller") } diff --git a/remoting/kubernetes/client_test.go b/remoting/kubernetes/client_test.go index fdaee96b4451cba3fd6ba043be9d6b96feadf8c0..9cc421225ea15c250c3ea1196432cb65635144a2 100644 --- a/remoting/kubernetes/client_test.go +++ b/remoting/kubernetes/client_test.go @@ -317,7 +317,8 @@ func TestClientGetChildrenKVList(t *testing.T) { wc, done, err := client.WatchWithPrefix(prefix) if err != nil { - t.Fatal(err) + t.Error(err) + return } wg.Done() diff --git a/remoting/kubernetes/facade_test.go b/remoting/kubernetes/facade_test.go index 00e2e1171c54c2b07973b66cb96cf64e67683f00..a6c6c02b515b6e1ebc815bb5b388ae68db68621d 100644 --- a/remoting/kubernetes/facade_test.go +++ b/remoting/kubernetes/facade_test.go @@ -19,7 +19,6 @@ package kubernetes import ( "strconv" - "sync" "testing" ) @@ -30,9 +29,9 @@ import ( type mockFacade struct { *common.URL - client *Client - cltLock sync.Mutex - done chan struct{} + client *Client + //cltLock sync.Mutex + //done chan struct{} } func (r *mockFacade) Client() *Client { diff --git a/remoting/kubernetes/watch.go b/remoting/kubernetes/watch.go index 07eeb09b4dd4627fdd3b18ee4d59356911b3a9b1..7bb5ef1754836b481089d67b9cf34437567ffa9a 100644 --- a/remoting/kubernetes/watch.go +++ b/remoting/kubernetes/watch.go @@ -116,21 +116,17 @@ type watcherSetImpl struct { // closeWatchers // when the watcher-set was closed func (s *watcherSetImpl) closeWatchers() { - - select { - case <-s.ctx.Done(): - - // parent ctx be canceled, close the watch-set's watchers - s.lock.Lock() - watchers := s.watchers - s.lock.Unlock() - - for _, w := range watchers { - // stop data stream - // close(w.ch) - // stop watcher - w.stop() - } + <-s.ctx.Done() + // parent ctx be canceled, close the watch-set's watchers + s.lock.Lock() + watchers := s.watchers + s.lock.Unlock() + + for _, w := range watchers { + // stop data stream + // close(w.ch) + // stop watcher + w.stop() } } diff --git a/remoting/kubernetes/watch_test.go b/remoting/kubernetes/watch_test.go index 8889103be212381c07ffff3c3d4399f41aeee564..efefcc5dc9db629aa0f109a8da4f4227c18504fa 100644 --- a/remoting/kubernetes/watch_test.go +++ b/remoting/kubernetes/watch_test.go @@ -42,7 +42,8 @@ func TestWatchSet(t *testing.T) { defer wg.Done() w, err := s.Watch("key-1", false) if err != nil { - t.Fatal(err) + t.Error(err) + return } for { select { @@ -64,7 +65,8 @@ func TestWatchSet(t *testing.T) { defer wg.Done() w, err := s.Watch("key", true) if err != nil { - t.Fatal(err) + t.Error(err) + return } for { @@ -86,7 +88,8 @@ func TestWatchSet(t *testing.T) { Key: "key-" + strconv.Itoa(i), Value: strconv.Itoa(i), }); err != nil { - t.Fatal(err) + t.Error(err) + return } }(i) } diff --git a/remoting/zookeeper/listener.go b/remoting/zookeeper/listener.go index e5ddcadeaca9c3ce972cbe781413ebec7393afce..7b90e523364b6a1a77b8e30ef73ddca6caffda6a 100644 --- a/remoting/zookeeper/listener.go +++ b/remoting/zookeeper/listener.go @@ -362,9 +362,9 @@ func (l *ZkEventListener) ListenServiceEvent(conf *common.URL, zkPath string, li }(zkPath, listener) } -func (l *ZkEventListener) valid() bool { - return l.client.ZkConnValid() -} +//func (l *ZkEventListener) valid() bool { +// return l.client.ZkConnValid() +//} // Close will let client listen exit func (l *ZkEventListener) Close() {