This is an automated email from the ASF dual-hosted git repository.
alexstocks pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/dubbo-go.git
The following commit(s) were added to refs/heads/develop by this push:
new 0ba792a48 fix: update golangci-lint to v2 and fix the issues detected
by it(#2850) (#2878)
0ba792a48 is described below
commit 0ba792a48728b278c910fabb251d0a82e96e9bae
Author: ALSoryu <[email protected]>
AuthorDate: Sat May 17 22:20:32 2025 +0800
fix: update golangci-lint to v2 and fix the issues detected by it(#2850)
(#2878)
* update golangci-lint to v2 and fix the issues detected by it
* change .github\workflows\golangci-lint.yml
* change .github\workflows\golangci-lint.yml
* change .github\workflows\golangci-lint.yml
* fix issues detected by golangci-lint
---
.github/workflows/golangci-lint.yml | 4 +-
.golangci.yml | 111 ++++++++++++---------
client/client.go | 6 +-
cluster/cluster/interceptor_invoker.go | 2 +-
cluster/cluster/zoneaware/cluster_interceptor.go | 2 +-
cluster/cluster/zoneaware/cluster_invoker.go | 4 +-
cluster/cluster/zoneaware/cluster_invoker_test.go | 4 +-
cluster/directory/static/directory.go | 4 +-
cluster/router/chain/chain.go | 2 +-
cluster/router/condition/dynamic_router.go | 2 +-
cluster/router/condition/matcher/argument.go | 2 +-
cluster/router/condition/matcher/attachment.go | 2 +-
.../condition/matcher/pattern_value/wildcard.go | 2 +-
cluster/router/condition/route.go | 8 +-
cluster/router/script/instance/js_instance_test.go | 6 +-
cluster/router/script/router.go | 10 +-
common/config/utils.go | 2 +-
config/config_center_config.go | 2 +-
config/config_utils.go | 2 +-
config/graceful_shutdown.go | 29 +++---
config/metadata_config.go | 2 +-
config/options.go | 4 +-
config/registry_config.go | 18 ++--
config_center/nacos/facade.go | 9 +-
config_center/zookeeper/listener.go | 2 +-
filter/adaptivesvc/limiter/hill_climbing.go | 2 +-
filter/auth/default_authenticator.go | 2 +-
filter/generic/service_filter_test.go | 4 +-
filter/otel/trace/filter_test.go | 12 +--
filter/token/filter.go | 6 +-
global/reference_config.go | 4 +-
graceful_shutdown/shutdown.go | 30 +++---
metadata/client_test.go | 2 +-
metadata/report/zookeeper/listener.go | 2 +-
options.go | 9 +-
protocol/dubbo/hessian2/hessian_request.go | 4 +-
protocol/dubbo/hessian2/java_class.go | 2 +-
protocol/dubbo/impl/hessian.go | 6 +-
protocol/dubbo3/dubbo3_protocol.go | 2 +-
protocol/grpc/codec.go | 2 +-
.../grpc/protoc-gen-dubbo/plugin/dubbo/dubbo.go | 4 +-
protocol/jsonrpc/json.go | 2 +-
.../protocolwrapper/protocol_filter_wrapper.go | 7 +-
protocol/rest/server/rest_server.go | 29 +++---
protocol/rpc_status.go | 2 +-
protocol/triple/triple_protocol/codec.go | 6 +-
protocol/triple/triple_protocol/handler_compat.go | 6 +-
.../triple_protocol/handler_stream_compat.go | 1 -
protocol/triple/triple_protocol/header.go | 16 +--
protocol/triple/triple_protocol/protocol_grpc.go | 10 +-
registry/base_registry.go | 4 +-
registry/directory/directory.go | 8 +-
registry/directory/directory_test.go | 2 +-
registry/etcdv3/service_discovery.go | 4 +-
registry/nacos/registry.go | 8 +-
registry/nacos/service_discovery.go | 3 +-
registry/options.go | 3 +-
registry/polaris/core.go | 53 +++++-----
registry/polaris/registry.go | 1 -
registry/polaris/service_discovery.go | 4 +-
registry/protocol/protocol.go | 14 ++-
.../protocol_ports_metadata_customizer.go | 2 +-
.../service_instances_changed_listener_impl.go | 2 +-
.../rest/rest_subscribed_urls_synthesizer.go | 2 +-
registry/zookeeper/listener.go | 2 +-
registry/zookeeper/registry.go | 4 +-
registry/zookeeper/service_discovery.go | 3 +-
remoting/polaris/builder.go | 2 +-
server/options.go | 10 +-
server/server.go | 5 +-
70 files changed, 277 insertions(+), 272 deletions(-)
diff --git a/.github/workflows/golangci-lint.yml
b/.github/workflows/golangci-lint.yml
index c54934b58..9df539d0d 100644
--- a/.github/workflows/golangci-lint.yml
+++ b/.github/workflows/golangci-lint.yml
@@ -25,7 +25,7 @@ jobs:
go-version: ${{ matrix.golang }}
- uses: actions/checkout@v4
- name: golangci-lint
- uses: golangci/golangci-lint-action@v6
+ uses: golangci/golangci-lint-action@v8
with:
- version: v1.64.8
+ version: v2.1.6
args: --timeout=10m
diff --git a/.golangci.yml b/.golangci.yml
index 79f2e8a70..ae141b307 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -1,52 +1,69 @@
-linters-settings:
- govet:
- enable:
- - shadow
- gocyclo:
- min-complexity: 10
- dupl:
- threshold: 100
- goconst:
- min-len: 2
- min-occurrences: 2
- depguard:
- rules:
- main:
- deny:
- - pkg: "github.com/sirupsen/logrus"
- desc: logging is allowed only by logutils.Log, logrus is allowed
to use only in logutils package
- misspell:
- locale: US
- ignore-words:
- - nto
- lll:
- line-length: 140
- goimports:
- local-prefixes: github.com/golangci/golangci-lint
- gocritic:
- enabled-tags:
- - performance
- - style
- - experimental
- disabled-checks:
- - wrapperFunc
-
+version: "2"
linters:
- disable-all: true
+ default: none
enable:
- govet
- - staticcheck
- ineffassign
- misspell
-
-issues:
- exclude-rules:
- - text: "weak cryptographic primitive"
- linters:
- - gosec
- - linters:
- - staticcheck
- text: "SA1019:"
- exclude-dirs:
- - test/testdata_etc
- - pkg/golinters/goanalysis/(checker|passes)
+ - staticcheck
+ settings:
+ depguard:
+ rules:
+ main:
+ deny:
+ - pkg: github.com/sirupsen/logrus
+ desc: logging is allowed only by logutils.Log, logrus is allowed
to use only in logutils package
+ dupl:
+ threshold: 100
+ goconst:
+ min-len: 2
+ min-occurrences: 2
+ gocritic:
+ disabled-checks:
+ - wrapperFunc
+ enabled-tags:
+ - performance
+ - style
+ - experimental
+ gocyclo:
+ min-complexity: 10
+ govet:
+ enable:
+ - shadow
+ lll:
+ line-length: 140
+ misspell:
+ locale: US
+ ignore-rules:
+ - nto
+ exclusions:
+ generated: lax
+ presets:
+ - comments
+ - common-false-positives
+ - legacy
+ - std-error-handling
+ rules:
+ - linters:
+ - gosec
+ text: weak cryptographic primitive
+ - linters:
+ - staticcheck
+ text: '(SA1019|ST1001):'
+ paths:
+ - test/testdata_etc
+ - pkg/golinters/goanalysis/(checker|passes)
+ - third_party$
+ - builtin$
+ - examples$
+formatters:
+ settings:
+ goimports:
+ local-prefixes:
+ - github.com/golangci/golangci-lint
+ exclusions:
+ generated: lax
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
diff --git a/client/client.go b/client/client.go
index 24414a0e9..69ad59cd0 100644
--- a/client/client.go
+++ b/client/client.go
@@ -144,9 +144,9 @@ func (cli *Client) dial(interfaceName string, info
*ClientInfo, opts ...Referenc
func generateInvocation(methodName string, reqs []any, resp any, callType
string, opts *CallOptions) (protocol.Invocation, error) {
var paramsRawVals []any
- for _, req := range reqs {
- paramsRawVals = append(paramsRawVals, req)
- }
+
+ paramsRawVals = append(paramsRawVals, reqs...)
+
if resp != nil {
paramsRawVals = append(paramsRawVals, resp)
}
diff --git a/cluster/cluster/interceptor_invoker.go
b/cluster/cluster/interceptor_invoker.go
index 0cbe262da..caba5ff18 100644
--- a/cluster/cluster/interceptor_invoker.go
+++ b/cluster/cluster/interceptor_invoker.go
@@ -98,7 +98,7 @@ func BuildInterceptorChain(invoker protocol.Invoker, builtins
...Interceptor) pr
}
}
- if builtins != nil && len(builtins) > 0 {
+ if len(builtins) > 0 {
for i := len(builtins) - 1; i >= 0; i-- {
v := &InterceptorInvoker{next: next, interceptor:
builtins[i]}
next = v
diff --git a/cluster/cluster/zoneaware/cluster_interceptor.go
b/cluster/cluster/zoneaware/cluster_interceptor.go
index cb988cbcb..b78640b87 100644
--- a/cluster/cluster/zoneaware/cluster_interceptor.go
+++ b/cluster/cluster/zoneaware/cluster_interceptor.go
@@ -40,7 +40,7 @@ func (z *interceptor) Invoke(ctx context.Context, invoker
protocol.Invoker, invo
invocation.SetAttachment(key, "true")
}
case string:
- if "true" == value {
+ if value == "true" {
invocation.SetAttachment(key, "true")
}
default:
diff --git a/cluster/cluster/zoneaware/cluster_invoker.go
b/cluster/cluster/zoneaware/cluster_invoker.go
index f6cbacf1f..90489174e 100644
--- a/cluster/cluster/zoneaware/cluster_invoker.go
+++ b/cluster/cluster/zoneaware/cluster_invoker.go
@@ -66,7 +66,7 @@ func (invoker *zoneawareClusterInvoker) Invoke(ctx
context.Context, invocation p
// providers in the registry with the same zone
key := constant.RegistryKey + "." + constant.RegistryZoneKey
zone := invocation.GetAttachmentWithDefaultValue(key, "")
- if "" != zone {
+ if zone != "" {
for _, invoker := range invokers {
if invoker.IsAvailable() && matchParam(zone, key, "",
invoker) {
return invoker.Invoke(ctx, invocation)
@@ -74,7 +74,7 @@ func (invoker *zoneawareClusterInvoker) Invoke(ctx
context.Context, invocation p
}
force :=
invocation.GetAttachmentWithDefaultValue(constant.RegistryKey+"."+constant.RegistryZoneForceKey,
"")
- if "true" == force {
+ if force == "true" {
return &protocol.RPCResult{
Err: fmt.Errorf("no registry instance in zone
or "+
"no available providers in the
registry, zone: %v, "+
diff --git a/cluster/cluster/zoneaware/cluster_invoker_test.go
b/cluster/cluster/zoneaware/cluster_invoker_test.go
index 36b138a3f..4ce58e7ba 100644
--- a/cluster/cluster/zoneaware/cluster_invoker_test.go
+++ b/cluster/cluster/zoneaware/cluster_invoker_test.go
@@ -58,7 +58,7 @@ func TestZoneWareInvokerWithPreferredSuccess(t *testing.T) {
invoker := mock.NewMockInvoker(ctrl)
invoker.EXPECT().IsAvailable().Return(true).AnyTimes()
invoker.EXPECT().GetURL().Return(url).AnyTimes()
- if 0 == i {
+ if i == 0 {
url.SetParam(constant.RegistryKey+"."+constant.PreferredKey, "true")
invoker.EXPECT().Invoke(gomock.Any(),
gomock.Any()).DoAndReturn(
func(ctx context.Context, invocation
protocol.Invocation) protocol.Result {
@@ -101,7 +101,7 @@ func TestZoneWareInvokerWithWeightSuccess(t *testing.T) {
invoker.EXPECT().IsAvailable().Return(true).AnyTimes()
invoker.EXPECT().GetURL().Return(url).AnyTimes()
url.SetParam(constant.RegistryKey+"."+constant.RegistryLabelKey, "true")
- if 1 == i {
+ if i == 1 {
url.SetParam(constant.RegistryKey+"."+constant.WeightKey, w1)
invoker.EXPECT().Invoke(gomock.Any(),
gomock.Any()).DoAndReturn(
func(ctx context.Context, invocation
protocol.Invocation) protocol.Result {
diff --git a/cluster/directory/static/directory.go
b/cluster/directory/static/directory.go
index d8ed888b2..401c93efc 100644
--- a/cluster/directory/static/directory.go
+++ b/cluster/directory/static/directory.go
@@ -51,7 +51,7 @@ func NewDirectory(invokers []protocol.Invoker) *directory {
// for-loop invokers ,if all invokers is available ,then it means directory is
available
func (dir *directory) IsAvailable() bool {
- if dir.Directory.IsDestroyed() {
+ if dir.IsDestroyed() {
return false
}
@@ -82,7 +82,7 @@ func (dir *directory) List(invocation protocol.Invocation)
[]protocol.Invoker {
// Destroy Destroy
func (dir *directory) Destroy() {
- dir.Directory.DoDestroy(func() {
+ dir.DoDestroy(func() {
for _, ivk := range dir.invokers {
ivk.Destroy()
}
diff --git a/cluster/router/chain/chain.go b/cluster/router/chain/chain.go
index a9f9ce5a8..b13866596 100644
--- a/cluster/router/chain/chain.go
+++ b/cluster/router/chain/chain.go
@@ -109,7 +109,7 @@ func (c *RouterChain) copyRouters() []router.PriorityRouter
{
func (c *RouterChain) copyInvokers() []protocol.Invoker {
c.mutex.RLock()
defer c.mutex.RUnlock()
- if c.invokers == nil || len(c.invokers) == 0 {
+ if len(c.invokers) == 0 {
return nil
}
ret := make([]protocol.Invoker, 0, len(c.invokers))
diff --git a/cluster/router/condition/dynamic_router.go
b/cluster/router/condition/dynamic_router.go
index 4e344d2ce..3e7910730 100644
--- a/cluster/router/condition/dynamic_router.go
+++ b/cluster/router/condition/dynamic_router.go
@@ -231,7 +231,7 @@ func generateMultiConditionRoute(rawConfig string)
(*multiplyConditionRoute, boo
if conditionRoute == nil {
continue
}
- if conditionRoute.thenCondition != nil &&
len(conditionRoute.thenCondition) != 0 {
+ if len(conditionRoute.thenCondition) != 0 {
conditionRouters = append(conditionRouters,
conditionRoute)
} else {
disableMultiConditions = append(disableMultiConditions,
&conditionRoute.whenCondition)
diff --git a/cluster/router/condition/matcher/argument.go
b/cluster/router/condition/matcher/argument.go
index f0115f4a7..6adf1b188 100644
--- a/cluster/router/condition/matcher/argument.go
+++ b/cluster/router/condition/matcher/argument.go
@@ -34,7 +34,7 @@ import (
)
var (
- argumentsPattern = regexp.MustCompile("arguments\\[([0-9]+)\\]")
+ argumentsPattern = regexp.MustCompile(`arguments\[([0-9]+)\]`)
notFoundArgumentValue = "dubbo internal not found argument condition
value"
)
diff --git a/cluster/router/condition/matcher/attachment.go
b/cluster/router/condition/matcher/attachment.go
index 338fed29e..c8cf02c68 100644
--- a/cluster/router/condition/matcher/attachment.go
+++ b/cluster/router/condition/matcher/attachment.go
@@ -32,7 +32,7 @@ import (
)
var (
- attachmentPattern =
regexp.MustCompile("attachments\\[([a-zA-Z0-9_]+)\\]")
+ attachmentPattern =
regexp.MustCompile(`attachments\[([a-zA-Z0-9_]+)\]`)
notFoundAttachmentValue = "dubbo internal not found attachment
condition value"
)
diff --git a/cluster/router/condition/matcher/pattern_value/wildcard.go
b/cluster/router/condition/matcher/pattern_value/wildcard.go
index 7e73610c5..15aa9c272 100644
--- a/cluster/router/condition/matcher/pattern_value/wildcard.go
+++ b/cluster/router/condition/matcher/pattern_value/wildcard.go
@@ -54,7 +54,7 @@ func (w *WildcardValuePattern) Match(pattern string, value
string, url *common.U
pattern = url.GetRawParam(pattern[1:])
}
- if "*" == pattern {
+ if pattern == "*" {
return true
}
if pattern == "" && value == "" {
diff --git a/cluster/router/condition/route.go
b/cluster/router/condition/route.go
index cbe2995fb..ed09eb9d1 100644
--- a/cluster/router/condition/route.go
+++ b/cluster/router/condition/route.go
@@ -42,7 +42,7 @@ import (
)
var (
- routePattern = regexp.MustCompile("([&!=,]*)\\s*([^&!=,\\s]+)")
+ routePattern = regexp.MustCompile(`([&!=,]*)\s*([^&!=,\s]+)`)
illegalMsg = "Illegal route rule \"%s\", The error char '%s'
before '%s'"
matcherFactories = make([]matcher.ConditionMatcherFactory, 0, 8)
once sync.Once
@@ -118,8 +118,8 @@ func generateMatcher(url *common.URL) (when, then
map[string]matcher.Matcher, er
if rule == "" || len(strings.Trim(rule, " ")) == 0 {
return nil, nil, errors.Errorf("Illegal route rule!")
}
- rule = strings.Replace(rule, "consumer.", "", -1)
- rule = strings.Replace(rule, "provider.", "", -1)
+ rule = strings.ReplaceAll(rule, "consumer.", "")
+ rule = strings.ReplaceAll(rule, "provider.", "")
i := strings.Index(rule, "=>")
// for the case of `{when rule} => {then rule}`
var whenRule string
@@ -444,7 +444,7 @@ func NewConditionMultiDestRouter(url *common.URL)
(*MultiDestRouter, error) {
return nil, errors.Errorf("Condition Router get the rule key
invaild , got %T", rawCondConf)
}
// ensure config effective
- if (condConf.To == nil || len(condConf.To) == 0) && condConf.From.Match
== "" {
+ if (len(condConf.To) == 0) && condConf.From.Match == "" {
return nil, nil
}
diff --git a/cluster/router/script/instance/js_instance_test.go
b/cluster/router/script/instance/js_instance_test.go
index 4263966bf..c090c7bfd 100644
--- a/cluster/router/script/instance/js_instance_test.go
+++ b/cluster/router/script/instance/js_instance_test.go
@@ -587,11 +587,11 @@ func TestRunScriptInPanic(t *testing.T) {
defer func(err *error) {
panicReason := recover()
if panicReason != nil {
- switch panicReason.(type) {
+ switch panicReason :=
panicReason.(type) {
case string:
- *err = fmt.Errorf("panic: %s",
panicReason.(string))
+ *err = fmt.Errorf("panic: %s",
panicReason)
case error:
- *err = panicReason.(error)
+ *err = panicReason
default:
*err = fmt.Errorf("panic
occurred: failed to retrieve panic information. Expected string or error, got
%T", panicReason)
}
diff --git a/cluster/router/script/router.go b/cluster/router/script/router.go
index ecb75c70d..57ff432d6 100644
--- a/cluster/router/script/router.go
+++ b/cluster/router/script/router.go
@@ -92,15 +92,15 @@ func (s *ScriptRouter) Process(event
*config_center.ConfigChangeEvent) {
}
}
// check new config
- if "" == cfg.ScriptType {
+ if cfg.ScriptType == "" {
logger.Errorf("`type` field must be set in config")
return
}
- if "" == cfg.Script {
+ if cfg.Script == "" {
logger.Errorf("`script` field must be set in config")
return
}
- if "" == cfg.Key {
+ if cfg.Key == "" {
logger.Errorf("`applicationName` field must be set in
config")
return
}
@@ -149,7 +149,7 @@ func (s *ScriptRouter) runScript(scriptType, rawScript
string, invokers []protoc
}
func (s *ScriptRouter) Route(invokers []protocol.Invoker, _ *common.URL,
invocation protocol.Invocation) []protocol.Invoker {
- if invokers == nil || len(invokers) == 0 {
+ if len(invokers) == 0 {
return []protocol.Invoker{}
}
@@ -157,7 +157,7 @@ func (s *ScriptRouter) Route(invokers []protocol.Invoker, _
*common.URL, invocat
enabled, scriptType, rawScript := s.enabled, s.scriptType, s.rawScript
s.mu.RUnlock()
- if enabled == false || s.scriptType == "" || s.rawScript == "" {
+ if !enabled || s.scriptType == "" || s.rawScript == "" {
return invokers
}
diff --git a/common/config/utils.go b/common/config/utils.go
index 1d7989935..2f5a68e5b 100644
--- a/common/config/utils.go
+++ b/common/config/utils.go
@@ -85,7 +85,7 @@ func MergeValue(str1, str2, def string) string {
if !defKey {
str = "," + constant.DefaultKey + str
}
- str = strings.TrimPrefix(strings.Replace(str, ","+constant.DefaultKey,
","+def, -1), ",")
+ str = strings.TrimPrefix(strings.ReplaceAll(str,
","+constant.DefaultKey, ","+def), ",")
return removeMinus(strings.Split(str, ","))
}
diff --git a/config/config_center_config.go b/config/config_center_config.go
index e206b8ae5..0c82a97db 100644
--- a/config/config_center_config.go
+++ b/config/config_center_config.go
@@ -117,7 +117,7 @@ func (c *CenterConfig) translateConfigAddress() string {
panic(err)
}
c.Protocol = translatedUrl.Scheme
- c.Address = strings.Replace(c.Address,
translatedUrl.Scheme+"://", "", -1)
+ c.Address = strings.ReplaceAll(c.Address,
translatedUrl.Scheme+"://", "")
}
return c.Address
}
diff --git a/config/config_utils.go b/config/config_utils.go
index 3ebc3672a..8a3c8a60f 100644
--- a/config/config_utils.go
+++ b/config/config_utils.go
@@ -51,7 +51,7 @@ func mergeValue(str1, str2, def string) string {
if !defKey {
str = "," + constant.DefaultKey + str
}
- str = strings.TrimPrefix(strings.Replace(str, ","+constant.DefaultKey,
","+def, -1), ",")
+ str = strings.TrimPrefix(strings.ReplaceAll(str,
","+constant.DefaultKey, ","+def), ",")
return removeMinus(strings.Split(str, ","))
}
diff --git a/config/graceful_shutdown.go b/config/graceful_shutdown.go
index 44b979456..e39b2b7e7 100644
--- a/config/graceful_shutdown.go
+++ b/config/graceful_shutdown.go
@@ -76,23 +76,22 @@ func gracefulShutdownInit() {
signal.Notify(signals, ShutdownSignals...)
go func() {
- select {
- case sig := <-signals:
- logger.Infof("get signal %s, applicationConfig
will shutdown.", sig)
- // gracefulShutdownOnce.Do(func() {
- time.AfterFunc(totalTimeout(), func() {
- logger.Warn("Shutdown gracefully
timeout, applicationConfig will shutdown immediately. ")
- os.Exit(0)
- })
- BeforeShutdown()
- // those signals' original behavior is exit
with dump ths stack, so we try to keep the behavior
- for _, dumpSignal := range
DumpHeapShutdownSignals {
- if sig == dumpSignal {
-
debug.WriteHeapDump(os.Stdout.Fd())
- }
- }
+ sig := <-signals
+ logger.Infof("get signal %s, applicationConfig will
shutdown.", sig)
+ // gracefulShutdownOnce.Do(func() {
+ time.AfterFunc(totalTimeout(), func() {
+ logger.Warn("Shutdown gracefully timeout,
applicationConfig will shutdown immediately. ")
os.Exit(0)
+ })
+ BeforeShutdown()
+ // those signals' original behavior is exit with dump
ths stack, so we try to keep the behavior
+ for _, dumpSignal := range DumpHeapShutdownSignals {
+ if sig == dumpSignal {
+ debug.WriteHeapDump(os.Stdout.Fd())
+ }
}
+ os.Exit(0)
+
}()
}
}
diff --git a/config/metadata_config.go b/config/metadata_config.go
index 9d7685a0e..24c88a339 100644
--- a/config/metadata_config.go
+++ b/config/metadata_config.go
@@ -143,7 +143,7 @@ func (mc *MetadataReportConfig) Init(rc *RootConfig) error {
}
return opts.Init()
}
- if rc.Registries != nil && len(rc.Registries) > 0 {
+ if len(rc.Registries) > 0 {
// if metadata report config is not available, then init
metadata report instance with registries
for id, reg := range rc.Registries {
if isValid(reg.Address) {
diff --git a/config/options.go b/config/options.go
index 7d01b0d2e..ca607c84f 100644
--- a/config/options.go
+++ b/config/options.go
@@ -100,9 +100,9 @@ func WithSticky() MethodOption {
}
}
-func WithRequestTimeout(millSeconds time.Duration) MethodOption {
+func WithRequestTimeout(timeout time.Duration) MethodOption {
return func(opts *MethodOptions) {
- opts.Method.RequestTimeout = millSeconds.String()
+ opts.Method.RequestTimeout = timeout.String()
}
}
diff --git a/config/registry_config.go b/config/registry_config.go
index 906fe83d2..e67233329 100644
--- a/config/registry_config.go
+++ b/config/registry_config.go
@@ -144,12 +144,14 @@ func (c *RegistryConfig) GetInstance(roleType
common.RoleType) (registry.Registr
func (c *RegistryConfig) toURL(roleType common.RoleType) (*common.URL, error) {
address := c.translateRegistryAddress()
var registryURLProtocol string
- if c.RegistryType == constant.RegistryTypeService {
+
+ switch c.RegistryType {
+ case constant.RegistryTypeService:
// service discovery protocol
registryURLProtocol = constant.ServiceRegistryProtocol
- } else if c.RegistryType == constant.RegistryTypeInterface {
+ case constant.RegistryTypeInterface:
registryURLProtocol = constant.RegistryProtocol
- } else {
+ default:
registryURLProtocol = constant.ServiceRegistryProtocol
}
return common.NewURL(registryURLProtocol+"://"+address,
@@ -175,24 +177,24 @@ func (c *RegistryConfig) toURLs(roleType common.RoleType)
([]*common.URL, error)
"which means that the address of this instance will not
be registered and not able to be found by other consumer instances.")
return urls, nil
}
-
- if c.RegistryType == constant.RegistryTypeService {
+ switch c.RegistryType {
+ case constant.RegistryTypeService:
// service discovery protocol
if registryURL, err =
c.createNewURL(constant.ServiceRegistryProtocol, address, roleType); err == nil
{
urls = append(urls, registryURL)
}
- } else if c.RegistryType == constant.RegistryTypeInterface {
+ case constant.RegistryTypeInterface:
if registryURL, err = c.createNewURL(constant.RegistryProtocol,
address, roleType); err == nil {
urls = append(urls, registryURL)
}
- } else if c.RegistryType == constant.RegistryTypeAll {
+ case constant.RegistryTypeAll:
if registryURL, err =
c.createNewURL(constant.ServiceRegistryProtocol, address, roleType); err == nil
{
urls = append(urls, registryURL)
}
if registryURL, err = c.createNewURL(constant.RegistryProtocol,
address, roleType); err == nil {
urls = append(urls, registryURL)
}
- } else {
+ default:
if registryURL, err =
c.createNewURL(constant.ServiceRegistryProtocol, address, roleType); err == nil
{
urls = append(urls, registryURL)
}
diff --git a/config_center/nacos/facade.go b/config_center/nacos/facade.go
index 7b8ce8c0c..39ca77281 100644
--- a/config_center/nacos/facade.go
+++ b/config_center/nacos/facade.go
@@ -43,11 +43,8 @@ type nacosClientFacade interface {
// HandleClientRestart Restart configClient handler
func HandleClientRestart(r nacosClientFacade) {
defer r.WaitGroup().Done()
- for {
- select {
- case <-r.GetDone():
-
logger.Warnf("(NacosProviderRegistry)reconnectNacosRegistry goroutine exit
now...")
- return
- }
+ for range r.GetDone() {
+ logger.Warnf("(NacosProviderRegistry)reconnectNacosRegistry
goroutine exit now...")
+ return
}
}
diff --git a/config_center/zookeeper/listener.go
b/config_center/zookeeper/listener.go
index 12454d170..9c7239532 100644
--- a/config_center/zookeeper/listener.go
+++ b/config_center/zookeeper/listener.go
@@ -94,7 +94,7 @@ func (l *CacheListener) pathToKeyGroup(path string) (string,
string) {
if len(path) == 0 {
return path, ""
}
- groupKey := strings.Replace(strings.Replace(path,
l.rootPath+constant.PathSeparator, "", -1), constant.PathSeparator,
constant.DotSeparator, -1)
+ groupKey := strings.ReplaceAll(strings.ReplaceAll(path,
l.rootPath+constant.PathSeparator, ""), constant.PathSeparator,
constant.DotSeparator)
index := strings.Index(groupKey, constant.DotSeparator)
return groupKey[index+1:], groupKey[0:index]
}
diff --git a/filter/adaptivesvc/limiter/hill_climbing.go
b/filter/adaptivesvc/limiter/hill_climbing.go
index 3ce16ee0a..2f714ff60 100644
--- a/filter/adaptivesvc/limiter/hill_climbing.go
+++ b/filter/adaptivesvc/limiter/hill_climbing.go
@@ -140,7 +140,7 @@ func (u *HillClimbingUpdater) DoUpdate() error {
}()
VerboseDebugf("[HillClimbingUpdater] A request finished, the limiter
will be updated, seq: %d.", u.seq)
- rtt := uint64(time.Now().Sub(u.startTime).Milliseconds())
+ rtt := uint64(time.Since(u.startTime).Milliseconds())
inflight := u.limiter.Inflight()
option, err := u.getOption(rtt, inflight)
diff --git a/filter/auth/default_authenticator.go
b/filter/auth/default_authenticator.go
index 43a7a9227..08e03c445 100644
--- a/filter/auth/default_authenticator.go
+++ b/filter/auth/default_authenticator.go
@@ -140,7 +140,7 @@ func doAuthWork(url *common.URL, do
func(filter.Authenticator) error) error {
return do(authenticator)
} else {
- return errors.New("Authenticator for " +
constant.ServiceAuthKey + " is not existing, make sure you have import the
package.")
+ return errors.New("authenticator for " +
constant.ServiceAuthKey + " is not existing, make sure you have import the
package")
}
}
return nil
diff --git a/filter/generic/service_filter_test.go
b/filter/generic/service_filter_test.go
index 971d7312a..ef631a930 100644
--- a/filter/generic/service_filter_test.go
+++ b/filter/generic/service_filter_test.go
@@ -177,12 +177,12 @@ func TestServiceFilter_Invoke(t *testing.T) {
result = filter.Invoke(context.Background(), mockInvoker, invocation5)
assert.Equal(t,
fmt.Sprintf("\"hello11\" method is not found, service key: %s",
ivkUrl.ServiceKey()),
- fmt.Sprintf("%v", result.Error().(error)))
+ fmt.Sprintf("%v", result.Error()))
result = filter.Invoke(context.Background(), mockInvoker, invocation6)
assert.Equal(t,
"the number of args(=2) is not matched with \"Hello\" method",
- fmt.Sprintf("%v", result.Error().(error)))
+ fmt.Sprintf("%v", result.Error()))
//result = filter.Invoke(context.Background(), mockInvoker, invocation7)
//assert.Equal(t, int64(200),
result.Result().(*generalizer.ResponseType).GetCode())
diff --git a/filter/otel/trace/filter_test.go b/filter/otel/trace/filter_test.go
index b672ffc9f..35772ca5e 100644
--- a/filter/otel/trace/filter_test.go
+++ b/filter/otel/trace/filter_test.go
@@ -157,7 +157,7 @@ func (mr *MockInvocationMockRecorder) Arguments()
*gomock.Call {
// Reply mocks base method
func (m *MockInvocation) Reply() any {
ret := m.ctrl.Call(m, "Reply")
- ret0, _ := ret[0].(any)
+ ret0 := ret[0]
return ret0
}
@@ -228,7 +228,7 @@ func (mr *MockInvocationMockRecorder) GetAttachment(key
any) *gomock.Call {
// GetAttachmentInterface mocks base method
func (m *MockInvocation) GetAttachmentInterface(arg0 string) any {
ret := m.ctrl.Call(m, "GetAttachmentInterface", arg0)
- ret0, _ := ret[0].(any)
+ ret0 := ret[0]
return ret0
}
@@ -290,7 +290,7 @@ func (mr *MockInvocationMockRecorder) SetAttribute(key,
value any) *gomock.Call
// GetAttribute mocks base method
func (m *MockInvocation) GetAttribute(key string) (any, bool) {
ret := m.ctrl.Call(m, "GetAttribute", key)
- ret0, _ := ret[0].(any)
+ ret0 := ret[0]
ret1, _ := ret[1].(bool)
return ret0, ret1
}
@@ -303,7 +303,7 @@ func (mr *MockInvocationMockRecorder) GetAttribute(key any)
*gomock.Call {
// GetAttributeWithDefaultValue mocks base method
func (m *MockInvocation) GetAttributeWithDefaultValue(key string, defaultValue
any) any {
ret := m.ctrl.Call(m, "GetAttributeWithDefaultValue", key, defaultValue)
- ret0, _ := ret[0].(any)
+ ret0 := ret[0]
return ret0
}
@@ -370,7 +370,7 @@ func (mr *MockResultMockRecorder) SetResult(arg0 any)
*gomock.Call {
// Result mocks base method
func (m *MockResult) Result() any {
ret := m.ctrl.Call(m, "Result")
- ret0, _ := ret[0].(any)
+ ret0 := ret[0]
return ret0
}
@@ -414,7 +414,7 @@ func (mr *MockResultMockRecorder) AddAttachment(arg0, arg1
any) *gomock.Call {
// Attachment mocks base method
func (m *MockResult) Attachment(arg0 string, arg1 any) any {
ret := m.ctrl.Call(m, "Attachment", arg0, arg1)
- ret0, _ := ret[0].(any)
+ ret0 := ret[0]
return ret0
}
diff --git a/filter/token/filter.go b/filter/token/filter.go
index a84e9dedd..62e5f0413 100644
--- a/filter/token/filter.go
+++ b/filter/token/filter.go
@@ -70,13 +70,13 @@ func (f *tokenFilter) Invoke(ctx context.Context, invoker
protocol.Invoker, invo
if !exist || remoteTknIface == nil {
return &protocol.RPCResult{Err:
perrors.Errorf(InValidTokenFormat, invoker, invocation.MethodName())}
}
- switch remoteTknIface.(type) {
+ switch remoteTknIface := remoteTknIface.(type) {
case string:
// deal with dubbo protocol
- remoteTkn = remoteTknIface.(string)
+ remoteTkn = remoteTknIface
case []string:
// deal with triple protocol
- remoteTkns := remoteTknIface.([]string)
+ remoteTkns := remoteTknIface
if len(remoteTkns) != 1 {
return &protocol.RPCResult{Err:
perrors.Errorf(InValidTokenFormat, invoker, invocation.MethodName())}
}
diff --git a/global/reference_config.go b/global/reference_config.go
index f5eb23335..ff035d6e6 100644
--- a/global/reference_config.go
+++ b/global/reference_config.go
@@ -75,7 +75,7 @@ func (c *ReferenceConfig) GetOptions() []ReferenceOption {
if c.Protocol != "" {
refOpts = append(refOpts, WithReference_Protocol(c.Protocol))
}
- if c.RegistryIDs != nil && len(c.RegistryIDs) > 0 {
+ if len(c.RegistryIDs) > 0 {
refOpts = append(refOpts,
WithReference_RegistryIDs(c.RegistryIDs))
}
if c.Cluster != "" {
@@ -101,7 +101,7 @@ func (c *ReferenceConfig) GetOptions() []ReferenceOption {
if c.ProvidedBy != "" {
refOpts = append(refOpts,
WithReference_ProviderBy(c.ProvidedBy))
}
- if c.Params != nil && len(c.Params) > 0 {
+ if len(c.Params) > 0 {
newParams := make(map[string]string, len(c.Params))
for k, v := range c.Params {
newParams[k] = v
diff --git a/graceful_shutdown/shutdown.go b/graceful_shutdown/shutdown.go
index 84fbbe214..edb0ce0b5 100644
--- a/graceful_shutdown/shutdown.go
+++ b/graceful_shutdown/shutdown.go
@@ -86,23 +86,23 @@ func Init(opts ...Option) {
signal.Notify(signals, ShutdownSignals...)
go func() {
- select {
- case sig := <-signals:
- logger.Infof("get signal %s,
applicationConfig will shutdown.", sig)
- // gracefulShutdownOnce.Do(func() {
- time.AfterFunc(totalTimeout(), func() {
- logger.Warn("Shutdown
gracefully timeout, applicationConfig will shutdown immediately. ")
- os.Exit(0)
- })
- beforeShutdown()
- // those signals' original behavior is
exit with dump ths stack, so we try to keep the behavior
- for _, dumpSignal := range
DumpHeapShutdownSignals {
- if sig == dumpSignal {
-
debug.WriteHeapDump(os.Stdout.Fd())
- }
- }
+
+ sig := <-signals
+ logger.Infof("get signal %s, applicationConfig
will shutdown.", sig)
+ // gracefulShutdownOnce.Do(func() {
+ time.AfterFunc(totalTimeout(), func() {
+ logger.Warn("Shutdown gracefully
timeout, applicationConfig will shutdown immediately. ")
os.Exit(0)
+ })
+ beforeShutdown()
+ // those signals' original behavior is exit
with dump ths stack, so we try to keep the behavior
+ for _, dumpSignal := range
DumpHeapShutdownSignals {
+ if sig == dumpSignal {
+
debug.WriteHeapDump(os.Stdout.Fd())
+ }
}
+ os.Exit(0)
+
}()
}
})
diff --git a/metadata/client_test.go b/metadata/client_test.go
index 13c593a8e..2c8cc2b27 100644
--- a/metadata/client_test.go
+++ b/metadata/client_test.go
@@ -275,7 +275,7 @@ func (m *mockInvoker) Destroy() {
}
func (m *mockInvoker) Invoke(ctx context.Context, inv protocol.Invocation)
protocol.Result {
- args := m.Mock.Called()
+ args := m.Called()
meta := args.Get(0).(protocol.Result).Result().(*info.MetadataInfo)
reply := inv.Reply().(*info.MetadataInfo)
reply.App = meta.App
diff --git a/metadata/report/zookeeper/listener.go
b/metadata/report/zookeeper/listener.go
index e844f11c1..c91429bf3 100644
--- a/metadata/report/zookeeper/listener.go
+++ b/metadata/report/zookeeper/listener.go
@@ -140,6 +140,6 @@ func (l *CacheListener) pathToKey(path string) string {
if len(path) == 0 {
return path
}
- groupKey := strings.Replace(strings.Replace(path,
l.rootPath+constant.PathSeparator, "", -1), constant.PathSeparator,
constant.DotSeparator, -1)
+ groupKey := strings.ReplaceAll(strings.ReplaceAll(path,
l.rootPath+constant.PathSeparator, ""), constant.PathSeparator,
constant.DotSeparator)
return groupKey[strings.Index(groupKey, constant.DotSeparator)+1:]
}
diff --git a/options.go b/options.go
index 68f194169..4242a62e3 100644
--- a/options.go
+++ b/options.go
@@ -119,11 +119,10 @@ func (rc *InstanceOptions) init(opts ...InstanceOption)
error {
// init registry
registries := rcCompat.Registries
- if registries != nil {
- for _, reg := range registries {
- if err := reg.Init(); err != nil {
- return err
- }
+
+ for _, reg := range registries {
+ if err := reg.Init(); err != nil {
+ return err
}
}
diff --git a/protocol/dubbo/hessian2/hessian_request.go
b/protocol/dubbo/hessian2/hessian_request.go
index fbc7a77f0..42481a304 100644
--- a/protocol/dubbo/hessian2/hessian_request.go
+++ b/protocol/dubbo/hessian2/hessian_request.go
@@ -50,10 +50,10 @@ func getArgsTypeList(args []any) (string, error) {
if !strings.Contains(typ, ".") {
types += typ
} else if strings.Index(typ, "[") == 0 {
- types += strings.Replace(typ, ".", "/", -1)
+ types += strings.ReplaceAll(typ, ".", "/")
} else {
// java.util.List -> Ljava/util/List;
- types += "L" + strings.Replace(typ, ".", "/", -1) + ";"
+ types += "L" + strings.ReplaceAll(typ, ".", "/") + ";"
}
}
diff --git a/protocol/dubbo/hessian2/java_class.go
b/protocol/dubbo/hessian2/java_class.go
index dc75d1343..4f51180f3 100644
--- a/protocol/dubbo/hessian2/java_class.go
+++ b/protocol/dubbo/hessian2/java_class.go
@@ -176,7 +176,7 @@ func GetClassDesc(v any) string {
// return "java.util.HashMap"
return "java.util.Map"
case hessian.POJOEnum:
- return v.(hessian.POJOEnum).JavaClassName()
+ return v.JavaClassName()
// Serialized tags for complex types
default:
t := reflect.TypeOf(v)
diff --git a/protocol/dubbo/impl/hessian.go b/protocol/dubbo/impl/hessian.go
index 29db07a85..c9c7e82f0 100644
--- a/protocol/dubbo/impl/hessian.go
+++ b/protocol/dubbo/impl/hessian.go
@@ -409,10 +409,10 @@ func GetArgsTypeList(args []any) (string, error) {
if !strings.Contains(typ, ".") {
types += typ
} else if strings.Index(typ, "[") == 0 {
- types += strings.Replace(typ, ".", "/", -1)
+ types += strings.ReplaceAll(typ, ".", "/")
} else {
// java.util.List -> Ljava/util/List;
- types += "L" + strings.Replace(typ, ".", "/", -1) + ";"
+ types += "L" + strings.ReplaceAll(typ, ".", "/") + ";"
}
}
@@ -484,7 +484,7 @@ func getArgType(v any) string {
// return "java.util.HashMap"
return "java.util.Map"
case hessian.POJOEnum:
- return v.(hessian.POJOEnum).JavaClassName()
+ return v.JavaClassName()
case *int8:
return "java.lang.Byte"
case *int16:
diff --git a/protocol/dubbo3/dubbo3_protocol.go
b/protocol/dubbo3/dubbo3_protocol.go
index 3bc9c3805..10267e1b8 100644
--- a/protocol/dubbo3/dubbo3_protocol.go
+++ b/protocol/dubbo3/dubbo3_protocol.go
@@ -152,7 +152,7 @@ func (dp *DubboProtocol) Destroy() {
dp.serverLock.Lock()
defer dp.serverLock.Unlock()
// Stop all server
- for k, _ := range dp.serverMap {
+ for k := range dp.serverMap {
keyList = append(keyList, k)
}
for _, v := range keyList {
diff --git a/protocol/grpc/codec.go b/protocol/grpc/codec.go
index a97db8ce4..df6d2ff27 100644
--- a/protocol/grpc/codec.go
+++ b/protocol/grpc/codec.go
@@ -50,7 +50,7 @@ type grpcJson struct {
// Name implements grpc encoding package Codec interface method,
// returns the name of the Codec implementation.
-func (_ grpcJson) Name() string {
+func (grpcJson) Name() string {
return codecJson
}
diff --git a/protocol/grpc/protoc-gen-dubbo/plugin/dubbo/dubbo.go
b/protocol/grpc/protoc-gen-dubbo/plugin/dubbo/dubbo.go
index a48d63eb3..cd7e31e3a 100644
--- a/protocol/grpc/protoc-gen-dubbo/plugin/dubbo/dubbo.go
+++ b/protocol/grpc/protoc-gen-dubbo/plugin/dubbo/dubbo.go
@@ -81,14 +81,14 @@ func (g *dubboGrpc) P(args ...any) { g.gen.P(args...) }
// Generate generates code for the services in the given file.
// be consistent with grpc plugin
func (g *dubboGrpc) Generate(file *generator.FileDescriptor) {
- if len(file.FileDescriptorProto.Service) == 0 {
+ if len(file.Service) == 0 {
return
}
contextPkg = string(g.gen.AddImport(contextPkgPath))
grpcPkg = string(g.gen.AddImport(grpcPkgPath))
- for i, service := range file.FileDescriptorProto.Service {
+ for i, service := range file.Service {
g.generateService(file, service, i)
}
}
diff --git a/protocol/jsonrpc/json.go b/protocol/jsonrpc/json.go
index 758503543..bc1fa630d 100644
--- a/protocol/jsonrpc/json.go
+++ b/protocol/jsonrpc/json.go
@@ -230,7 +230,7 @@ func (r *serverRequest) UnmarshalJSON(raw []byte) error {
}
_, okID := o["id"]
_, okParams := o["params"]
- if len(o) == 3 && !(okID || okParams) || len(o) == 4 && !(okID &&
okParams) || len(o) > 4 {
+ if len(o) == 3 && (!okID && !okParams) || len(o) == 4 && (!okID ||
!okParams) || len(o) > 4 {
return perrors.New("bad request")
}
if r.Version != Version {
diff --git a/protocol/protocolwrapper/protocol_filter_wrapper.go
b/protocol/protocolwrapper/protocol_filter_wrapper.go
index 6c1023a0e..12dcdac08 100644
--- a/protocol/protocolwrapper/protocol_filter_wrapper.go
+++ b/protocol/protocolwrapper/protocol_filter_wrapper.go
@@ -89,14 +89,15 @@ func BuildInvokerChain(invoker protocol.Invoker, key
string) protocol.Invoker {
fi := &FilterInvoker{next: next, invoker: invoker, filter: flt}
next = fi
}
-
- if key == constant.ServiceFilterKey {
+ switch key {
+ case constant.ServiceFilterKey:
logger.Debugf("[BuildInvokerChain] The provider invocation link
is %s, invoker: %s",
strings.Join(append(filterNames, "proxyInvoker"), " ->
"), invoker)
- } else if key == constant.ReferenceFilterKey {
+ case constant.ReferenceFilterKey:
logger.Debugf("[BuildInvokerChain] The consumer filters are %s,
invoker: %s",
strings.Join(append(filterNames, "proxyInvoker"), " ->
"), invoker)
}
+
return next
}
diff --git a/protocol/rest/server/rest_server.go
b/protocol/rest/server/rest_server.go
index 78a33c097..eba29a734 100644
--- a/protocol/rest/server/rest_server.go
+++ b/protocol/rest/server/rest_server.go
@@ -38,7 +38,7 @@ import (
rest_config "dubbo.apache.org/dubbo-go/v3/protocol/rest/config"
)
-const parseParameterErrorStr = "An error occurred while parsing parameters on
the server"
+const parseParameterErrorStr = "an error occurred while parsing parameters on
the server"
// RestServer user can implement this server interface
type RestServer interface {
@@ -259,22 +259,24 @@ func assembleArgsFromQueryParams(methodConfig
*rest_config.RestMethodConfig, arg
t = t.Elem()
kind = t.Kind()
}
- if kind == reflect.Slice {
+ switch kind {
+ case reflect.Slice:
param = req.QueryParameters(v)
- } else if kind == reflect.String {
+ case reflect.String:
param = req.QueryParameter(v)
- } else if kind == reflect.Int {
+ case reflect.Int:
param, err = strconv.Atoi(req.QueryParameter(v))
- } else if kind == reflect.Int32 {
+ case reflect.Int32:
i64, err = strconv.ParseInt(req.QueryParameter(v), 10,
32)
if err == nil {
param = int32(i64)
}
- } else if kind == reflect.Int64 {
+ case reflect.Int64:
param, err = strconv.ParseInt(req.QueryParameter(v),
10, 64)
- } else {
+ default:
return perrors.Errorf("[Go restful] Query param parse
error, the index %v args's type isn't int or string or slice", k)
}
+
if err != nil {
return perrors.Errorf("[Go restful] Query param parse
error, error:%v", perrors.WithStack(err))
}
@@ -300,20 +302,23 @@ func assembleArgsFromPathParams(methodConfig
*rest_config.RestMethodConfig, args
t = t.Elem()
kind = t.Kind()
}
- if kind == reflect.Int {
+
+ switch kind {
+ case reflect.Int:
param, err = strconv.Atoi(req.PathParameter(v))
- } else if kind == reflect.Int32 {
+ case reflect.Int32:
i64, err = strconv.ParseInt(req.PathParameter(v), 10,
32)
if err == nil {
param = int32(i64)
}
- } else if kind == reflect.Int64 {
+ case reflect.Int64:
param, err = strconv.ParseInt(req.PathParameter(v), 10,
64)
- } else if kind == reflect.String {
+ case reflect.String:
param = req.PathParameter(v)
- } else {
+ default:
return perrors.Errorf("[Go restful] Path param parse
error, the index %v args's type isn't int or string", k)
}
+
if err != nil {
return perrors.Errorf("[Go restful] Path param parse
error, error is %v", perrors.WithStack(err))
}
diff --git a/protocol/rpc_status.go b/protocol/rpc_status.go
index e3b5c5d5e..5d301093c 100644
--- a/protocol/rpc_status.go
+++ b/protocol/rpc_status.go
@@ -265,7 +265,7 @@ func TryRefreshBlackList() {
go func(ivks []Invoker, i int) {
defer wg.Done()
for j := range ivks {
- if j%3-i == 0 &&
ivks[j].(Invoker).IsAvailable() {
+ if j%3-i == 0 && ivks[j].IsAvailable() {
RemoveInvokerUnhealthyStatus(ivks[i])
}
}
diff --git a/protocol/triple/triple_protocol/codec.go
b/protocol/triple/triple_protocol/codec.go
index 1d885cf8c..343e93d9b 100644
--- a/protocol/triple/triple_protocol/codec.go
+++ b/protocol/triple/triple_protocol/codec.go
@@ -150,7 +150,7 @@ func (c *protoJSONCodec) Marshal(message any) ([]byte,
error) {
if !ok {
return nil, errNotProto(message)
}
- var options protojson.MarshalOptions = protojson.MarshalOptions{
+ var options = protojson.MarshalOptions{
UseProtoNames: true,
}
return options.Marshal(protoMessage)
@@ -356,7 +356,7 @@ func getArgType(v any) string {
return "V"
}
- switch v.(type) {
+ switch v := v.(type) {
// Serialized tags for base types
case nil:
return "V"
@@ -414,7 +414,7 @@ func getArgType(v any) string {
// return "java.util.HashMap"
return "java.util.Map"
case hessian.POJOEnum:
- return v.(hessian.POJOEnum).JavaClassName()
+ return v.JavaClassName()
// Serialized tags for complex types
default:
t := reflect.TypeOf(v)
diff --git a/protocol/triple/triple_protocol/handler_compat.go
b/protocol/triple/triple_protocol/handler_compat.go
index 9839986ee..7b65e3fdc 100644
--- a/protocol/triple/triple_protocol/handler_compat.go
+++ b/protocol/triple/triple_protocol/handler_compat.go
@@ -80,11 +80,11 @@ func (t *tripleCompatInterceptor)
compatUnaryServerInterceptor(ctx context.Conte
resp := NewResponse(dubbo3Resp.Rest)
trailer := make(http.Header)
for key, valRaw := range dubbo3Resp.Attachments() {
- switch valRaw.(type) {
+ switch valRaw := valRaw.(type) {
case string:
- trailer[key] = []string{valRaw.(string)}
+ trailer[key] = []string{valRaw}
case []string:
- trailer[key] = valRaw.([]string)
+ trailer[key] = valRaw
default:
panic(fmt.Sprintf("unsupported attachment value
type %T", valRaw))
}
diff --git a/protocol/triple/triple_protocol/handler_stream_compat.go
b/protocol/triple/triple_protocol/handler_stream_compat.go
index 85f4c8941..70130f18b 100644
--- a/protocol/triple/triple_protocol/handler_stream_compat.go
+++ b/protocol/triple/triple_protocol/handler_stream_compat.go
@@ -47,7 +47,6 @@ func (c *compatHandlerStream) SendHeader(md metadata.MD)
error {
func (c *compatHandlerStream) SetTrailer(md metadata.MD) {
// todo(DMwangnima): add trailer method for streaming
- return
}
func (c *compatHandlerStream) Context() context.Context {
diff --git a/protocol/triple/triple_protocol/header.go
b/protocol/triple/triple_protocol/header.go
index 791cf4a30..e46b0a93b 100644
--- a/protocol/triple/triple_protocol/header.go
+++ b/protocol/triple/triple_protocol/header.go
@@ -102,11 +102,11 @@ func newIncomingContext(ctx context.Context, data
http.Header) context.Context {
if !ok {
extraData = map[string]http.Header{}
}
- if data != nil {
- for key, vals := range data {
- header[strings.ToLower(key)] = vals
- }
+
+ for key, vals := range data {
+ header[strings.ToLower(key)] = vals
}
+
extraData[headerIncomingKey] = header
return context.WithValue(ctx, extraDataKey{}, extraData)
}
@@ -117,11 +117,11 @@ func newIncomingContext(ctx context.Context, data
http.Header) context.Context {
// Please refer to
https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md#sending-metadata.
func NewOutgoingContext(ctx context.Context, data http.Header) context.Context
{
var header = http.Header{}
- if data != nil {
- for key, vals := range data {
- header[strings.ToLower(key)] = vals
- }
+
+ for key, vals := range data {
+ header[strings.ToLower(key)] = vals
}
+
extraData, ok := ctx.Value(extraDataKey{}).(map[string]http.Header)
if !ok {
extraData = map[string]http.Header{}
diff --git a/protocol/triple/triple_protocol/protocol_grpc.go
b/protocol/triple/triple_protocol/protocol_grpc.go
index 8049c3038..13dc1fff3 100644
--- a/protocol/triple/triple_protocol/protocol_grpc.go
+++ b/protocol/triple/triple_protocol/protocol_grpc.go
@@ -481,9 +481,7 @@ func (hc *grpcHandlerConn) ExportableHeader() http.Header {
continue
}
cloneVals := make([]string, len(vals))
- for i, val := range vals {
- cloneVals[i] = val
- }
+ copy(cloneVals, vals)
res[key] = cloneVals
}
@@ -641,8 +639,8 @@ type grpcMarshaler struct {
}
func (m *grpcMarshaler) MarshalWebTrailers(trailer http.Header) *Error {
- raw := m.envelopeWriter.bufferPool.Get()
- defer m.envelopeWriter.bufferPool.Put(raw)
+ raw := m.bufferPool.Get()
+ defer m.bufferPool.Put(raw)
for key, values := range trailer {
// Per the Go specification, keys inserted during iteration may
be produced
// later in the iteration or may be skipped. For safety, avoid
mutating the
@@ -946,7 +944,7 @@ func grpcPercentEncodeSlow(bufferPool *bufferPool, msg
string, offset int) strin
for i := offset; i < len(msg); i++ {
c := msg[i]
if c < ' ' || c > '~' || c == '%' {
- out.WriteString(fmt.Sprintf("%%%02X", c))
+ fmt.Fprintf(out, "%%%02X", c)
continue
}
out.WriteByte(c)
diff --git a/registry/base_registry.go b/registry/base_registry.go
index 78986930f..40c7675fb 100644
--- a/registry/base_registry.go
+++ b/registry/base_registry.go
@@ -264,7 +264,7 @@ func (r *BaseRegistry) providerRegistry(c *common.URL,
params url.Values, f crea
if c.Path == "" || len(c.Methods) == 0 {
return "", "", perrors.Errorf("conf{Path:%s, Methods:%s}",
c.Path, c.Methods)
}
- dubboPath = fmt.Sprintf("/%s/%s/%s",
r.URL.GetParam(constant.RegistryGroupKey, "dubbo"), r.service(c),
common.DubboNodes[common.PROVIDER])
+ dubboPath = fmt.Sprintf("/%s/%s/%s",
r.GetParam(constant.RegistryGroupKey, "dubbo"), r.service(c),
common.DubboNodes[common.PROVIDER])
if f != nil {
err = f(dubboPath)
}
@@ -310,7 +310,7 @@ func (r *BaseRegistry) consumerRegistry(c *common.URL,
params url.Values, f crea
rawURL string
err error
)
- dubboPath = fmt.Sprintf("/%s/%s/%s",
r.URL.GetParam(constant.RegistryGroupKey, "dubbo"), r.service(c),
common.DubboNodes[common.CONSUMER])
+ dubboPath = fmt.Sprintf("/%s/%s/%s",
r.GetParam(constant.RegistryGroupKey, "dubbo"), r.service(c),
common.DubboNodes[common.CONSUMER])
if f != nil {
err = f(dubboPath)
diff --git a/registry/directory/directory.go b/registry/directory/directory.go
index 634baada0..bb06c27a0 100644
--- a/registry/directory/directory.go
+++ b/registry/directory/directory.go
@@ -92,7 +92,7 @@ func NewRegistryDirectory(url *common.URL, registry
registry.Registry) (director
dir.consumerURL = dir.getConsumerUrl(url.SubURL)
if routerChain, err := chain.NewRouterChain(); err == nil {
- dir.Directory.SetRouterChain(routerChain)
+ dir.SetRouterChain(routerChain)
} else {
logger.Warnf("fail to create router chain with url: %s, err is:
%v", url.SubURL, err)
}
@@ -476,7 +476,7 @@ func (dir *RegistryDirectory) List(invocation
protocol.Invocation) []protocol.In
// IsAvailable whether the directory is available
func (dir *RegistryDirectory) IsAvailable() bool {
- if dir.Directory.IsDestroyed() {
+ if dir.IsDestroyed() {
return false
}
@@ -492,7 +492,7 @@ func (dir *RegistryDirectory) IsAvailable() bool {
// Destroy method
func (dir *RegistryDirectory) Destroy() {
// TODO:unregister & unsubscribe
- dir.Directory.DoDestroy(func() {
+ dir.DoDestroy(func() {
if dir.RegisteredUrl != nil {
err := dir.registry.UnRegister(dir.RegisteredUrl)
if err != nil {
@@ -622,7 +622,7 @@ func (dir *ServiceDiscoveryRegistryDirectory) Subscribe(url
*common.URL) error {
}
urlToReg := getConsumerUrlToRegistry(url)
- err := dir.RegistryDirectory.registry.Register(urlToReg)
+ err := dir.registry.Register(urlToReg)
if err != nil {
logger.Errorf("consumer service %v register registry %v error,
error message is %s",
url.String(), dir.registry.GetURL().String(),
err.Error())
diff --git a/registry/directory/directory_test.go
b/registry/directory/directory_test.go
index bcc3a74fb..60449d414 100644
--- a/registry/directory/directory_test.go
+++ b/registry/directory/directory_test.go
@@ -112,7 +112,7 @@ Loop1:
Loop2:
for {
if len(registryDirectory.cacheInvokers) > 0 {
- if "mock1" ==
registryDirectory.cacheInvokers[0].GetURL().GetParam(constant.ClusterKey, "") {
+ if
registryDirectory.cacheInvokers[0].GetURL().GetParam(constant.ClusterKey, "")
== "mock1" {
assert.Len(t,
registryDirectory.cacheInvokers, 1)
assert.True(t, true)
break Loop2
diff --git a/registry/etcdv3/service_discovery.go
b/registry/etcdv3/service_discovery.go
index 8421a6325..dd3d88cd9 100644
--- a/registry/etcdv3/service_discovery.go
+++ b/registry/etcdv3/service_discovery.go
@@ -288,8 +288,8 @@ func (e *etcdV3ServiceDiscovery) DataChange(eventType
remoting.Event) bool {
name := instance.ServiceName
instances := e.GetInstances(name)
for _, lis := range
e.instanceListenerMap[instance.ServiceName].Values() {
- var instanceLis registry.ServiceInstancesChangedListener
- instanceLis =
lis.(registry.ServiceInstancesChangedListener)
+
+ instanceLis :=
lis.(registry.ServiceInstancesChangedListener)
err =
instanceLis.OnEvent(registry.NewServiceInstancesChangedEvent(name, instances))
}
if err != nil {
diff --git a/registry/nacos/registry.go b/registry/nacos/registry.go
index 7f5ec246b..1eb0d39d0 100644
--- a/registry/nacos/registry.go
+++ b/registry/nacos/registry.go
@@ -128,7 +128,7 @@ func createRegisterParam(url *common.URL, serviceName
string, groupName string)
func (nr *nacosRegistry) Register(url *common.URL) error {
start := time.Now()
serviceName := getServiceName(url)
- groupName := nr.URL.GetParam(constant.NacosGroupKey, defaultGroup)
+ groupName := nr.GetParam(constant.NacosGroupKey, defaultGroup)
param := createRegisterParam(url, serviceName, groupName)
logger.Infof("[Nacos Registry] Registry instance with param = %+v",
param)
isRegistry, err := nr.namingClient.Client().RegisterInstance(param)
@@ -158,7 +158,7 @@ func createDeregisterParam(url *common.URL, serviceName
string, groupName string
// UnRegister returns nil if unregister successfully. If not, returns an error.
func (nr *nacosRegistry) UnRegister(url *common.URL) error {
serviceName := getServiceName(url)
- groupName := nr.URL.GetParam(constant.NacosGroupKey, defaultGroup)
+ groupName := nr.GetParam(constant.NacosGroupKey, defaultGroup)
param := createDeregisterParam(url, serviceName, groupName)
isDeRegistry, err := nr.namingClient.Client().DeregisterInstance(param)
if err != nil {
@@ -209,7 +209,7 @@ func (nr *nacosRegistry) scheduledLookUp(url *common.URL,
notifyListener registr
}
func (nr *nacosRegistry) subscribeAll(url *common.URL, notifyListener
registry.NotifyListener) {
- groupName := nr.URL.GetParam(constant.RegistryGroupKey, defaultGroup)
+ groupName := nr.GetParam(constant.RegistryGroupKey, defaultGroup)
serviceNames, err := nr.getAllSubscribeServiceNames(url)
if err != nil {
logger.Warnf("getAllServices() = err:%v",
perrors.WithStack(err))
@@ -301,7 +301,7 @@ func (nr *nacosRegistry) handleServiceEvents(listener
registry.Listener, notifyL
// UnSubscribe :
func (nr *nacosRegistry) UnSubscribe(url *common.URL, _
registry.NotifyListener) error {
- param := createSubscribeParam(getSubscribeName(url),
nr.URL.GetParam(constant.RegistryGroupKey, defaultGroup), nil)
+ param := createSubscribeParam(getSubscribeName(url),
nr.GetParam(constant.RegistryGroupKey, defaultGroup), nil)
if param == nil {
return nil
}
diff --git a/registry/nacos/service_discovery.go
b/registry/nacos/service_discovery.go
index c299213bd..7628b1ac4 100644
--- a/registry/nacos/service_discovery.go
+++ b/registry/nacos/service_discovery.go
@@ -290,8 +290,7 @@ func (n *nacosServiceDiscovery) AddListener(listener
registry.ServiceInstancesCh
var e error
for _, lis := range
n.instanceListenerMap[serviceName].Values() {
- var instanceListener
registry.ServiceInstancesChangedListener
- instanceListener =
lis.(registry.ServiceInstancesChangedListener)
+ instanceListener :=
lis.(registry.ServiceInstancesChangedListener)
e =
instanceListener.OnEvent(registry.NewServiceInstancesChangedEvent(serviceName,
instances))
}
diff --git a/registry/options.go b/registry/options.go
index 6638b438d..e9f1fb285 100644
--- a/registry/options.go
+++ b/registry/options.go
@@ -18,7 +18,6 @@
package registry
import (
- "fmt"
"strings"
"time"
)
@@ -47,7 +46,7 @@ func NewOptions(opts ...Option) *Options {
}
if defOpts.Registry.Protocol == "" {
- panic(fmt.Sprintf("Please specify registry, eg.
WithZookeeper()"))
+ panic("Please specify registry, eg. WithZookeeper()")
}
if defOpts.ID == "" {
defOpts.ID = defOpts.Registry.Protocol
diff --git a/registry/polaris/core.go b/registry/polaris/core.go
index f2b35332a..1db3ef04f 100644
--- a/registry/polaris/core.go
+++ b/registry/polaris/core.go
@@ -85,35 +85,32 @@ func (watcher *PolarisServiceWatcher) startWatch() {
ConfigType: remoting.EventTypeAdd,
})
- for {
- select {
- case event := <-resp.EventChannel:
- eType := event.GetSubScribeEventType()
- if eType == internalapi.EventInstance {
- insEvent := event.(*model.InstanceEvent)
-
- if insEvent.AddEvent != nil {
-
watcher.notifyAllSubscriber(&config_center.ConfigChangeEvent{
- Value:
insEvent.AddEvent.Instances,
- ConfigType:
remoting.EventTypeAdd,
- })
- }
- if insEvent.UpdateEvent != nil {
- instances :=
make([]model.Instance, len(insEvent.UpdateEvent.UpdateList))
- for i := range
insEvent.UpdateEvent.UpdateList {
- instances[i] =
insEvent.UpdateEvent.UpdateList[i].After
- }
-
watcher.notifyAllSubscriber(&config_center.ConfigChangeEvent{
- Value: instances,
- ConfigType:
remoting.EventTypeUpdate,
- })
- }
- if insEvent.DeleteEvent != nil {
-
watcher.notifyAllSubscriber(&config_center.ConfigChangeEvent{
- Value:
insEvent.DeleteEvent.Instances,
- ConfigType:
remoting.EventTypeDel,
- })
+ for event := range resp.EventChannel {
+ eType := event.GetSubScribeEventType()
+ if eType == internalapi.EventInstance {
+ insEvent := event.(*model.InstanceEvent)
+
+ if insEvent.AddEvent != nil {
+
watcher.notifyAllSubscriber(&config_center.ConfigChangeEvent{
+ Value:
insEvent.AddEvent.Instances,
+ ConfigType:
remoting.EventTypeAdd,
+ })
+ }
+ if insEvent.UpdateEvent != nil {
+ instances := make([]model.Instance,
len(insEvent.UpdateEvent.UpdateList))
+ for i := range
insEvent.UpdateEvent.UpdateList {
+ instances[i] =
insEvent.UpdateEvent.UpdateList[i].After
}
+
watcher.notifyAllSubscriber(&config_center.ConfigChangeEvent{
+ Value: instances,
+ ConfigType:
remoting.EventTypeUpdate,
+ })
+ }
+ if insEvent.DeleteEvent != nil {
+
watcher.notifyAllSubscriber(&config_center.ConfigChangeEvent{
+ Value:
insEvent.DeleteEvent.Instances,
+ ConfigType:
remoting.EventTypeDel,
+ })
}
}
}
diff --git a/registry/polaris/registry.go b/registry/polaris/registry.go
index dad5ea058..41f754f10 100644
--- a/registry/polaris/registry.go
+++ b/registry/polaris/registry.go
@@ -236,7 +236,6 @@ func (pr *polarisRegistry) Destroy() {
logger.Errorf("Deregister Polaris URL:%+v err:%v", url,
err.Error())
}
}
- return
}
// IsAvailable always return true when use polaris
diff --git a/registry/polaris/service_discovery.go
b/registry/polaris/service_discovery.go
index 96e27d829..c8971f485 100644
--- a/registry/polaris/service_discovery.go
+++ b/registry/polaris/service_discovery.go
@@ -157,9 +157,7 @@ func (polaris *polarisServiceDiscovery) Unregister(instance
registry.ServiceInst
polaris.instanceLock.Lock()
defer polaris.instanceLock.Unlock()
key := getInstanceKey(polaris.namespace, instance)
- if _, exist := polaris.registryInstances[key]; exist {
- delete(polaris.registryInstances, key)
- }
+ delete(polaris.registryInstances, key)
}()
err :=
polaris.provider.Deregister(convertToDeregisterInstance(polaris.namespace,
instance))
diff --git a/registry/protocol/protocol.go b/registry/protocol/protocol.go
index 9109ae371..68ccdab8a 100644
--- a/registry/protocol/protocol.go
+++ b/registry/protocol/protocol.go
@@ -350,9 +350,9 @@ func isMatched(providerUrl *common.URL, consumerUrl
*common.URL) bool {
consumerInterface := consumerUrl.GetParam(constant.InterfaceKey,
consumerUrl.Path)
providerInterface := providerUrl.GetParam(constant.InterfaceKey,
providerUrl.Path)
- if !(constant.AnyValue == consumerInterface ||
- constant.AnyValue == providerInterface ||
- providerInterface == consumerInterface) {
+ if constant.AnyValue != consumerInterface &&
+ constant.AnyValue != providerInterface &&
+ providerInterface != consumerInterface {
return false
}
@@ -416,11 +416,9 @@ func (proto *registryProtocol) Destroy() {
// close all protocol server after consumerUpdateWait +
stepTimeout(max time wait during
// waitAndAcceptNewRequests procedure)
go func() {
- select {
- case <-time.After(config.GetShutDown().GetStepTimeout()
+ config.GetShutDown().GetConsumerUpdateWaitTime()):
- exporter.UnExport()
- proto.bounds.Delete(key)
- }
+ <-time.After(config.GetShutDown().GetStepTimeout() +
config.GetShutDown().GetConsumerUpdateWaitTime())
+ exporter.UnExport()
+ proto.bounds.Delete(key)
}()
return true
})
diff --git
a/registry/servicediscovery/customizer/protocol_ports_metadata_customizer.go
b/registry/servicediscovery/customizer/protocol_ports_metadata_customizer.go
index a5d757ebf..f748259b2 100644
--- a/registry/servicediscovery/customizer/protocol_ports_metadata_customizer.go
+++ b/registry/servicediscovery/customizer/protocol_ports_metadata_customizer.go
@@ -53,7 +53,7 @@ func (p *ProtocolPortsMetadataCustomizer) Customize(instance
registry.ServiceIns
logger.Errorf("get metadata exported service url is error, %v",
err)
return
}
- if list == nil || len(list) == 0 {
+ if len(list) == 0 {
// client side
return
}
diff --git
a/registry/servicediscovery/service_instances_changed_listener_impl.go
b/registry/servicediscovery/service_instances_changed_listener_impl.go
index 7ec3197a5..24618054a 100644
--- a/registry/servicediscovery/service_instances_changed_listener_impl.go
+++ b/registry/servicediscovery/service_instances_changed_listener_impl.go
@@ -106,7 +106,7 @@ func (lstn *ServiceInstancesChangedListenerImpl) OnEvent(e
observer.Event) error
continue
}
revision :=
instance.GetMetadata()[constant.ExportedServicesRevisionPropertyName]
- if "0" == revision {
+ if revision == "0" {
logger.Infof("Find instance without valid
service metadata: %s", instance.GetHost())
continue
}
diff --git
a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
index 6823662fb..438f29a0c 100644
---
a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
+++
b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
@@ -37,7 +37,7 @@ func init() {
type RestSubscribedURLsSynthesizer struct{}
func (r RestSubscribedURLsSynthesizer) Support(subscribedURL *common.URL) bool
{
- return "rest" == subscribedURL.Protocol
+ return subscribedURL.Protocol == "rest"
}
func (r RestSubscribedURLsSynthesizer) Synthesize(subscribedURL *common.URL,
serviceInstances []registry.ServiceInstance) []*common.URL {
diff --git a/registry/zookeeper/listener.go b/registry/zookeeper/listener.go
index ee8e56ddc..6c2aefbe2 100644
--- a/registry/zookeeper/listener.go
+++ b/registry/zookeeper/listener.go
@@ -155,7 +155,7 @@ func (l *RegistryConfigurationListener) Next()
(*registry.ServiceEvent, error) {
case <-l.close:
return nil, perrors.New("listener has been closed")
case <-l.registry.Done():
- logger.Warnf("zk consumer register has quit, so zk
event listener exit now. (registry url {%v}", l.registry.BaseRegistry.URL)
+ logger.Warnf("zk consumer register has quit, so zk
event listener exit now. (registry url {%v}", l.registry.URL)
return nil, perrors.New("zookeeper registry, (registry
url{%v}) stopped")
case val := <-l.events.Out():
e, _ := val.(*config_center.ConfigChangeEvent)
diff --git a/registry/zookeeper/registry.go b/registry/zookeeper/registry.go
index a743f71a8..594d64bc4 100644
--- a/registry/zookeeper/registry.go
+++ b/registry/zookeeper/registry.go
@@ -134,7 +134,7 @@ func (r *zkRegistry) InitListeners() {
regConfigListener.Close()
}
newDataListener.SubscribeURL(regConfigListener.subscribeURL,
NewRegistryConfigurationListener(r.client, r, regConfigListener.subscribeURL))
- go
r.listener.ListenServiceEvent(regConfigListener.subscribeURL,
fmt.Sprintf("/%s/%s/"+constant.DefaultCategory,
r.URL.GetParam(constant.RegistryGroupKey, "dubbo"),
url.QueryEscape(regConfigListener.subscribeURL.Service())), newDataListener)
+ go
r.listener.ListenServiceEvent(regConfigListener.subscribeURL,
fmt.Sprintf("/%s/%s/"+constant.DefaultCategory,
r.GetParam(constant.RegistryGroupKey, "dubbo"),
url.QueryEscape(regConfigListener.subscribeURL.Service())), newDataListener)
}
}
@@ -287,7 +287,7 @@ func (r *zkRegistry) getListener(conf *common.URL)
(*RegistryConfigurationListen
// Interested register to dataconfig.
r.dataListener.SubscribeURL(conf, zkListener)
- go r.listener.ListenServiceEvent(conf,
fmt.Sprintf("/%s/%s/"+constant.DefaultCategory,
r.URL.GetParam(constant.RegistryGroupKey, "dubbo"),
url.QueryEscape(conf.Service())), r.dataListener)
+ go r.listener.ListenServiceEvent(conf,
fmt.Sprintf("/%s/%s/"+constant.DefaultCategory,
r.GetParam(constant.RegistryGroupKey, "dubbo"),
url.QueryEscape(conf.Service())), r.dataListener)
return zkListener, nil
}
diff --git a/registry/zookeeper/service_discovery.go
b/registry/zookeeper/service_discovery.go
index 9da2b23fc..be64dffba 100644
--- a/registry/zookeeper/service_discovery.go
+++ b/registry/zookeeper/service_discovery.go
@@ -277,8 +277,7 @@ func (zksd *zookeeperServiceDiscovery) DataChange(eventType
remoting.Event) bool
var err error
instances := zksd.GetInstances(serviceName)
for _, lis := range zksd.instanceListenerMap[serviceName].Values() {
- var instanceListener registry.ServiceInstancesChangedListener
- instanceListener =
lis.(registry.ServiceInstancesChangedListener)
+ instanceListener :=
lis.(registry.ServiceInstancesChangedListener)
err =
instanceListener.OnEvent(registry.NewServiceInstancesChangedEvent(serviceName,
instances))
}
diff --git a/remoting/polaris/builder.go b/remoting/polaris/builder.go
index 389e80466..30ab31d9e 100644
--- a/remoting/polaris/builder.go
+++ b/remoting/polaris/builder.go
@@ -105,7 +105,7 @@ func GetNamespace() string {
// InitSDKContext inits polaris SDKContext by URL
func InitSDKContext(url *common.URL) error {
if url == nil {
- return errors.New("url is empty!")
+ return errors.New("url is empty")
}
openPolarisAbility = true
diff --git a/server/options.go b/server/options.go
index f28e97400..0f6ef9ad1 100644
--- a/server/options.go
+++ b/server/options.go
@@ -251,9 +251,9 @@ func WithServerNotRegister() ServerOption {
}
}
-func WithServerWarmup(milliSeconds time.Duration) ServerOption {
+func WithServerWarmup(warmupDuration time.Duration) ServerOption {
return func(opts *ServerOptions) {
- opts.Provider.Warmup = milliSeconds.String()
+ opts.Provider.Warmup = warmupDuration.String()
}
}
@@ -551,7 +551,7 @@ func (svcOpts *ServiceOptions) init(srv *Server, opts
...ServiceOption) error {
if len(svc.RegistryIDs) <= 0 {
svc.RegistryIDs = svcOpts.Provider.RegistryIDs
}
- if svc.RegistryIDs == nil || len(svc.RegistryIDs) <= 0 {
+ if len(svc.RegistryIDs) <= 0 {
svc.NotRegister = true
}
@@ -751,9 +751,9 @@ func WithNotRegister() ServiceOption {
}
}
-func WithWarmup(milliSeconds time.Duration) ServiceOption {
+func WithWarmup(warmupDuration time.Duration) ServiceOption {
return func(opts *ServiceOptions) {
- opts.Service.Warmup = milliSeconds.String()
+ opts.Service.Warmup = warmupDuration.String()
}
}
diff --git a/server/server.go b/server/server.go
index 294656af7..ea2d5b9e5 100644
--- a/server/server.go
+++ b/server/server.go
@@ -129,9 +129,8 @@ func (s *Server) exportServices() (err error) {
newMethod.Name =
dubboutil.SwapCaseFirstRune(method.Name)
additionalMethods = append(additionalMethods,
newMethod)
}
- for _, additionalMethod := range additionalMethods {
- info.Methods = append(info.Methods,
additionalMethod)
- }
+
+ info.Methods = append(info.Methods,
additionalMethods...)
err = svcOpts.ExportWithInfo(info)
}