Merge pull request #1118 from wenxuwan/fix_type_error
add ut for config_loader file
diff --git a/cluster/cluster_impl/available_cluster_invoker_test.go b/cluster/cluster_impl/available_cluster_invoker_test.go
index 0631000..948f207 100644
--- a/cluster/cluster_impl/available_cluster_invoker_test.go
+++ b/cluster/cluster_impl/available_cluster_invoker_test.go
@@ -40,10 +40,8 @@
"github.com/apache/dubbo-go/protocol/mock"
)
-var (
- availableUrl, _ = common.NewURL(fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider",
- constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
-)
+var availableUrl, _ = common.NewURL(fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider",
+ constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
func registerAvailable(invoker *mock.MockInvoker) protocol.Invoker {
extension.SetLoadbalance("random", loadbalance.NewRandomLoadBalance)
diff --git a/cluster/cluster_impl/base_cluster_invoker.go b/cluster/cluster_impl/base_cluster_invoker.go
index 0d39bff..2df5f36 100644
--- a/cluster/cluster_impl/base_cluster_invoker.go
+++ b/cluster/cluster_impl/base_cluster_invoker.go
@@ -56,7 +56,7 @@
}
func (invoker *baseClusterInvoker) Destroy() {
- //this is must atom operation
+ // this is must atom operation
if invoker.destroyed.CAS(false, true) {
invoker.directory.Destroy()
}
@@ -69,7 +69,7 @@
return invoker.directory.IsAvailable()
}
-//check invokers availables
+// check invokers availables
func (invoker *baseClusterInvoker) checkInvokers(invokers []protocol.Invoker, invocation protocol.Invocation) error {
if len(invokers) == 0 {
ip := common.GetLocalIp()
@@ -78,10 +78,9 @@
invocation.MethodName(), invoker.directory.GetUrl().SubURL.Key(), invoker.directory.GetUrl().String(), ip, constant.Version)
}
return nil
-
}
-//check cluster invoker is destroyed or not
+// check cluster invoker is destroyed or not
func (invoker *baseClusterInvoker) checkWhetherDestroyed() error {
if invoker.destroyed.Load() {
ip := common.GetLocalIp()
@@ -99,7 +98,7 @@
url := invokers[0].GetUrl()
sticky := url.GetParamBool(constant.STICKY_KEY, false)
- //Get the service method sticky config if have
+ // Get the service method sticky config if have
sticky = url.GetMethodParamBool(invocation.MethodName(), constant.STICKY_KEY, sticky)
if invoker.stickyInvoker != nil && !isInvoked(invoker.stickyInvoker, invokers) {
@@ -135,7 +134,7 @@
selectedInvoker := lb.Select(invokers, invocation)
- //judge if the selected Invoker is invoked and available
+ // judge if the selected Invoker is invoked and available
if (!selectedInvoker.IsAvailable() && invoker.availablecheck) || isInvoked(selectedInvoker, invoked) {
protocol.SetInvokerUnhealthyStatus(selectedInvoker)
otherInvokers := getOtherInvokers(invokers, selectedInvoker)
@@ -193,10 +192,10 @@
url := invoker.GetUrl()
methodName := invocation.MethodName()
- //Get the service loadbalance config
+ // Get the service loadbalance config
lb := url.GetParam(constant.LOADBALANCE_KEY, constant.DEFAULT_LOADBALANCE)
- //Get the service method loadbalance config if have
+ // Get the service method loadbalance config if have
if v := url.GetMethodParam(methodName, constant.LOADBALANCE_KEY, ""); len(v) > 0 {
lb = v
}
diff --git a/cluster/cluster_impl/broadcast_cluster_invoker.go b/cluster/cluster_impl/broadcast_cluster_invoker.go
index b117dbb..52ae65c 100644
--- a/cluster/cluster_impl/broadcast_cluster_invoker.go
+++ b/cluster/cluster_impl/broadcast_cluster_invoker.go
@@ -20,6 +20,7 @@
import (
"context"
)
+
import (
"github.com/apache/dubbo-go/cluster"
"github.com/apache/dubbo-go/common/logger"
diff --git a/cluster/cluster_impl/broadcast_cluster_invoker_test.go b/cluster/cluster_impl/broadcast_cluster_invoker_test.go
index 08d0002..a654fb7 100644
--- a/cluster/cluster_impl/broadcast_cluster_invoker_test.go
+++ b/cluster/cluster_impl/broadcast_cluster_invoker_test.go
@@ -40,10 +40,8 @@
"github.com/apache/dubbo-go/protocol/mock"
)
-var (
- broadcastUrl, _ = common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
-)
+var broadcastUrl, _ = common.NewURL(
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
func registerBroadcast(mockInvokers ...*mock.MockInvoker) protocol.Invoker {
extension.SetLoadbalance("random", loadbalance.NewRandomLoadBalance)
diff --git a/cluster/cluster_impl/failback_cluster_invoker.go b/cluster/cluster_impl/failback_cluster_invoker.go
index 5e0d133..2ed1bae 100644
--- a/cluster/cluster_impl/failback_cluster_invoker.go
+++ b/cluster/cluster_impl/failback_cluster_invoker.go
@@ -137,10 +137,10 @@
return &protocol.RPCResult{}
}
- //Get the service loadbalance config
+ // Get the service loadbalance config
url := invokers[0].GetUrl()
lb := url.GetParam(constant.LOADBALANCE_KEY, constant.DEFAULT_LOADBALANCE)
- //Get the service method loadbalance config if have
+ // Get the service method loadbalance config if have
methodName := invocation.MethodName()
if v := url.GetMethodParam(methodName, constant.LOADBALANCE_KEY, ""); v != "" {
lb = v
@@ -149,7 +149,7 @@
loadBalance := extension.GetLoadbalance(lb)
invoked := make([]protocol.Invoker, 0, len(invokers))
ivk := invoker.doSelect(loadBalance, invocation, invokers, invoked)
- //DO INVOKE
+ // DO INVOKE
result := ivk.Invoke(ctx, invocation)
if result.Error() != nil {
invoker.once.Do(func() {
diff --git a/cluster/cluster_impl/failback_cluster_test.go b/cluster/cluster_impl/failback_cluster_test.go
index d36e16e..8fbd24f 100644
--- a/cluster/cluster_impl/failback_cluster_test.go
+++ b/cluster/cluster_impl/failback_cluster_test.go
@@ -42,10 +42,8 @@
"github.com/apache/dubbo-go/protocol/mock"
)
-var (
- failbackUrl, _ = common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
-)
+var failbackUrl, _ = common.NewURL(
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
// registerFailback register failbackCluster to cluster extension.
func registerFailback(invoker *mock.MockInvoker) protocol.Invoker {
diff --git a/cluster/cluster_impl/failfast_cluster_invoker.go b/cluster/cluster_impl/failfast_cluster_invoker.go
index d71ef5f..a7faa1b 100644
--- a/cluster/cluster_impl/failfast_cluster_invoker.go
+++ b/cluster/cluster_impl/failfast_cluster_invoker.go
@@ -20,6 +20,7 @@
import (
"context"
)
+
import (
"github.com/apache/dubbo-go/cluster"
"github.com/apache/dubbo-go/protocol"
diff --git a/cluster/cluster_impl/failfast_cluster_test.go b/cluster/cluster_impl/failfast_cluster_test.go
index 9ac06b8..6577c99 100644
--- a/cluster/cluster_impl/failfast_cluster_test.go
+++ b/cluster/cluster_impl/failfast_cluster_test.go
@@ -40,10 +40,8 @@
"github.com/apache/dubbo-go/protocol/mock"
)
-var (
- failfastUrl, _ = common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
-)
+var failfastUrl, _ = common.NewURL(
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
// registerFailfast register failfastCluster to cluster extension.
func registerFailfast(invoker *mock.MockInvoker) protocol.Invoker {
diff --git a/cluster/cluster_impl/failover_cluster_invoker.go b/cluster/cluster_impl/failover_cluster_invoker.go
index ca490e7..3d070c1 100644
--- a/cluster/cluster_impl/failover_cluster_invoker.go
+++ b/cluster/cluster_impl/failover_cluster_invoker.go
@@ -64,8 +64,8 @@
loadBalance := getLoadBalance(invokers[0], invocation)
for i := 0; i <= retries; i++ {
- //Reselect before retry to avoid a change of candidate `invokers`.
- //NOTE: if `invokers` changed, then `invoked` also lose accuracy.
+ // Reselect before retry to avoid a change of candidate `invokers`.
+ // NOTE: if `invokers` changed, then `invoked` also lose accuracy.
if i > 0 {
if err := invoker.checkWhetherDestroyed(); err != nil {
return &protocol.RPCResult{Err: err}
@@ -81,7 +81,7 @@
continue
}
invoked = append(invoked, ivk)
- //DO INVOKE
+ // DO INVOKE
result = ivk.Invoke(ctx, invocation)
if result.Error() != nil {
providers = append(providers, ivk.GetUrl().Key())
@@ -105,7 +105,8 @@
"Tried %v times of the providers %v (%v/%v)from the registry %v on the consumer %v using the dubbo version %v. "+
"Last error is %+v.", methodName, invokerSvc, retries, providers, len(providers), len(invokers),
invokerUrl, ip, constant.Version, result.Error().Error()),
- )}
+ ),
+ }
}
func getRetries(invokers []protocol.Invoker, methodName string) int {
@@ -114,9 +115,9 @@
}
url := invokers[0].GetUrl()
- //get reties
+ // get reties
retriesConfig := url.GetParam(constant.RETRIES_KEY, constant.DEFAULT_RETRIES)
- //Get the service method loadbalance config if have
+ // Get the service method loadbalance config if have
if v := url.GetMethodParam(methodName, constant.RETRIES_KEY, ""); len(v) != 0 {
retriesConfig = v
}
diff --git a/cluster/cluster_impl/failover_cluster_test.go b/cluster/cluster_impl/failover_cluster_test.go
index 3ea6232..dd43e0f 100644
--- a/cluster/cluster_impl/failover_cluster_test.go
+++ b/cluster/cluster_impl/failover_cluster_test.go
@@ -23,6 +23,7 @@
"net/url"
"testing"
)
+
import (
perrors "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
diff --git a/cluster/cluster_impl/failsafe_cluster_invoker.go b/cluster/cluster_impl/failsafe_cluster_invoker.go
index 27c59ff..29d8884 100644
--- a/cluster/cluster_impl/failsafe_cluster_invoker.go
+++ b/cluster/cluster_impl/failsafe_cluster_invoker.go
@@ -20,6 +20,7 @@
import (
"context"
)
+
import (
"github.com/apache/dubbo-go/cluster"
"github.com/apache/dubbo-go/common/constant"
@@ -56,9 +57,9 @@
url := invokers[0].GetUrl()
methodName := invocation.MethodName()
- //Get the service loadbalance config
+ // Get the service loadbalance config
lb := url.GetParam(constant.LOADBALANCE_KEY, constant.DEFAULT_LOADBALANCE)
- //Get the service method loadbalance config if have
+ // Get the service method loadbalance config if have
if v := url.GetMethodParam(methodName, constant.LOADBALANCE_KEY, ""); v != "" {
lb = v
}
@@ -68,7 +69,7 @@
var result protocol.Result
ivk := invoker.doSelect(loadbalance, invocation, invokers, invoked)
- //DO INVOKE
+ // DO INVOKE
result = ivk.Invoke(ctx, invocation)
if result.Error() != nil {
// ignore
diff --git a/cluster/cluster_impl/failsafe_cluster_test.go b/cluster/cluster_impl/failsafe_cluster_test.go
index 5e208bd..95e1145 100644
--- a/cluster/cluster_impl/failsafe_cluster_test.go
+++ b/cluster/cluster_impl/failsafe_cluster_test.go
@@ -40,10 +40,8 @@
"github.com/apache/dubbo-go/protocol/mock"
)
-var (
- failsafeUrl, _ = common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
-)
+var failsafeUrl, _ = common.NewURL(
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
// registerFailsafe register failsafeCluster to cluster extension.
func registerFailsafe(invoker *mock.MockInvoker) protocol.Invoker {
diff --git a/cluster/cluster_impl/forking_cluster_test.go b/cluster/cluster_impl/forking_cluster_test.go
index a2fa136..6549be5 100644
--- a/cluster/cluster_impl/forking_cluster_test.go
+++ b/cluster/cluster_impl/forking_cluster_test.go
@@ -42,10 +42,8 @@
"github.com/apache/dubbo-go/protocol/mock"
)
-var (
- forkingUrl, _ = common.NewURL(
- fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
-)
+var forkingUrl, _ = common.NewURL(
+ fmt.Sprintf("dubbo://%s:%d/com.ikurento.user.UserProvider", constant.LOCAL_HOST_VALUE, constant.DEFAULT_PORT))
func registerForking(mockInvokers ...*mock.MockInvoker) protocol.Invoker {
extension.SetLoadbalance(loadbalance.RoundRobin, loadbalance.NewRoundRobinLoadBalance)
@@ -72,7 +70,7 @@
mockResult := &protocol.RPCResult{Rest: rest{tried: 0, success: true}}
forkingUrl.AddParam(constant.FORKS_KEY, strconv.Itoa(3))
- //forkingUrl.AddParam(constant.TIMEOUT_KEY, strconv.Itoa(constant.DEFAULT_TIMEOUT))
+ // forkingUrl.AddParam(constant.TIMEOUT_KEY, strconv.Itoa(constant.DEFAULT_TIMEOUT))
var wg sync.WaitGroup
wg.Add(2)
diff --git a/cluster/cluster_impl/zone_aware_cluster_invoker.go b/cluster/cluster_impl/zone_aware_cluster_invoker.go
index 050f831..9834d87 100644
--- a/cluster/cluster_impl/zone_aware_cluster_invoker.go
+++ b/cluster/cluster_impl/zone_aware_cluster_invoker.go
@@ -125,7 +125,6 @@
}
func (invoker *zoneAwareClusterInvoker) AfterInvoker(ctx context.Context, invocation protocol.Invocation) {
-
}
func matchParam(target, key, def string, invoker protocol.Invoker) bool {
diff --git a/cluster/cluster_impl/zone_aware_cluster_invoker_test.go b/cluster/cluster_impl/zone_aware_cluster_invoker_test.go
index 7f77f33..d681745 100644
--- a/cluster/cluster_impl/zone_aware_cluster_invoker_test.go
+++ b/cluster/cluster_impl/zone_aware_cluster_invoker_test.go
@@ -41,11 +41,12 @@
ctrl := gomock.NewController(t)
// In Go versions 1.14+, if you pass a *testing.T
// into gomock.NewController(t) you no longer need to call ctrl.Finish().
- //defer ctrl.Finish()
+ // defer ctrl.Finish()
mockResult := &protocol.RPCResult{
Attrs: map[string]interface{}{constant.PREFERRED_KEY: "true"},
- Rest: rest{tried: 0, success: true}}
+ Rest: rest{tried: 0, success: true},
+ }
var invokers []protocol.Invoker
for i := 0; i < 2; i++ {
@@ -82,7 +83,7 @@
ctrl := gomock.NewController(t)
// In Go versions 1.14+, if you pass a *testing.T
// into gomock.NewController(t) you no longer need to call ctrl.Finish().
- //defer ctrl.Finish()
+ // defer ctrl.Finish()
w1 := "50"
w2 := "200"
@@ -100,7 +101,8 @@
func(invocation protocol.Invocation) protocol.Result {
return &protocol.RPCResult{
Attrs: map[string]interface{}{constant.WEIGHT_KEY: w1},
- Rest: rest{tried: 0, success: true}}
+ Rest: rest{tried: 0, success: true},
+ }
}).MaxTimes(100)
} else {
url.SetParam(constant.REGISTRY_KEY+"."+constant.WEIGHT_KEY, w2)
@@ -108,7 +110,8 @@
func(invocation protocol.Invocation) protocol.Result {
return &protocol.RPCResult{
Attrs: map[string]interface{}{constant.WEIGHT_KEY: w2},
- Rest: rest{tried: 0, success: true}}
+ Rest: rest{tried: 0, success: true},
+ }
}).MaxTimes(100)
}
invokers = append(invokers, invoker)
@@ -135,12 +138,12 @@
}
func TestZoneWareInvokerWithZoneSuccess(t *testing.T) {
- var zoneArray = []string{"hangzhou", "shanghai"}
+ zoneArray := []string{"hangzhou", "shanghai"}
ctrl := gomock.NewController(t)
// In Go versions 1.14+, if you pass a *testing.T
// into gomock.NewController(t) you no longer need to call ctrl.Finish().
- //defer ctrl.Finish()
+ // defer ctrl.Finish()
var invokers []protocol.Invoker
for i := 0; i < 2; i++ {
@@ -155,7 +158,8 @@
func(invocation protocol.Invocation) protocol.Result {
return &protocol.RPCResult{
Attrs: map[string]interface{}{constant.ZONE_KEY: zoneValue},
- Rest: rest{tried: 0, success: true}}
+ Rest: rest{tried: 0, success: true},
+ }
})
invokers = append(invokers, invoker)
}
@@ -178,7 +182,7 @@
ctrl := gomock.NewController(t)
// In Go versions 1.14+, if you pass a *testing.T
// into gomock.NewController(t) you no longer need to call ctrl.Finish().
- //defer ctrl.Finish()
+ // defer ctrl.Finish()
var invokers []protocol.Invoker
for i := 0; i < 2; i++ {
diff --git a/cluster/directory/base_directory_test.go b/cluster/directory/base_directory_test.go
index 443f07d..9bbcac3 100644
--- a/cluster/directory/base_directory_test.go
+++ b/cluster/directory/base_directory_test.go
@@ -47,7 +47,6 @@
}
func TestBuildRouterChain(t *testing.T) {
-
regURL := url
regURL.AddParam(constant.INTERFACE_KEY, "mock-app")
directory := NewBaseDirectory(regURL)
diff --git a/cluster/directory/static_directory.go b/cluster/directory/static_directory.go
index d9695d4..e184dc6 100644
--- a/cluster/directory/static_directory.go
+++ b/cluster/directory/static_directory.go
@@ -48,7 +48,7 @@
return dir
}
-//for-loop invokers ,if all invokers is available ,then it means directory is available
+// for-loop invokers ,if all invokers is available ,then it means directory is available
func (dir *staticDirectory) IsAvailable() bool {
if len(dir.invokers) == 0 {
return false
diff --git a/cluster/loadbalance/consistent_hash.go b/cluster/loadbalance/consistent_hash.go
index 3d036b4..314728a 100644
--- a/cluster/loadbalance/consistent_hash.go
+++ b/cluster/loadbalance/consistent_hash.go
@@ -27,9 +27,11 @@
"strconv"
"strings"
)
+
import (
gxsort "github.com/dubbogo/gost/sort"
)
+
import (
"github.com/apache/dubbo-go/cluster"
"github.com/apache/dubbo-go/common/constant"
@@ -56,8 +58,7 @@
}
// ConsistentHashLoadBalance implementation of load balancing: using consistent hashing
-type ConsistentHashLoadBalance struct {
-}
+type ConsistentHashLoadBalance struct{}
// NewConsistentHashLoadBalance creates NewConsistentHashLoadBalance
//
diff --git a/cluster/loadbalance/least_active.go b/cluster/loadbalance/least_active.go
index 8776735..f8fc015 100644
--- a/cluster/loadbalance/least_active.go
+++ b/cluster/loadbalance/least_active.go
@@ -36,8 +36,7 @@
extension.SetLoadbalance(LeastActive, NewLeastActiveLoadBalance)
}
-type leastActiveLoadBalance struct {
-}
+type leastActiveLoadBalance struct{}
// NewLeastActiveLoadBalance returns a least active load balance.
//
diff --git a/cluster/loadbalance/random.go b/cluster/loadbalance/random.go
index cdde1b4..a2ae2be 100644
--- a/cluster/loadbalance/random.go
+++ b/cluster/loadbalance/random.go
@@ -35,8 +35,7 @@
extension.SetLoadbalance(name, NewRandomLoadBalance)
}
-type randomLoadBalance struct {
-}
+type randomLoadBalance struct{}
// NewRandomLoadBalance returns a random load balance instance.
//
diff --git a/cluster/loadbalance/round_robin.go b/cluster/loadbalance/round_robin.go
index 51a76da..f7653b6 100644
--- a/cluster/loadbalance/round_robin.go
+++ b/cluster/loadbalance/round_robin.go
@@ -83,7 +83,7 @@
)
for _, invoker := range invokers {
- var weight = GetWeight(invoker, invocation)
+ weight := GetWeight(invoker, invocation)
if weight < 0 {
weight = 0
}
diff --git a/cluster/loadbalance/util.go b/cluster/loadbalance/util.go
index 684ffe1..2dd55d3 100644
--- a/cluster/loadbalance/util.go
+++ b/cluster/loadbalance/util.go
@@ -38,7 +38,7 @@
weight = url.GetMethodParamInt64(invocation.MethodName(), constant.WEIGHT_KEY, constant.DEFAULT_WEIGHT)
if weight > 0 {
- //get service register time an do warm up time
+ // get service register time an do warm up time
now := time.Now().Unix()
timestamp := url.GetParamInt(constant.REMOTE_TIMESTAMP_KEY, now)
if uptime := now - timestamp; uptime > 0 {
diff --git a/cluster/router/condition/app_router_test.go b/cluster/router/condition/app_router_test.go
index 86fdede..6e072b6 100644
--- a/cluster/router/condition/app_router_test.go
+++ b/cluster/router/condition/app_router_test.go
@@ -51,7 +51,6 @@
)
func TestNewAppRouter(t *testing.T) {
-
testYML := `scope: application
key: mock-app
enabled: true
@@ -105,7 +104,6 @@
}
func TestGenerateConditions(t *testing.T) {
-
testYML := `scope: application
key: mock-app
enabled: true
@@ -152,7 +150,6 @@
}
func TestProcess(t *testing.T) {
-
testYML := `scope: application
key: mock-app
enabled: true
diff --git a/cluster/router/condition/factory_test.go b/cluster/router/condition/factory_test.go
index e08016d..7cd6fae 100644
--- a/cluster/router/condition/factory_test.go
+++ b/cluster/router/condition/factory_test.go
@@ -204,7 +204,6 @@
assert.Equal(t, 1, len(ret4.ToArray()))
assert.Equal(t, 2, len(ret5.ToArray()))
assert.Equal(t, 1, len(ret6.ToArray()))
-
}
func TestRoute_methodRoute(t *testing.T) {
@@ -232,7 +231,6 @@
router3, _ := newConditionRouterFactory().NewPriorityRouter(getRouteUrl(rule3), notify)
matchWhen = router3.(*ConditionRouter).MatchWhen(url3, inv)
assert.Equal(t, true, matchWhen)
-
}
func TestRoute_ReturnFalse(t *testing.T) {
diff --git a/cluster/router/condition/listenable_router.go b/cluster/router/condition/listenable_router.go
index 2e55b20..79d80da 100644
--- a/cluster/router/condition/listenable_router.go
+++ b/cluster/router/condition/listenable_router.go
@@ -83,7 +83,8 @@
l.Process(&config_center.ConfigChangeEvent{
Key: routerKey,
Value: rule,
- ConfigType: remoting.EventTypeUpdate})
+ ConfigType: remoting.EventTypeUpdate,
+ })
logger.Info("Init app router success")
return l, nil
diff --git a/cluster/router/condition/router.go b/cluster/router/condition/router.go
index d543ca3..e1aef98 100644
--- a/cluster/router/condition/router.go
+++ b/cluster/router/condition/router.go
@@ -42,16 +42,12 @@
pattern = `([&!=,]*)\\s*([^&!=,\\s]+)`
)
-var (
- routerPatternReg = regexp.MustCompile(`([&!=,]*)\s*([^&!=,\s]+)`)
-)
+var routerPatternReg = regexp.MustCompile(`([&!=,]*)\s*([^&!=,\s]+)`)
-var (
- emptyMatchPair = MatchPair{
- Matches: gxset.NewSet(),
- Mismatches: gxset.NewSet(),
- }
-)
+var emptyMatchPair = MatchPair{
+ Matches: gxset.NewSet(),
+ Mismatches: gxset.NewSet(),
+}
// ConditionRouter Condition router struct
type ConditionRouter struct {
@@ -231,26 +227,26 @@
}
case "=":
if pair == emptyMatchPair {
- var startIndex = getStartIndex(rule)
+ startIndex := getStartIndex(rule)
return nil, perrors.Errorf("Illegal route rule \"%s\", The error char '%s' at index %d before \"%d\".", rule, separator, startIndex, startIndex)
}
values = pair.Matches
values.Add(content)
case "!=":
if pair == emptyMatchPair {
- var startIndex = getStartIndex(rule)
+ startIndex := getStartIndex(rule)
return nil, perrors.Errorf("Illegal route rule \"%s\", The error char '%s' at index %d before \"%d\".", rule, separator, startIndex, startIndex)
}
values = pair.Mismatches
values.Add(content)
case ",":
if values.Empty() {
- var startIndex = getStartIndex(rule)
+ startIndex := getStartIndex(rule)
return nil, perrors.Errorf("Illegal route rule \"%s\", The error char '%s' at index %d before \"%d\".", rule, separator, startIndex, startIndex)
}
values.Add(content)
default:
- var startIndex = getStartIndex(rule)
+ startIndex := getStartIndex(rule)
return nil, perrors.Errorf("Illegal route rule \"%s\", The error char '%s' at index %d before \"%d\".", rule, separator, startIndex, startIndex)
}
diff --git a/cluster/router/conncheck/conn_check_route_test.go b/cluster/router/conncheck/conn_check_route_test.go
index fec7331..360e97c 100644
--- a/cluster/router/conncheck/conn_check_route_test.go
+++ b/cluster/router/conncheck/conn_check_route_test.go
@@ -78,7 +78,6 @@
res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*ConnCheckRouter), invokers), consumerURL, inv)
// now invoker3 invoker1 is healthy
assert.True(t, len(res.ToArray()) == 2)
-
}
func TestRecovery(t *testing.T) {
diff --git a/cluster/router/conncheck/conn_health_check.go b/cluster/router/conncheck/conn_health_check.go
index 9f05b06..a5cee10 100644
--- a/cluster/router/conncheck/conn_health_check.go
+++ b/cluster/router/conncheck/conn_health_check.go
@@ -30,8 +30,7 @@
}
// DefaultConnChecker is the default implementation of ConnChecker, which determines the health status of invoker conn
-type DefaultConnChecker struct {
-}
+type DefaultConnChecker struct{}
// IsConnHealthy evaluates the healthy state on the given Invoker based on the number of successive bad request
// and the current active request
diff --git a/cluster/router/conncheck/factory.go b/cluster/router/conncheck/factory.go
index a7b19aa..fb03689 100644
--- a/cluster/router/conncheck/factory.go
+++ b/cluster/router/conncheck/factory.go
@@ -30,8 +30,7 @@
// ConnCheckRouteFactory is the factory to create conn check router, it aims at filter ip with unhealthy status
// the unhealthy status is storied in protocol/rpc_status.go with sync.Map
-type ConnCheckRouteFactory struct {
-}
+type ConnCheckRouteFactory struct{}
// newConnCheckRouteFactory construct a new ConnCheckRouteFactory
func newConnCheckRouteFactory() router.PriorityRouterFactory {
diff --git a/cluster/router/healthcheck/default_health_check.go b/cluster/router/healthcheck/default_health_check.go
index eb15e6f..2c84d65 100644
--- a/cluster/router/healthcheck/default_health_check.go
+++ b/cluster/router/healthcheck/default_health_check.go
@@ -77,7 +77,6 @@
// getCircuitBreakerSleepWindowTime get the sleep window time of invoker, the unit is millisecond
func (c *DefaultHealthChecker) getCircuitBreakerSleepWindowTime(status *protocol.RPCStatus) int64 {
-
successiveFailureCount := status.GetSuccessiveRequestFailureCount()
diff := successiveFailureCount - c.GetRequestSuccessiveFailureThreshold()
if diff < 0 {
diff --git a/cluster/router/healthcheck/default_health_check_test.go b/cluster/router/healthcheck/default_health_check_test.go
index c32a607..4583dad 100644
--- a/cluster/router/healthcheck/default_health_check_test.go
+++ b/cluster/router/healthcheck/default_health_check_test.go
@@ -123,7 +123,6 @@
timeout = defaultHc.getCircuitBreakerTimeout(protocol.GetURLStatus(url1))
// timeout must after the current time
assert.True(t, timeout > protocol.CurrentTimeMillis())
-
}
func TestDefaultHealthCheckerIsCircuitBreakerTripped(t *testing.T) {
@@ -139,7 +138,6 @@
}
tripped = defaultHc.isCircuitBreakerTripped(protocol.GetURLStatus(url))
assert.True(t, tripped)
-
}
func TestNewDefaultHealthChecker(t *testing.T) {
diff --git a/cluster/router/healthcheck/factory.go b/cluster/router/healthcheck/factory.go
index a9054c7..e6d876d 100644
--- a/cluster/router/healthcheck/factory.go
+++ b/cluster/router/healthcheck/factory.go
@@ -29,8 +29,7 @@
}
// HealthCheckRouteFactory
-type HealthCheckRouteFactory struct {
-}
+type HealthCheckRouteFactory struct{}
// newHealthCheckRouteFactory construct a new HealthCheckRouteFactory
func newHealthCheckRouteFactory() router.PriorityRouterFactory {
diff --git a/cluster/router/healthcheck/health_check_route_test.go b/cluster/router/healthcheck/health_check_route_test.go
index f499c85..5422c53 100644
--- a/cluster/router/healthcheck/health_check_route_test.go
+++ b/cluster/router/healthcheck/health_check_route_test.go
@@ -112,7 +112,6 @@
// invoker1 go to healthy again after 2s
res = hcr.Route(utils.ToBitmap(invokers), setUpAddrCache(hcr.(*HealthCheckRouter), invokers), consumerURL, inv)
assert.True(t, res.Contains(0))
-
}
func TestNewHealthCheckRouter(t *testing.T) {
diff --git a/cluster/router/local/factory.go b/cluster/router/local/factory.go
index 42e03e2..711a9ea 100644
--- a/cluster/router/local/factory.go
+++ b/cluster/router/local/factory.go
@@ -29,8 +29,7 @@
}
// LocalPriorityRouteFactory
-type LocalPriorityRouteFactory struct {
-}
+type LocalPriorityRouteFactory struct{}
// newLocalPriorityRouteFactory construct a new LocalDiscRouteFactory
func newLocalPriorityRouteFactory() router.PriorityRouterFactory {
diff --git a/cluster/router/local/self_priority_route.go b/cluster/router/local/self_priority_route.go
index 87eaaf7..7fd188c 100644
--- a/cluster/router/local/self_priority_route.go
+++ b/cluster/router/local/self_priority_route.go
@@ -80,7 +80,7 @@
logger.Debug("found local ip ")
return rb, nil
}
- for i, _ := range invokers {
+ for i := range invokers {
rb[localPriority].Add(uint32(i))
}
return rb, nil
diff --git a/cluster/router/tag/file.go b/cluster/router/tag/file.go
index 81c2510..8977ddc 100644
--- a/cluster/router/tag/file.go
+++ b/cluster/router/tag/file.go
@@ -41,7 +41,7 @@
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/file_test.go b/cluster/router/tag/file_test.go
index 513ba0c..1866ec0 100644
--- a/cluster/router/tag/file_test.go
+++ b/cluster/router/tag/file_test.go
@@ -52,7 +52,6 @@
priority := url.GetParam(constant.RouterPriority, "0")
assert.Equal(t, "true", force)
assert.Equal(t, "100", priority)
-
}
func TestFileTagRouterPriority(t *testing.T) {
diff --git a/cluster/router/tag/router_rule.go b/cluster/router/tag/router_rule.go
index 512d8f1..1259c42 100644
--- a/cluster/router/tag/router_rule.go
+++ b/cluster/router/tag/router_rule.go
@@ -69,7 +69,7 @@
}
func (t *RouterRule) getAddresses() []string {
- var result = make([]string, 0, 2*len(t.Tags))
+ result := make([]string, 0, 2*len(t.Tags))
for _, tag := range t.Tags {
result = append(result, tag.Addresses...)
}
@@ -77,7 +77,7 @@
}
func (t *RouterRule) getTagNames() []string {
- var result = make([]string, 0, len(t.Tags))
+ result := make([]string, 0, len(t.Tags))
for _, tag := range t.Tags {
result = append(result, tag.Name)
}
diff --git a/cluster/router/tag/tag_router.go b/cluster/router/tag/tag_router.go
index 3d0393a..e0522d4 100644
--- a/cluster/router/tag/tag_router.go
+++ b/cluster/router/tag/tag_router.go
@@ -53,7 +53,7 @@
// 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
@@ -267,7 +267,8 @@
c.Process(&config_center.ConfigChangeEvent{
Key: routerKey,
Value: rule,
- ConfigType: remoting.EventTypeUpdate})
+ ConfigType: remoting.EventTypeUpdate,
+ })
}
}
diff --git a/cluster/router/tag/tag_router_test.go b/cluster/router/tag/tag_router_test.go
index 3b53d47..e5abf4e 100644
--- a/cluster/router/tag/tag_router_test.go
+++ b/cluster/router/tag/tag_router_test.go
@@ -72,9 +72,7 @@
routerZk = "zookeeper"
)
-var (
- zkFormat = "zookeeper://%s:%d"
-)
+var zkFormat = "zookeeper://%s:%d"
// MockInvoker is only mock the Invoker to support test tagRouter
type MockInvoker struct {
@@ -257,7 +255,7 @@
type DynamicTagRouter struct {
suite.Suite
- //rule *RouterRule
+ // rule *RouterRule
route *tagRouter
zkClient *gxzookeeper.ZookeeperClient
diff --git a/common/config/environment.go b/common/config/environment.go
index 23baa70..c568646 100644
--- a/common/config/environment.go
+++ b/common/config/environment.go
@@ -35,7 +35,7 @@
// 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
+ // externalConfigs sync.Map
externalConfigMap sync.Map
appExternalConfigMap sync.Map
dynamicConfiguration config_center.DynamicConfiguration
diff --git a/common/constant/default.go b/common/constant/default.go
index 8afb5c7..f52a3f0 100644
--- a/common/constant/default.go
+++ b/common/constant/default.go
@@ -20,7 +20,7 @@
const (
DUBBO = "dubbo"
PROVIDER_PROTOCOL = "provider"
- //compatible with 2.6.x
+ // compatible with 2.6.x
OVERRIDE_PROTOCOL = "override"
EMPTY_PROTOCOL = "empty"
ROUTER_PROTOCOL = "router"
diff --git a/common/constant/key.go b/common/constant/key.go
index 4b867d8..62a8fcc 100644
--- a/common/constant/key.go
+++ b/common/constant/key.go
@@ -49,7 +49,7 @@
PORT_KEY = "port"
PROTOCOL_KEY = "protocol"
PATH_SEPARATOR = "/"
- //DUBBO_KEY = "dubbo"
+ // DUBBO_KEY = "dubbo"
SSL_ENABLED_KEY = "ssl-enabled"
)
@@ -144,6 +144,7 @@
CONFIG_VERSION_KEY = "configVersion"
COMPATIBLE_CONFIG_KEY = "compatible_config"
)
+
const (
RegistryConfigPrefix = "dubbo.registries."
SingleRegistryConfigPrefix = "dubbo.registry."
diff --git a/common/constant/time.go b/common/constant/time.go
index 3bb3392..d50990c 100644
--- a/common/constant/time.go
+++ b/common/constant/time.go
@@ -21,8 +21,6 @@
"time"
)
-var (
- // The value will be 10^6
- // 1ms = 10^6ns
- MsToNanoRate = int64(time.Millisecond / time.Nanosecond)
-)
+// The value will be 10^6
+// 1ms = 10^6ns
+var MsToNanoRate = int64(time.Millisecond / time.Nanosecond)
diff --git a/common/extension/cluster.go b/common/extension/cluster.go
index 8be27a1..1f6ab10 100644
--- a/common/extension/cluster.go
+++ b/common/extension/cluster.go
@@ -21,9 +21,7 @@
"github.com/apache/dubbo-go/cluster"
)
-var (
- clusters = make(map[string]func() cluster.Cluster)
-)
+var clusters = make(map[string]func() cluster.Cluster)
// SetCluster sets the cluster fault-tolerant mode with @name
// For example: available/failfast/broadcast/failfast/failsafe/...
diff --git a/common/extension/config_center.go b/common/extension/config_center.go
index 5a2c52f..9c616d3 100644
--- a/common/extension/config_center.go
+++ b/common/extension/config_center.go
@@ -22,9 +22,7 @@
"github.com/apache/dubbo-go/config_center"
)
-var (
- configCenters = make(map[string]func(config *common.URL) (config_center.DynamicConfiguration, error))
-)
+var configCenters = make(map[string]func(config *common.URL) (config_center.DynamicConfiguration, error))
// SetConfigCenter sets the DynamicConfiguration with @name
func SetConfigCenter(name string, v func(*common.URL) (config_center.DynamicConfiguration, error)) {
@@ -37,5 +35,4 @@
panic("config center for " + name + " is not existing, make sure you have import the package.")
}
return configCenters[name](config)
-
}
diff --git a/common/extension/config_center_factory.go b/common/extension/config_center_factory.go
index dff8975..9d3f0d9 100644
--- a/common/extension/config_center_factory.go
+++ b/common/extension/config_center_factory.go
@@ -21,9 +21,7 @@
"github.com/apache/dubbo-go/config_center"
)
-var (
- configCenterFactories = make(map[string]func() config_center.DynamicConfigurationFactory)
-)
+var configCenterFactories = make(map[string]func() config_center.DynamicConfigurationFactory)
// SetConfigCenterFactory sets the DynamicConfigurationFactory with @name
func SetConfigCenterFactory(name string, v func() config_center.DynamicConfigurationFactory) {
diff --git a/common/extension/config_post_processor.go b/common/extension/config_post_processor.go
index db126b7..19a479e 100644
--- a/common/extension/config_post_processor.go
+++ b/common/extension/config_post_processor.go
@@ -21,9 +21,7 @@
"github.com/apache/dubbo-go/config/interfaces"
)
-var (
- processors = make(map[string]interfaces.ConfigPostProcessor)
-)
+var processors = make(map[string]interfaces.ConfigPostProcessor)
// SetConfigPostProcessor registers a ConfigPostProcessor with the given name.
func SetConfigPostProcessor(name string, processor interfaces.ConfigPostProcessor) {
diff --git a/common/extension/configurator.go b/common/extension/configurator.go
index dc2bea7..3cc7ffc 100644
--- a/common/extension/configurator.go
+++ b/common/extension/configurator.go
@@ -29,9 +29,7 @@
type getConfiguratorFunc func(url *common.URL) config_center.Configurator
-var (
- configurator = make(map[string]getConfiguratorFunc)
-)
+var configurator = make(map[string]getConfiguratorFunc)
// SetConfigurator sets the getConfiguratorFunc with @name
func SetConfigurator(name string, v getConfiguratorFunc) {
@@ -44,7 +42,6 @@
panic("configurator for " + name + " is not existing, make sure you have import the package.")
}
return configurator[name](url)
-
}
// SetDefaultConfigurator sets the default Configurator
@@ -58,7 +55,6 @@
panic("configurator for default is not existing, make sure you have import the package.")
}
return configurator[DefaultKey](url)
-
}
// GetDefaultConfiguratorFunc gets default configurator function
diff --git a/common/extension/conn_checker.go b/common/extension/conn_checker.go
index fbd9e34..38659d7 100644
--- a/common/extension/conn_checker.go
+++ b/common/extension/conn_checker.go
@@ -22,9 +22,7 @@
"github.com/apache/dubbo-go/common"
)
-var (
- connCheckers = make(map[string]func(url *common.URL) router.ConnChecker)
-)
+var connCheckers = make(map[string]func(url *common.URL) router.ConnChecker)
// SetHealthChecker sets the HealthChecker with @name
func SetConnChecker(name string, fcn func(_ *common.URL) router.ConnChecker) {
diff --git a/common/extension/event_dispatcher.go b/common/extension/event_dispatcher.go
index f0503e0..3504d9b 100644
--- a/common/extension/event_dispatcher.go
+++ b/common/extension/event_dispatcher.go
@@ -32,9 +32,7 @@
initEventOnce sync.Once
)
-var (
- dispatchers = make(map[string]func() observer.EventDispatcher, 8)
-)
+var dispatchers = make(map[string]func() observer.EventDispatcher, 8)
// SetEventDispatcher, actually, it doesn't really init the global dispatcher
func SetEventDispatcher(name string, v func() observer.EventDispatcher) {
diff --git a/common/extension/event_dispatcher_test.go b/common/extension/event_dispatcher_test.go
index 472360c..fbcf452 100644
--- a/common/extension/event_dispatcher_test.go
+++ b/common/extension/event_dispatcher_test.go
@@ -25,6 +25,7 @@
import (
"github.com/stretchr/testify/assert"
)
+
import (
"github.com/apache/dubbo-go/common/observer"
)
@@ -64,8 +65,7 @@
assert.Equal(t, 2, len(initEventListeners))
}
-type mockEventListener struct {
-}
+type mockEventListener struct{}
func (m mockEventListener) GetPriority() int {
panic("implement me")
@@ -79,8 +79,7 @@
panic("implement me")
}
-type mockEventDispatcher struct {
-}
+type mockEventDispatcher struct{}
func (m mockEventDispatcher) AddEventListener(listener observer.EventListener) {
panic("implement me")
diff --git a/common/extension/graceful_shutdown.go b/common/extension/graceful_shutdown.go
index cb55419..8c98192 100644
--- a/common/extension/graceful_shutdown.go
+++ b/common/extension/graceful_shutdown.go
@@ -21,9 +21,7 @@
"container/list"
)
-var (
- customShutdownCallbacks = list.New()
-)
+var customShutdownCallbacks = list.New()
/**
* AddCustomShutdownCallback
diff --git a/common/extension/health_checker.go b/common/extension/health_checker.go
index cec4c2d..c0cc0f6 100644
--- a/common/extension/health_checker.go
+++ b/common/extension/health_checker.go
@@ -22,9 +22,7 @@
"github.com/apache/dubbo-go/common"
)
-var (
- healthCheckers = make(map[string]func(url *common.URL) router.HealthChecker)
-)
+var healthCheckers = make(map[string]func(url *common.URL) router.HealthChecker)
// SetHealthChecker sets the HealthChecker with @name
func SetHealthChecker(name string, fcn func(_ *common.URL) router.HealthChecker) {
diff --git a/common/extension/health_checker_test.go b/common/extension/health_checker_test.go
index af6b114..cee12ce 100644
--- a/common/extension/health_checker_test.go
+++ b/common/extension/health_checker_test.go
@@ -37,8 +37,7 @@
assert.NotNil(t, checker)
}
-type mockHealthChecker struct {
-}
+type mockHealthChecker struct{}
func (m mockHealthChecker) IsHealthy(invoker protocol.Invoker) bool {
return true
diff --git a/common/extension/loadbalance.go b/common/extension/loadbalance.go
index aa19141..bbd0fbc 100644
--- a/common/extension/loadbalance.go
+++ b/common/extension/loadbalance.go
@@ -21,9 +21,7 @@
"github.com/apache/dubbo-go/cluster"
)
-var (
- loadbalances = make(map[string]func() cluster.LoadBalance)
-)
+var loadbalances = make(map[string]func() cluster.LoadBalance)
// SetLoadbalance sets the loadbalance extension with @name
// For example: random/round_robin/consistent_hash/least_active/...
diff --git a/common/extension/metadata_report_factory.go b/common/extension/metadata_report_factory.go
index 593318d..641ba4a 100644
--- a/common/extension/metadata_report_factory.go
+++ b/common/extension/metadata_report_factory.go
@@ -21,9 +21,7 @@
"github.com/apache/dubbo-go/metadata/report/factory"
)
-var (
- metaDataReportFactories = make(map[string]func() factory.MetadataReportFactory, 8)
-)
+var metaDataReportFactories = make(map[string]func() factory.MetadataReportFactory, 8)
// SetMetadataReportFactory sets the MetadataReportFactory with @name
func SetMetadataReportFactory(name string, v func() factory.MetadataReportFactory) {
diff --git a/common/extension/metadata_service_proxy_factory.go b/common/extension/metadata_service_proxy_factory.go
index 2b88d37..3e05c22 100644
--- a/common/extension/metadata_service_proxy_factory.go
+++ b/common/extension/metadata_service_proxy_factory.go
@@ -25,9 +25,7 @@
"github.com/apache/dubbo-go/metadata/service"
)
-var (
- metadataServiceProxyFactoryMap = make(map[string]func() service.MetadataServiceProxyFactory, 2)
-)
+var metadataServiceProxyFactoryMap = make(map[string]func() service.MetadataServiceProxyFactory, 2)
type MetadataServiceProxyFactoryFunc func() service.MetadataServiceProxyFactory
diff --git a/common/extension/metrics.go b/common/extension/metrics.go
index 60cf6ba..3e221b7 100644
--- a/common/extension/metrics.go
+++ b/common/extension/metrics.go
@@ -21,11 +21,9 @@
"github.com/apache/dubbo-go/metrics"
)
-var (
- // we couldn't store the instance because the some instance may initialize before loading configuration
- // so lazy initialization will be better.
- metricReporterMap = make(map[string]func() metrics.Reporter, 4)
-)
+// we couldn't store the instance because the some instance may initialize before loading configuration
+// so lazy initialization will be better.
+var metricReporterMap = make(map[string]func() metrics.Reporter, 4)
// SetMetricReporter sets a reporter with the @name
func SetMetricReporter(name string, reporterFunc func() metrics.Reporter) {
diff --git a/common/extension/metrics_test.go b/common/extension/metrics_test.go
index 2aaae75..bcd86a8 100644
--- a/common/extension/metrics_test.go
+++ b/common/extension/metrics_test.go
@@ -42,8 +42,7 @@
assert.Equal(t, reporter, res)
}
-type mockReporter struct {
-}
+type mockReporter struct{}
// Report method for feature expansion
func (m mockReporter) Report(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation, cost time.Duration, res protocol.Result) {
diff --git a/common/extension/protocol.go b/common/extension/protocol.go
index c89dd08..0c77ead 100644
--- a/common/extension/protocol.go
+++ b/common/extension/protocol.go
@@ -21,9 +21,7 @@
"github.com/apache/dubbo-go/protocol"
)
-var (
- protocols = make(map[string]func() protocol.Protocol)
-)
+var protocols = make(map[string]func() protocol.Protocol)
// SetProtocol sets the protocol extension with @name
func SetProtocol(name string, v func() protocol.Protocol) {
diff --git a/common/extension/proxy_factory.go b/common/extension/proxy_factory.go
index 1e326d8..414905f 100644
--- a/common/extension/proxy_factory.go
+++ b/common/extension/proxy_factory.go
@@ -21,9 +21,7 @@
"github.com/apache/dubbo-go/common/proxy"
)
-var (
- proxyFactories = make(map[string]func(...proxy.Option) proxy.ProxyFactory)
-)
+var proxyFactories = make(map[string]func(...proxy.Option) proxy.ProxyFactory)
// SetProxyFactory sets the ProxyFactory extension with @name
func SetProxyFactory(name string, f func(...proxy.Option) proxy.ProxyFactory) {
diff --git a/common/extension/registry.go b/common/extension/registry.go
index 187c8fe..411ee37 100644
--- a/common/extension/registry.go
+++ b/common/extension/registry.go
@@ -22,9 +22,7 @@
"github.com/apache/dubbo-go/registry"
)
-var (
- registrys = make(map[string]func(config *common.URL) (registry.Registry, error))
-)
+var registrys = make(map[string]func(config *common.URL) (registry.Registry, error))
// SetRegistry sets the registry extension with @name
func SetRegistry(name string, v func(_ *common.URL) (registry.Registry, error)) {
@@ -37,5 +35,4 @@
panic("registry for " + name + " does not exist. please make sure that you have imported the package `github.com/apache/dubbo-go/registry/" + name + "`.")
}
return registrys[name](config)
-
}
diff --git a/common/extension/rest_client.go b/common/extension/rest_client.go
index 0c2f4dd..be60d28 100644
--- a/common/extension/rest_client.go
+++ b/common/extension/rest_client.go
@@ -21,9 +21,7 @@
"github.com/apache/dubbo-go/protocol/rest/client"
)
-var (
- restClients = make(map[string]func(restOptions *client.RestOptions) client.RestClient, 8)
-)
+var restClients = make(map[string]func(restOptions *client.RestOptions) client.RestClient, 8)
// SetRestClient sets the RestClient with @name
func SetRestClient(name string, fun func(_ *client.RestOptions) client.RestClient) {
diff --git a/common/extension/rest_server.go b/common/extension/rest_server.go
index 37a231a..c055309 100644
--- a/common/extension/rest_server.go
+++ b/common/extension/rest_server.go
@@ -21,9 +21,7 @@
"github.com/apache/dubbo-go/protocol/rest/server"
)
-var (
- restServers = make(map[string]func() server.RestServer, 8)
-)
+var restServers = make(map[string]func() server.RestServer, 8)
// SetRestServer sets the RestServer with @name
func SetRestServer(name string, fun func() server.RestServer) {
diff --git a/common/extension/service_discovery.go b/common/extension/service_discovery.go
index 0227920..6a691e1 100644
--- a/common/extension/service_discovery.go
+++ b/common/extension/service_discovery.go
@@ -20,13 +20,12 @@
import (
perrors "github.com/pkg/errors"
)
+
import (
"github.com/apache/dubbo-go/registry"
)
-var (
- discoveryCreatorMap = make(map[string]func(name string) (registry.ServiceDiscovery, error), 4)
-)
+var discoveryCreatorMap = make(map[string]func(name string) (registry.ServiceDiscovery, error), 4)
// SetServiceDiscovery will store the @creator and @name
// protocol indicate the implementation, like nacos
diff --git a/common/extension/service_instance_customizer.go b/common/extension/service_instance_customizer.go
index 3ebb3e4..3ec6af1 100644
--- a/common/extension/service_instance_customizer.go
+++ b/common/extension/service_instance_customizer.go
@@ -25,9 +25,7 @@
"github.com/apache/dubbo-go/registry"
)
-var (
- customizers = make([]registry.ServiceInstanceCustomizer, 0, 8)
-)
+var customizers = make([]registry.ServiceInstanceCustomizer, 0, 8)
// AddCustomizers will put the customizer into slices and then sort them;
// this method will be invoked several time, so we sort them here.
diff --git a/common/extension/service_instance_selector_factory.go b/common/extension/service_instance_selector_factory.go
index 66d3e76..9d107c4 100644
--- a/common/extension/service_instance_selector_factory.go
+++ b/common/extension/service_instance_selector_factory.go
@@ -25,9 +25,7 @@
"github.com/apache/dubbo-go/registry/servicediscovery/instance"
)
-var (
- serviceInstanceSelectorMappings = make(map[string]func() instance.ServiceInstanceSelector, 2)
-)
+var serviceInstanceSelectorMappings = make(map[string]func() instance.ServiceInstanceSelector, 2)
// nolint
func SetServiceInstanceSelector(name string, f func() instance.ServiceInstanceSelector) {
diff --git a/common/extension/service_name_mapping.go b/common/extension/service_name_mapping.go
index 99fd4c2..317acf6 100644
--- a/common/extension/service_name_mapping.go
+++ b/common/extension/service_name_mapping.go
@@ -23,9 +23,7 @@
type ServiceNameMappingCreator func() mapping.ServiceNameMapping
-var (
- globalNameMappingCreator ServiceNameMappingCreator
-)
+var globalNameMappingCreator ServiceNameMappingCreator
func SetGlobalServiceNameMapping(nameMappingCreator ServiceNameMappingCreator) {
globalNameMappingCreator = nameMappingCreator
diff --git a/common/logger/logger.go b/common/logger/logger.go
index 655b364..bc01043 100644
--- a/common/logger/logger.go
+++ b/common/logger/logger.go
@@ -37,9 +37,7 @@
"github.com/apache/dubbo-go/common/constant"
)
-var (
- logger Logger
-)
+var logger Logger
// nolint
type DubboLogger struct {
diff --git a/common/observer/dispatcher/mock_event_dispatcher.go b/common/observer/dispatcher/mock_event_dispatcher.go
index 45cdaa7..012f5ba 100644
--- a/common/observer/dispatcher/mock_event_dispatcher.go
+++ b/common/observer/dispatcher/mock_event_dispatcher.go
@@ -25,8 +25,7 @@
// It is only used by tests
// Now the implementation doing nothing,
// But you can modify this if needed
-type MockEventDispatcher struct {
-}
+type MockEventDispatcher struct{}
// AddEventListener do nothing
func (m MockEventDispatcher) AddEventListener(listener observer.EventListener) {
diff --git a/common/observer/listenable_test.go b/common/observer/listenable_test.go
index 5a03382..3ae6e5e 100644
--- a/common/observer/listenable_test.go
+++ b/common/observer/listenable_test.go
@@ -41,7 +41,6 @@
ts = append(ts, el)
b.AddEventListeners(ts)
assert.Equal(t, len(al), 1)
-
}
type TestEvent struct {
diff --git a/common/proxy/proxy.go b/common/proxy/proxy.go
index fd34810..68d37b7 100644
--- a/common/proxy/proxy.go
+++ b/common/proxy/proxy.go
@@ -53,9 +53,7 @@
ImplementFunc func(p *Proxy, v common.RPCService)
)
-var (
- typError = reflect.Zero(reflect.TypeOf((*error)(nil)).Elem()).Type()
-)
+var typError = reflect.Zero(reflect.TypeOf((*error)(nil)).Elem()).Type()
// NewProxy create service proxy.
func NewProxy(invoke protocol.Invoker, callback interface{}, attachments map[string]string) *Proxy {
@@ -251,7 +249,7 @@
continue
}
- var funcOuts = make([]reflect.Type, outNum)
+ funcOuts := make([]reflect.Type, outNum)
for i := 0; i < outNum; i++ {
funcOuts[i] = t.Type.Out(i)
}
@@ -261,5 +259,4 @@
logger.Debugf("set method [%s]", methodName)
}
}
-
}
diff --git a/common/proxy/proxy_factory/default.go b/common/proxy/proxy_factory/default.go
index ff3d795..4ef828f 100644
--- a/common/proxy/proxy_factory/default.go
+++ b/common/proxy/proxy_factory/default.go
@@ -41,11 +41,10 @@
}
// DefaultProxyFactory is the default proxy factory
-type DefaultProxyFactory struct {
- //delegate ProxyFactory
+type DefaultProxyFactory struct { // delegate ProxyFactory
}
-//you can rewrite DefaultProxyFactory in extension and delegate the default proxy factory like below
+// you can rewrite DefaultProxyFactory in extension and delegate the default proxy factory like below
//func WithDelegate(delegateProxyFactory ProxyFactory) Option {
// return func(proxy ProxyFactory) {
@@ -65,7 +64,7 @@
// GetAsyncProxy gets a async proxy
func (factory *DefaultProxyFactory) GetAsyncProxy(invoker protocol.Invoker, callBack interface{}, url *common.URL) *proxy.Proxy {
- //create proxy
+ // create proxy
attachments := map[string]string{}
attachments[constant.ASYNC_KEY] = url.GetParam(constant.ASYNC_KEY, "false")
return proxy.NewProxy(invoker, callBack, attachments)
@@ -88,7 +87,7 @@
result := &protocol.RPCResult{}
result.SetAttachments(invocation.Attachments())
- //get providerUrl. The origin url may be is registry URL.
+ // get providerUrl. The origin url may be is registry URL.
url := getProviderURL(pi.GetUrl())
methodName := invocation.MethodName()
diff --git a/common/proxy/proxy_factory/default_test.go b/common/proxy/proxy_factory/default_test.go
index 4002ab9..6a8c29a 100644
--- a/common/proxy/proxy_factory/default_test.go
+++ b/common/proxy/proxy_factory/default_test.go
@@ -38,8 +38,7 @@
assert.NotNil(t, proxy)
}
-type TestAsync struct {
-}
+type TestAsync struct{}
func (u *TestAsync) CallBack(res common.CallbackResponse) {
fmt.Println("CallBack res:", res)
diff --git a/common/proxy/proxy_test.go b/common/proxy/proxy_test.go
index c335bf6..86b3b61 100644
--- a/common/proxy/proxy_test.go
+++ b/common/proxy/proxy_test.go
@@ -58,7 +58,6 @@
}
func TestProxyImplement(t *testing.T) {
-
invoker := protocol.NewBaseInvoker(&common.URL{})
p := NewProxy(invoker, nil, map[string]string{constant.ASYNC_KEY: "false"})
s := &TestService{}
@@ -122,7 +121,6 @@
s3 := &S3{TestService: *s}
p.Implement(s3)
assert.Nil(t, s3.MethodOne)
-
}
func TestProxyImplementForContext(t *testing.T) {
diff --git a/common/rpc_service_test.go b/common/rpc_service_test.go
index e8bd393..ce861b7 100644
--- a/common/rpc_service_test.go
+++ b/common/rpc_service_test.go
@@ -39,47 +39,52 @@
testSuiteMethodExpectedString = "interface {}"
)
-type TestService struct {
-}
+type TestService struct{}
func (s *TestService) MethodOne(ctx context.Context, arg1, arg2, arg3 interface{}) error {
return nil
}
+
func (s *TestService) MethodTwo(arg1, arg2, arg3 interface{}) (interface{}, error) {
return struct{}{}, nil
}
+
func (s *TestService) MethodThree() error {
return nil
}
+
func (s *TestService) Reference() string {
return referenceTestPath
}
+
func (s *TestService) MethodMapper() map[string]string {
return map[string]string{
"MethodTwo": "methodTwo",
}
}
-type testService struct {
-}
+type testService struct{}
func (s *testService) Method1(ctx context.Context, args testService, rsp *struct{}) error {
return nil
}
+
func (s *testService) Method2(ctx context.Context, args []interface{}) (testService, error) {
return testService{}, nil
}
+
func (s *testService) Method3(ctx context.Context, args []interface{}, rsp *struct{}) {
}
+
func (s *testService) Method4(ctx context.Context, args []interface{}, rsp *struct{}) *testService {
return nil
}
+
func (s *testService) Reference() string {
return referenceTestPath
}
-type TestService1 struct {
-}
+type TestService1 struct{}
func (s *TestService1) Reference() string {
return referenceTestPathDistinct
diff --git a/common/url.go b/common/url.go
index 80b85fc..0e923c5 100644
--- a/common/url.go
+++ b/common/url.go
@@ -113,7 +113,7 @@
noCopy noCopy
baseUrl
- //url.Values is not safe map, add to avoid concurrent map read and map write error
+ // url.Values is not safe map, add to avoid concurrent map read and map write error
paramsLock sync.RWMutex
params url.Values
diff --git a/common/yaml/yaml.go b/common/yaml/yaml.go
index d7e1ca4..7f61f72 100644
--- a/common/yaml/yaml.go
+++ b/common/yaml/yaml.go
@@ -49,7 +49,7 @@
return confFileStream, yaml.Unmarshal(confFileStream, out)
}
-//UnmarshalYML unmarshals decodes the first document found within the in byte slice and assigns decoded values into the out value.
+// UnmarshalYML unmarshals decodes the first document found within the in byte slice and assigns decoded values into the out value.
func UnmarshalYML(data []byte, out interface{}) error {
return yaml.Unmarshal(data, out)
}
diff --git a/config/base_config.go b/config/base_config.go
index df1686a..0937d51 100644
--- a/config/base_config.go
+++ b/config/base_config.go
@@ -45,7 +45,7 @@
// 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"`
@@ -68,9 +68,7 @@
}
func getKeyPrefix(val reflect.Value) []string {
- var (
- prefix string
- )
+ var prefix string
configPrefixMethod := "Prefix"
if val.CanAddr() {
prefix = val.Addr().MethodByName(configPrefixMethod).Call(nil)[0].String()
@@ -97,7 +95,6 @@
f := val.Field(i)
if f.IsValid() {
setBaseValue := func(f reflect.Value) {
-
var (
ok bool
value string
@@ -170,7 +167,6 @@
}
}
-
}
if f.Kind() == reflect.Ptr {
@@ -198,7 +194,6 @@
}
}
-
}
if f.Kind() == reflect.Map {
diff --git a/config/config_center_config.go b/config/config_center_config.go
index 2489709..90ad972 100644
--- a/config/config_center_config.go
+++ b/config/config_center_config.go
@@ -44,7 +44,7 @@
//
// 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"`
@@ -58,7 +58,7 @@
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
@@ -81,8 +81,7 @@
return urlMap
}
-type configCenter struct {
-}
+type configCenter struct{}
// toURL will compatible with baseConfig.ConfigCenterConfig.Address and baseConfig.ConfigCenterConfig.RemoteRef before 1.6.0
// After 1.6.0 will not compatible, only baseConfig.ConfigCenterConfig.RemoteRef
diff --git a/config/config_center_config_test.go b/config/config_center_config_test.go
index 2299167..58faff3 100644
--- a/config/config_center_config_test.go
+++ b/config/config_center_config_test.go
@@ -62,7 +62,8 @@
Group: "dubbo",
RemoteRef: "mock",
ConfigFile: "mockDubbo.properties",
- }}
+ },
+ }
c := &configCenter{}
err := c.startConfigCenter(*baseConfig)
@@ -85,7 +86,8 @@
Group: "dubbo",
RemoteRef: "mock",
ConfigFile: "mockDubbo.properties",
- }}
+ },
+ }
c := &configCenter{}
err := c.startConfigCenter(*baseConfig)
diff --git a/config/config_loader.go b/config/config_loader.go
index 90726fd..bb1069c 100644
--- a/config/config_loader.go
+++ b/config/config_loader.go
@@ -201,7 +201,7 @@
if data, err := yaml.MarshalYML(consumerConfig); err != nil {
logger.Errorf("Marshal consumer config err: %s", err.Error())
} else {
- if err := ioutil.WriteFile(consumerConfig.CacheFile, data, 0666); err != nil {
+ if err := ioutil.WriteFile(consumerConfig.CacheFile, data, 0o666); err != nil {
logger.Errorf("Write consumer config cache file err: %s", err.Error())
}
}
@@ -268,7 +268,7 @@
if data, err := yaml.MarshalYML(providerConfig); err != nil {
logger.Errorf("Marshal provider config err: %s", err.Error())
} else {
- if err := ioutil.WriteFile(providerConfig.CacheFile, data, 0666); err != nil {
+ if err := ioutil.WriteFile(providerConfig.CacheFile, data, 0o666); err != nil {
logger.Errorf("Write provider config cache file err: %s", err.Error())
}
}
@@ -387,7 +387,6 @@
// Load Dubbo Init
func Load() {
-
// init router
initRouter()
@@ -498,9 +497,11 @@
func GetSslEnabled() bool {
return sslEnabled
}
+
func SetSslEnabled(enabled bool) {
sslEnabled = enabled
}
+
func IsProvider() bool {
return providerConfig != nil
}
diff --git a/config/config_loader_test.go b/config/config_loader_test.go
index b9bb809..c43a4ae 100644
--- a/config/config_loader_test.go
+++ b/config/config_loader_test.go
@@ -45,8 +45,10 @@
"github.com/apache/dubbo-go/registry"
)
-const mockConsumerConfigPath = "./testdata/consumer_config.yml"
-const mockProviderConfigPath = "./testdata/provider_config.yml"
+const (
+ mockConsumerConfigPath = "./testdata/consumer_config.yml"
+ mockProviderConfigPath = "./testdata/provider_config.yml"
+)
func TestConfigLoader(t *testing.T) {
conPath, err := filepath.Abs(mockConsumerConfigPath)
@@ -242,7 +244,6 @@
assert.Equal(t, "BDTService", consumerConfig.ApplicationConfig.Name)
assert.Equal(t, "127.0.0.1:2181", consumerConfig.Registries["hangzhouzk"].Address)
-
}
func TestConfigLoaderWithConfigCenterSingleRegistry(t *testing.T) {
@@ -301,7 +302,6 @@
assert.Equal(t, "BDTService", consumerConfig.ApplicationConfig.Name)
assert.Equal(t, "mock://127.0.0.1:2182", consumerConfig.Registries[constant.DEFAULT_KEY].Address)
-
}
func TestGetBaseConfig(t *testing.T) {
@@ -321,7 +321,8 @@
Module: "module",
Version: "1.0.0",
Owner: "dubbo",
- Environment: "test"},
+ Environment: "test",
+ },
},
Registry: &RegistryConfig{
@@ -472,8 +473,7 @@
return res
}
-type mockServiceDiscoveryRegistry struct {
-}
+type mockServiceDiscoveryRegistry struct{}
func (mr *mockServiceDiscoveryRegistry) GetUrl() *common.URL {
panic("implement me")
@@ -507,8 +507,7 @@
return &mockServiceDiscovery{}
}
-type mockServiceDiscovery struct {
-}
+type mockServiceDiscovery struct{}
func (m *mockServiceDiscovery) String() string {
panic("implement me")
diff --git a/config/consumer_config.go b/config/consumer_config.go
index ca88fe3..39c0e96 100644
--- a/config/consumer_config.go
+++ b/config/consumer_config.go
@@ -95,9 +95,9 @@
return perrors.Errorf("unmarshalYmlConfig error %v", perrors.WithStack(err))
}
consumerConfig.fileStream = bytes.NewBuffer(fileStream)
- //set method interfaceId & interfaceName
+ // set method interfaceId & interfaceName
for k, v := range consumerConfig.References {
- //set id for reference
+ // set id for reference
for _, n := range consumerConfig.References[k].Methods {
n.InterfaceName = v.InterfaceName
n.InterfaceId = k
@@ -124,7 +124,7 @@
}
func configCenterRefreshConsumer() error {
- //fresh it
+ // fresh it
var err error
if consumerConfig.Request_Timeout != "" {
if consumerConfig.RequestTimeout, err = time.ParseDuration(consumerConfig.Request_Timeout); err != nil {
diff --git a/config/graceful_shutdown.go b/config/graceful_shutdown.go
index 89ac2e3..83204c8 100644
--- a/config/graceful_shutdown.go
+++ b/config/graceful_shutdown.go
@@ -55,7 +55,6 @@
// nolint
func GracefulShutdownInit() {
-
signals := make(chan os.Signal, 1)
signal.Notify(signals, ShutdownSignals...)
@@ -83,7 +82,6 @@
// BeforeShutdown provides processing flow before shutdown
func BeforeShutdown() {
-
destroyAllRegistries()
// waiting for a short time so that the clients have enough time to get the notification that server shutdowns
// The value of configuration depends on how long the clients will get notification.
@@ -127,7 +125,6 @@
// destroyProviderProtocols destroys the provider's protocol.
// if the protocol is consumer's protocol too, we will keep it
func destroyProviderProtocols(consumerProtocols *gxset.HashSet) {
-
logger.Info("Graceful shutdown --- Destroy provider's protocols. ")
if providerConfig == nil || providerConfig.Protocols == nil {
@@ -145,7 +142,6 @@
}
func waitAndAcceptNewRequests() {
-
logger.Info("Graceful shutdown --- Keep waiting and accept new requests for a short time. ")
if providerConfig == nil || providerConfig.ShutdownConfig == nil {
return
@@ -194,7 +190,7 @@
}
func totalTimeout() time.Duration {
- var providerShutdown = defaultShutDownTime
+ providerShutdown := defaultShutDownTime
if providerConfig != nil && providerConfig.ShutdownConfig != nil {
providerShutdown = providerConfig.ShutdownConfig.GetTimeout()
}
@@ -204,7 +200,7 @@
consumerShutdown = consumerConfig.ShutdownConfig.GetTimeout()
}
- var timeout = providerShutdown
+ timeout := providerShutdown
if consumerShutdown > providerShutdown {
timeout = consumerShutdown
}
diff --git a/config/graceful_shutdown_signal_darwin.go b/config/graceful_shutdown_signal_darwin.go
index 1a557dd..9b694b5 100644
--- a/config/graceful_shutdown_signal_darwin.go
+++ b/config/graceful_shutdown_signal_darwin.go
@@ -24,11 +24,15 @@
var (
// ShutdownSignals receives shutdown signals to process
- ShutdownSignals = []os.Signal{os.Interrupt, os.Kill, syscall.SIGKILL, syscall.SIGSTOP,
+ ShutdownSignals = []os.Signal{
+ os.Interrupt, os.Kill, syscall.SIGKILL, syscall.SIGSTOP,
syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP,
- syscall.SIGABRT, syscall.SIGSYS, syscall.SIGTERM}
+ syscall.SIGABRT, syscall.SIGSYS, syscall.SIGTERM,
+ }
// DumpHeapShutdownSignals receives shutdown signals to process
- DumpHeapShutdownSignals = []os.Signal{syscall.SIGQUIT, syscall.SIGILL,
- syscall.SIGTRAP, syscall.SIGABRT, syscall.SIGSYS}
+ DumpHeapShutdownSignals = []os.Signal{
+ syscall.SIGQUIT, syscall.SIGILL,
+ syscall.SIGTRAP, syscall.SIGABRT, syscall.SIGSYS,
+ }
)
diff --git a/config/graceful_shutdown_signal_linux.go b/config/graceful_shutdown_signal_linux.go
index 1a557dd..9b694b5 100644
--- a/config/graceful_shutdown_signal_linux.go
+++ b/config/graceful_shutdown_signal_linux.go
@@ -24,11 +24,15 @@
var (
// ShutdownSignals receives shutdown signals to process
- ShutdownSignals = []os.Signal{os.Interrupt, os.Kill, syscall.SIGKILL, syscall.SIGSTOP,
+ ShutdownSignals = []os.Signal{
+ os.Interrupt, os.Kill, syscall.SIGKILL, syscall.SIGSTOP,
syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP,
- syscall.SIGABRT, syscall.SIGSYS, syscall.SIGTERM}
+ syscall.SIGABRT, syscall.SIGSYS, syscall.SIGTERM,
+ }
// DumpHeapShutdownSignals receives shutdown signals to process
- DumpHeapShutdownSignals = []os.Signal{syscall.SIGQUIT, syscall.SIGILL,
- syscall.SIGTRAP, syscall.SIGABRT, syscall.SIGSYS}
+ DumpHeapShutdownSignals = []os.Signal{
+ syscall.SIGQUIT, syscall.SIGILL,
+ syscall.SIGTRAP, syscall.SIGABRT, syscall.SIGSYS,
+ }
)
diff --git a/config/graceful_shutdown_signal_windows.go b/config/graceful_shutdown_signal_windows.go
index 89edd27..17c209e 100644
--- a/config/graceful_shutdown_signal_windows.go
+++ b/config/graceful_shutdown_signal_windows.go
@@ -24,9 +24,11 @@
var (
// ShutdownSignals receives shutdown signals to process
- ShutdownSignals = []os.Signal{os.Interrupt, os.Kill, syscall.SIGKILL,
+ ShutdownSignals = []os.Signal{
+ os.Interrupt, os.Kill, syscall.SIGKILL,
syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP,
- syscall.SIGABRT, syscall.SIGTERM}
+ syscall.SIGABRT, syscall.SIGTERM,
+ }
// DumpHeapShutdownSignals receives shutdown signals to process
DumpHeapShutdownSignals = []os.Signal{syscall.SIGQUIT, syscall.SIGILL, syscall.SIGTRAP, syscall.SIGABRT}
diff --git a/config/graceful_shutdown_test.go b/config/graceful_shutdown_test.go
index de20357..851ec75 100644
--- a/config/graceful_shutdown_test.go
+++ b/config/graceful_shutdown_test.go
@@ -57,7 +57,8 @@
ShutdownConfig: &ShutdownConfig{
Timeout: "1",
StepTimeout: "1s",
- }}
+ },
+ }
providerProtocols := map[string]*ProtocolConfig{}
providerProtocols[constant.DUBBO] = &ProtocolConfig{
diff --git a/config/instance/metadata_report_test.go b/config/instance/metadata_report_test.go
index 110903a..7d4a93a 100644
--- a/config/instance/metadata_report_test.go
+++ b/config/instance/metadata_report_test.go
@@ -42,15 +42,13 @@
assert.NotNil(t, rpt)
}
-type mockMetadataReportFactory struct {
-}
+type mockMetadataReportFactory struct{}
func (m *mockMetadataReportFactory) CreateMetadataReport(*common.URL) report.MetadataReport {
return &mockMetadataReport{}
}
-type mockMetadataReport struct {
-}
+type mockMetadataReport struct{}
func (m mockMetadataReport) StoreProviderMetadata(*identifier.MetadataIdentifier, string) error {
panic("implement me")
diff --git a/config/metric_config.go b/config/metric_config.go
index 73a3ca1..9af1691 100644
--- a/config/metric_config.go
+++ b/config/metric_config.go
@@ -17,9 +17,7 @@
package config
-var (
- defaultHistogramBucket = []float64{10, 50, 100, 200, 500, 1000, 10000}
-)
+var defaultHistogramBucket = []float64{10, 50, 100, 200, 500, 1000, 10000}
// This is the config struct for all metrics implementation
type MetricConfig struct {
diff --git a/config/reference_config.go b/config/reference_config.go
index f71c7ec..a97018a 100644
--- a/config/reference_config.go
+++ b/config/reference_config.go
@@ -194,7 +194,7 @@
func (c *ReferenceConfig) getUrlMap() url.Values {
urlMap := url.Values{}
- //first set user params
+ // first set user params
for k, v := range c.Params {
urlMap.Set(k, v)
}
@@ -215,11 +215,11 @@
if len(c.RequestTimeout) != 0 {
urlMap.Set(constant.TIMEOUT_KEY, c.RequestTimeout)
}
- //getty invoke async or sync
+ // getty invoke async or sync
urlMap.Set(constant.ASYNC_KEY, strconv.FormatBool(c.Async))
urlMap.Set(constant.STICKY_KEY, strconv.FormatBool(c.Sticky))
- //application info
+ // application info
urlMap.Set(constant.APPLICATION_KEY, consumerConfig.ApplicationConfig.Name)
urlMap.Set(constant.ORGANIZATION_KEY, consumerConfig.ApplicationConfig.Organization)
urlMap.Set(constant.NAME_KEY, consumerConfig.ApplicationConfig.Name)
@@ -228,8 +228,8 @@
urlMap.Set(constant.OWNER_KEY, consumerConfig.ApplicationConfig.Owner)
urlMap.Set(constant.ENVIRONMENT_KEY, consumerConfig.ApplicationConfig.Environment)
- //filter
- var defaultReferenceFilter = constant.DEFAULT_REFERENCE_FILTERS
+ // filter
+ defaultReferenceFilter := constant.DEFAULT_REFERENCE_FILTERS
if c.Generic {
defaultReferenceFilter = constant.GENERIC_REFERENCE_FILTERS + "," + defaultReferenceFilter
}
diff --git a/config/reference_config_test.go b/config/reference_config_test.go
index 0207e1f..f47bb4b 100644
--- a/config/reference_config_test.go
+++ b/config/reference_config_test.go
@@ -46,7 +46,8 @@
Module: "module",
Version: "2.6.0",
Owner: "dubbo",
- Environment: "test"},
+ Environment: "test",
+ },
},
Registries: map[string]*RegistryConfig{
@@ -120,8 +121,7 @@
var mockProvider = new(MockProvider)
-type MockProvider struct {
-}
+type MockProvider struct{}
func (m *MockProvider) Reference() string {
return "MockProvider"
@@ -148,7 +148,8 @@
Module: "module",
Version: "2.6.0",
Owner: "dubbo",
- Environment: "test"},
+ Environment: "test",
+ },
},
Registry: &RegistryConfig{
@@ -359,6 +360,7 @@
func (*mockRegistryProtocol) Destroy() {
// Destroy is a mock function
}
+
func getRegistryUrl(invoker protocol.Invoker) *common.URL {
// here add * for return a new url
url := invoker.GetUrl()
diff --git a/config/registry_config.go b/config/registry_config.go
index ed81a07..462e3b8 100644
--- a/config/registry_config.go
+++ b/config/registry_config.go
@@ -129,7 +129,7 @@
urlMap.Set(constant.REGISTRY_KEY+"."+constant.REGISTRY_LABEL_KEY, strconv.FormatBool(true))
urlMap.Set(constant.REGISTRY_KEY+"."+constant.PREFERRED_KEY, strconv.FormatBool(c.Preferred))
urlMap.Set(constant.REGISTRY_KEY+"."+constant.ZONE_KEY, c.Zone)
- //urlMap.Set(constant.REGISTRY_KEY+"."+constant.ZONE_FORCE_KEY, strconv.FormatBool(c.ZoneForce))
+ // urlMap.Set(constant.REGISTRY_KEY+"."+constant.ZONE_FORCE_KEY, strconv.FormatBool(c.ZoneForce))
urlMap.Set(constant.REGISTRY_KEY+"."+constant.WEIGHT_KEY, strconv.FormatInt(c.Weight, 10))
urlMap.Set(constant.REGISTRY_TTL_KEY, c.TTL)
for k, v := range c.Params {
diff --git a/config/remote_config_test.go b/config/remote_config_test.go
index 82535fd..cd21369 100644
--- a/config/remote_config_test.go
+++ b/config/remote_config_test.go
@@ -20,6 +20,7 @@
import (
"testing"
)
+
import (
"github.com/stretchr/testify/assert"
)
diff --git a/config/router_config.go b/config/router_config.go
index ea19b46..06758b4 100644
--- a/config/router_config.go
+++ b/config/router_config.go
@@ -29,9 +29,7 @@
"github.com/apache/dubbo-go/common/yaml"
)
-var (
- routerURLSet = gxset.NewSet()
-)
+var routerURLSet = gxset.NewSet()
// LocalRouterRules defines the local router config structure
type LocalRouterRules struct {
diff --git a/config/router_config_test.go b/config/router_config_test.go
index 13af705..d2acf9d 100644
--- a/config/router_config_test.go
+++ b/config/router_config_test.go
@@ -31,12 +31,13 @@
_ "github.com/apache/dubbo-go/cluster/router/condition"
)
-const testYML = "testdata/router_config.yml"
-const testMultiRouterYML = "testdata/router_multi_config.yml"
-const errorTestYML = "testdata/router_config_error.yml"
+const (
+ testYML = "testdata/router_config.yml"
+ testMultiRouterYML = "testdata/router_multi_config.yml"
+ errorTestYML = "testdata/router_config_error.yml"
+)
func TestString(t *testing.T) {
-
s := "a1=>a2"
s1 := "=>a2"
s2 := "a1=>"
diff --git a/config/service_config_test.go b/config/service_config_test.go
index aea0bde..76800d9 100644
--- a/config/service_config_test.go
+++ b/config/service_config_test.go
@@ -18,8 +18,9 @@
package config
import (
- "github.com/apache/dubbo-go/common"
"testing"
+
+ "github.com/apache/dubbo-go/common"
)
import (
@@ -195,7 +196,7 @@
protocolConfigs = append(protocolConfigs, &ProtocolConfig{
Ip: ip,
})
- //assert.NoError(t, err)
+ // assert.NoError(t, err)
ports := getRandomPort(protocolConfigs)
assert.Equal(t, ports.Len(), len(protocolConfigs))
diff --git a/config_center/apollo/factory.go b/config_center/apollo/factory.go
index c52d942..e3a8364 100644
--- a/config_center/apollo/factory.go
+++ b/config_center/apollo/factory.go
@@ -42,5 +42,4 @@
}
dynamicConfiguration.SetParser(&parser.DefaultConfigurationParser{})
return dynamicConfiguration, err
-
}
diff --git a/config_center/apollo/impl_test.go b/config_center/apollo/impl_test.go
index 3b2cb16..8f4c315 100644
--- a/config_center/apollo/impl_test.go
+++ b/config_center/apollo/impl_test.go
@@ -59,8 +59,7 @@
}]`
)
-var (
- mockConfigRes = `{
+var mockConfigRes = `{
"appId": "testApplication_yang",
"cluster": "default",
"namespaceName": "mockDubbog.properties",
@@ -116,7 +115,6 @@
},
"releaseKey": "20191104105242-0f13805d89f834a4"
}`
-)
func initApollo() *httptest.Server {
handlerMap := make(map[string]func(http.ResponseWriter, *http.Request), 1)
@@ -215,13 +213,13 @@
},
"releaseKey": "20191104105242-0f13805d89f834a4"
}`
- //test add
+ // test add
apollo.AddListener(mockNamespace, listener)
listener.wg.Wait()
assert.Equal(t, "mockDubbog.properties", listener.event)
assert.Greater(t, listener.count, 0)
- //test remove
+ // test remove
apollo.RemoveListener(mockNamespace, listener)
listenerCount := 0
apollo.listeners.Range(func(_, value interface{}) bool {
diff --git a/config_center/apollo/listener.go b/config_center/apollo/listener.go
index 44d3255..215c74d 100644
--- a/config_center/apollo/listener.go
+++ b/config_center/apollo/listener.go
@@ -42,7 +42,6 @@
// OnChange process each listener
func (a *apolloListener) OnChange(changeEvent *storage.ChangeEvent) {
-
}
// OnNewestChange process each listener by all changes
diff --git a/config_center/base_dynamic_configuration.go b/config_center/base_dynamic_configuration.go
index 3d67578..b56ada1 100644
--- a/config_center/base_dynamic_configuration.go
+++ b/config_center/base_dynamic_configuration.go
@@ -18,8 +18,7 @@
package config_center
// BaseDynamicConfiguration will default implementation DynamicConfiguration some method
-type BaseDynamicConfiguration struct {
-}
+type BaseDynamicConfiguration struct{}
// RemoveConfig
func (bdc *BaseDynamicConfiguration) RemoveConfig(string, string) error {
diff --git a/config_center/configurator/override_test.go b/config_center/configurator/override_test.go
index 4d2552d..a7fced0 100644
--- a/config_center/configurator/override_test.go
+++ b/config_center/configurator/override_test.go
@@ -71,7 +71,6 @@
assert.NoError(t, err)
configurator.Configure(providerUrl)
assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, ""))
-
}
func TestConfigureVersion2p7(t *testing.T) {
@@ -83,5 +82,4 @@
assert.NoError(t, err)
configurator.Configure(providerUrl)
assert.Equal(t, failfast, providerUrl.GetParam(constant.CLUSTER_KEY, ""))
-
}
diff --git a/config_center/file/factory.go b/config_center/file/factory.go
index 2dda900..5dc8be1 100644
--- a/config_center/file/factory.go
+++ b/config_center/file/factory.go
@@ -35,8 +35,7 @@
})
}
-type fileDynamicConfigurationFactory struct {
-}
+type fileDynamicConfigurationFactory struct{}
// GetDynamicConfiguration Get Configuration with URL
func (f *fileDynamicConfigurationFactory) GetDynamicConfiguration(url *common.URL) (config_center.DynamicConfiguration,
diff --git a/config_center/file/impl.go b/config_center/file/impl.go
index 6489a07..112b0bb 100644
--- a/config_center/file/impl.go
+++ b/config_center/file/impl.go
@@ -40,9 +40,7 @@
"github.com/apache/dubbo-go/config_center/parser"
)
-var (
- osType = runtime.GOOS
-)
+var osType = runtime.GOOS
const (
windowsOS = "windows"
diff --git a/config_center/file/listener.go b/config_center/file/listener.go
index d569030..8e7aa61 100644
--- a/config_center/file/listener.go
+++ b/config_center/file/listener.go
@@ -128,7 +128,8 @@
// reference from https://stackoverflow.com/questions/34018908/golang-why-dont-we-have-a-set-datastructure
// make a map[your type]struct{} like set in java
listeners, loaded := cl.keyListeners.LoadOrStore(key, map[config_center.ConfigurationListener]struct{}{
- listener: {}})
+ listener: {},
+ })
if loaded {
listeners.(map[config_center.ConfigurationListener]struct{})[listener] = struct{}{}
cl.keyListeners.Store(key, listeners)
diff --git a/config_center/mock_dynamic_config.go b/config_center/mock_dynamic_config.go
index 9bebd60..5688499 100644
--- a/config_center/mock_dynamic_config.go
+++ b/config_center/mock_dynamic_config.go
@@ -83,7 +83,6 @@
dynamicConfiguration.content = f.Content
}
return dynamicConfiguration, err
-
}
// PublishConfig will publish the config with the (key, group, value) pair
@@ -116,7 +115,6 @@
// GetConfig returns content of MockDynamicConfiguration
func (c *MockDynamicConfiguration) GetConfig(_ string, _ ...Option) (string, error) {
-
return c.content, nil
}
@@ -158,7 +156,8 @@
Key: mockServiceName,
Enabled: true,
Configs: []parser.ConfigItem{
- {Type: parser.GeneralType,
+ {
+ Type: parser.GeneralType,
Enabled: true,
Addresses: []string{"0.0.0.0"},
Services: []string{mockServiceName},
@@ -180,7 +179,8 @@
Key: mockServiceName,
Enabled: true,
Configs: []parser.ConfigItem{
- {Type: parser.ScopeApplication,
+ {
+ Type: parser.ScopeApplication,
Enabled: true,
Addresses: []string{"0.0.0.0"},
Services: []string{mockServiceName},
diff --git a/config_center/nacos/client.go b/config_center/nacos/client.go
index 1e96b36..d6af806 100644
--- a/config_center/nacos/client.go
+++ b/config_center/nacos/client.go
@@ -65,7 +65,7 @@
type options struct {
nacosName string
- //client *NacosClient
+ // client *NacosClient
}
// WithNacosName Set nacos name
@@ -94,7 +94,7 @@
}
nacosAddresses := strings.Split(url.Location, ",")
if container.NacosClient() == nil {
- //in dubbo ,every registry only connect one node ,so this is []string{r.Address}
+ // in dubbo ,every registry only connect one node ,so this is []string{r.Address}
newClient, err := newNacosClient(os.nacosName, nacosAddresses, timeout, url)
if err != nil {
logger.Errorf("newNacosClient(name{%s}, nacos address{%v}, timeout{%d}) = error{%v}",
diff --git a/config_center/nacos/facade.go b/config_center/nacos/facade.go
index d089ed2..b81c224 100644
--- a/config_center/nacos/facade.go
+++ b/config_center/nacos/facade.go
@@ -21,6 +21,7 @@
"sync"
"time"
)
+
import (
"github.com/apache/dubbo-getty"
perrors "github.com/pkg/errors"
diff --git a/config_center/nacos/factory.go b/config_center/nacos/factory.go
index 3de91ea..da06abd 100644
--- a/config_center/nacos/factory.go
+++ b/config_center/nacos/factory.go
@@ -28,8 +28,7 @@
extension.SetConfigCenterFactory("nacos", func() config_center.DynamicConfigurationFactory { return &nacosDynamicConfigurationFactory{} })
}
-type nacosDynamicConfigurationFactory struct {
-}
+type nacosDynamicConfigurationFactory struct{}
// GetDynamicConfiguration Get Configuration with URL
func (f *nacosDynamicConfigurationFactory) GetDynamicConfiguration(url *common.URL) (config_center.DynamicConfiguration, error) {
@@ -39,5 +38,4 @@
}
dynamicConfiguration.SetParser(&parser.DefaultConfigurationParser{})
return dynamicConfiguration, err
-
}
diff --git a/config_center/nacos/impl.go b/config_center/nacos/impl.go
index 7c67930..8e56d23 100644
--- a/config_center/nacos/impl.go
+++ b/config_center/nacos/impl.go
@@ -72,7 +72,6 @@
c.wg.Add(1)
go HandleClientRestart(c)
return c, err
-
}
// AddListener Add listener
@@ -97,7 +96,6 @@
// PublishConfig will publish the config with the (key, group, value) pair
func (n *nacosDynamicConfiguration) PublishConfig(key string, group string, value string) error {
-
group = n.resolvedGroup(group)
ok, err := (*n.client.Client()).PublishConfig(vo.ConfigParam{
@@ -105,7 +103,6 @@
Group: group,
Content: value,
})
-
if err != nil {
return perrors.WithStack(err)
}
diff --git a/config_center/nacos/impl_test.go b/config_center/nacos/impl_test.go
index b7bd94b..0372a6c 100644
--- a/config_center/nacos/impl_test.go
+++ b/config_center/nacos/impl_test.go
@@ -117,7 +117,6 @@
assert.Nil(t, err)
assert.Equal(t, 1, configs.Size())
assert.True(t, configs.Contains("application"))
-
}
func TestNacosDynamicConfigurationPublishConfig(t *testing.T) {
@@ -139,7 +138,7 @@
}
func TestRemoveListener(_ *testing.T) {
- //TODO not supported in current go_nacos_sdk version
+ // TODO not supported in current go_nacos_sdk version
}
type mockDataListener struct {
diff --git a/config_center/parser/configuration_parser.go b/config_center/parser/configuration_parser.go
index b104d3d..eb811c0 100644
--- a/config_center/parser/configuration_parser.go
+++ b/config_center/parser/configuration_parser.go
@@ -112,7 +112,7 @@
// serviceItemToUrls is used to transfer item and config to urls
func serviceItemToUrls(item ConfigItem, config ConfiguratorConfig) ([]*common.URL, error) {
- var addresses = item.Addresses
+ addresses := item.Addresses
if len(addresses) == 0 {
addresses = append(addresses, constant.ANYHOST_VALUE)
}
@@ -159,7 +159,7 @@
// nolint
func appItemToUrls(item ConfigItem, config ConfiguratorConfig) ([]*common.URL, error) {
- var addresses = item.Addresses
+ addresses := item.Addresses
if len(addresses) == 0 {
addresses = append(addresses, constant.ANYHOST_VALUE)
}
diff --git a/config_center/zookeeper/factory.go b/config_center/zookeeper/factory.go
index 3f4690d..8e91972 100644
--- a/config_center/zookeeper/factory.go
+++ b/config_center/zookeeper/factory.go
@@ -28,8 +28,7 @@
extension.SetConfigCenterFactory("zookeeper", func() config_center.DynamicConfigurationFactory { return &zookeeperDynamicConfigurationFactory{} })
}
-type zookeeperDynamicConfigurationFactory struct {
-}
+type zookeeperDynamicConfigurationFactory struct{}
func (f *zookeeperDynamicConfigurationFactory) GetDynamicConfiguration(url *common.URL) (config_center.DynamicConfiguration, error) {
dynamicConfiguration, err := newZookeeperDynamicConfiguration(url)
@@ -38,5 +37,4 @@
}
dynamicConfiguration.SetParser(&parser.DefaultConfigurationParser{})
return dynamicConfiguration, err
-
}
diff --git a/config_center/zookeeper/impl.go b/config_center/zookeeper/impl.go
index e24e63f..082bfbe 100644
--- a/config_center/zookeeper/impl.go
+++ b/config_center/zookeeper/impl.go
@@ -53,7 +53,7 @@
done chan struct{}
client *gxzookeeper.ZookeeperClient
- //listenerLock sync.Mutex
+ // listenerLock sync.Mutex
listener *zookeeper.ZkEventListener
cacheListener *CacheListener
parser parser.ConfigurationParser
@@ -78,7 +78,6 @@
err = c.client.Create(c.rootPath)
c.listener.ListenServiceEvent(url, c.rootPath, c.cacheListener)
return c, err
-
}
func (c *zookeeperDynamicConfiguration) AddListener(key string, listener config_center.ConfigurationListener, opions ...config_center.Option) {
@@ -90,7 +89,6 @@
}
func (c *zookeeperDynamicConfiguration) GetProperties(key string, opts ...config_center.Option) (string, error) {
-
tmpOpts := &config_center.Options{}
for _, opt := range opts {
opt(tmpOpts)
diff --git a/config_center/zookeeper/impl_test.go b/config_center/zookeeper/impl_test.go
index 7f17153..26d7870 100644
--- a/config_center/zookeeper/impl_test.go
+++ b/config_center/zookeeper/impl_test.go
@@ -218,7 +218,6 @@
assert.Nil(t, err)
assert.Equal(t, 1, keys.Size())
assert.True(t, keys.Contains(key))
-
}
type mockDataListener struct {
diff --git a/config_center/zookeeper/listener.go b/config_center/zookeeper/listener.go
index 244451a..d93e9d5 100644
--- a/config_center/zookeeper/listener.go
+++ b/config_center/zookeeper/listener.go
@@ -41,7 +41,6 @@
// AddListener will add a listener if loaded
func (l *CacheListener) AddListener(key string, listener config_center.ConfigurationListener) {
-
// reference from https://stackoverflow.com/questions/34018908/golang-why-dont-we-have-a-set-datastructure
// make a map[your type]struct{} like set in java
listeners, loaded := l.keyListeners.LoadOrStore(key, map[config_center.ConfigurationListener]struct{}{listener: {}})
@@ -62,7 +61,7 @@
// DataChange changes all listeners' event
func (l *CacheListener) DataChange(event remoting.Event) bool {
if event.Content == "" {
- //meanings new node
+ // meanings new node
return true
}
key := l.pathToKey(event.Path)
@@ -82,7 +81,7 @@
if strings.HasSuffix(key, constant.CONFIGURATORS_SUFFIX) ||
strings.HasSuffix(key, constant.TagRouterRuleSuffix) ||
strings.HasSuffix(key, constant.ConditionRouterRuleSuffix) {
- //governance config, so we remove the "dubbo." prefix
+ // governance config, so we remove the "dubbo." prefix
return key[strings.Index(key, ".")+1:]
}
return key
diff --git a/filter/filter_impl/access_log_filter.go b/filter/filter_impl/access_log_filter.go
index 167b5ed..6aa4e65 100644
--- a/filter/filter_impl/access_log_filter.go
+++ b/filter/filter_impl/access_log_filter.go
@@ -34,7 +34,7 @@
)
const (
- //used in URL.
+ // used in URL.
// nolint
FileDateFormat = "2006-01-02"
@@ -43,7 +43,7 @@
// nolint
LogMaxBuffer = 5000
// nolint
- LogFileMode = 0600
+ LogFileMode = 0o600
// those fields are the data collected by this filter
diff --git a/filter/filter_impl/active_filter.go b/filter/filter_impl/active_filter.go
index 795de96..a391cb3 100644
--- a/filter/filter_impl/active_filter.go
+++ b/filter/filter_impl/active_filter.go
@@ -40,8 +40,7 @@
}
// ActiveFilter tracks the requests status
-type ActiveFilter struct {
-}
+type ActiveFilter struct{}
// Invoke starts to record the requests status
func (ef *ActiveFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
diff --git a/filter/filter_impl/active_filter_test.go b/filter/filter_impl/active_filter_test.go
index 2397503..bb1676d 100644
--- a/filter/filter_impl/active_filter_test.go
+++ b/filter/filter_impl/active_filter_test.go
@@ -47,7 +47,6 @@
invoker.EXPECT().GetUrl().Return(url).Times(1)
filter.Invoke(context.Background(), invoker, invoc)
assert.True(t, invoc.AttachmentsByKey(dubboInvokeStartTime, "") != "")
-
}
func TestActiveFilterOnResponse(t *testing.T) {
@@ -79,5 +78,4 @@
assert.True(t, urlStatus.GetFailedElapsed() >= int64(elapsed))
assert.True(t, urlStatus.GetLastRequestFailedTimestamp() != int64(0))
assert.True(t, methodStatus.GetLastRequestFailedTimestamp() != int64(0))
-
}
diff --git a/filter/filter_impl/auth/accesskey_storage.go b/filter/filter_impl/auth/accesskey_storage.go
index 90d3efb..de49bcb 100644
--- a/filter/filter_impl/auth/accesskey_storage.go
+++ b/filter/filter_impl/auth/accesskey_storage.go
@@ -26,8 +26,7 @@
)
// DefaultAccesskeyStorage is the default implementation of AccesskeyStorage
-type DefaultAccesskeyStorage struct {
-}
+type DefaultAccesskeyStorage struct{}
// GetAccessKeyPair retrieves AccessKeyPair from url by the key "accessKeyId" and "secretAccessKey"
func (storage *DefaultAccesskeyStorage) GetAccessKeyPair(invocation protocol.Invocation, url *common.URL) *filter.AccessKeyPair {
diff --git a/filter/filter_impl/auth/consumer_sign.go b/filter/filter_impl/auth/consumer_sign.go
index 823db82..3e298cd 100644
--- a/filter/filter_impl/auth/consumer_sign.go
+++ b/filter/filter_impl/auth/consumer_sign.go
@@ -21,6 +21,7 @@
"context"
"fmt"
)
+
import (
"github.com/apache/dubbo-go/common/constant"
"github.com/apache/dubbo-go/common/extension"
@@ -30,8 +31,7 @@
)
// ConsumerSignFilter signs the request on consumer side
-type ConsumerSignFilter struct {
-}
+type ConsumerSignFilter struct{}
func init() {
extension.SetFilter(constant.CONSUMER_SIGN_FILTER, getConsumerSignFilter)
@@ -47,7 +47,6 @@
})
if err != nil {
panic(fmt.Sprintf("Sign for invocation %s # %s failed", url.ServiceKey(), invocation.MethodName()))
-
}
return invoker.Invoke(ctx, invocation)
}
diff --git a/filter/filter_impl/auth/default_authenticator.go b/filter/filter_impl/auth/default_authenticator.go
index 7c7131c..5a08b54 100644
--- a/filter/filter_impl/auth/default_authenticator.go
+++ b/filter/filter_impl/auth/default_authenticator.go
@@ -20,9 +20,10 @@
import (
"errors"
"fmt"
- "github.com/apache/dubbo-go/filter"
"strconv"
"time"
+
+ "github.com/apache/dubbo-go/filter"
)
import (
@@ -38,8 +39,7 @@
}
// DefaultAuthenticator is the default implementation of Authenticator
-type DefaultAuthenticator struct {
-}
+type DefaultAuthenticator struct{}
// Sign adds the signature to the invocation
func (authenticator *DefaultAuthenticator) Sign(invocation protocol.Invocation, url *common.URL) error {
@@ -65,7 +65,6 @@
// getSignature
// get signature by the metadata and params of the invocation
func getSignature(url *common.URL, invocation protocol.Invocation, secrectKey string, currentTime string) (string, error) {
-
requestString := fmt.Sprintf(constant.SIGNATURE_STRING_FORMAT,
url.ColonSeparatedKey(), invocation.MethodName(), secrectKey, currentTime)
var signature string
@@ -125,7 +124,6 @@
}
func doAuthWork(url *common.URL, do func(filter.Authenticator) error) error {
-
shouldAuth := url.GetParamBool(constant.SERVICE_AUTH_KEY, false)
if shouldAuth {
authenticator := extension.GetAuthenticator(url.GetParam(constant.AUTHENTICATOR_KEY, constant.DEFAULT_AUTHENTICATOR))
diff --git a/filter/filter_impl/auth/default_authenticator_test.go b/filter/filter_impl/auth/default_authenticator_test.go
index d915b6a..c253caf 100644
--- a/filter/filter_impl/auth/default_authenticator_test.go
+++ b/filter/filter_impl/auth/default_authenticator_test.go
@@ -50,7 +50,7 @@
requestTime := strconv.Itoa(int(time.Now().Unix() * 1000))
signature, _ := getSignature(testurl, inv, secret, requestTime)
- var authenticator = &DefaultAuthenticator{}
+ authenticator := &DefaultAuthenticator{}
invcation := invocation.NewRPCInvocation("test", parmas, map[string]interface{}{
constant.REQUEST_SIGNATURE_KEY: signature,
@@ -69,7 +69,6 @@
})
err = authenticator.Authenticate(invcation, testurl)
assert.NotNil(t, err)
-
}
func TestDefaultAuthenticator_Sign(t *testing.T) {
@@ -84,7 +83,6 @@
assert.NotEqual(t, inv.AttachmentsByKey(constant.CONSUMER, ""), "")
assert.NotEqual(t, inv.AttachmentsByKey(constant.REQUEST_TIMESTAMP_KEY, ""), "")
assert.Equal(t, inv.AttachmentsByKey(constant.AK_KEY, ""), "akey")
-
}
func Test_getAccessKeyPairSuccess(t *testing.T) {
@@ -114,7 +112,6 @@
common.WithParamsValue(constant.ACCESS_KEY_ID_KEY, "akey"), common.WithParamsValue(constant.ACCESS_KEY_STORAGE_KEY, "dubbo"))
_, e = getAccessKeyPair(invcation, testurl)
assert.NoError(t, e)
-
}
func Test_getSignatureWithinParams(t *testing.T) {
diff --git a/filter/filter_impl/auth/provider_auth.go b/filter/filter_impl/auth/provider_auth.go
index 774fdb2..9a6490d 100644
--- a/filter/filter_impl/auth/provider_auth.go
+++ b/filter/filter_impl/auth/provider_auth.go
@@ -30,8 +30,7 @@
)
// ProviderAuthFilter verifies the correctness of the signature on provider side
-type ProviderAuthFilter struct {
-}
+type ProviderAuthFilter struct{}
func init() {
extension.SetFilter(constant.PROVIDER_AUTH_FILTER, getProviderAuthFilter)
diff --git a/filter/filter_impl/auth/provider_auth_test.go b/filter/filter_impl/auth/provider_auth_test.go
index dc130b5..9e68b64 100644
--- a/filter/filter_impl/auth/provider_auth_test.go
+++ b/filter/filter_impl/auth/provider_auth_test.go
@@ -70,5 +70,4 @@
assert.Equal(t, result, filter.Invoke(context.Background(), invoker, inv))
url.SetParam(constant.SERVICE_AUTH_KEY, "true")
assert.Equal(t, result, filter.Invoke(context.Background(), invoker, inv))
-
}
diff --git a/filter/filter_impl/auth/sign_util_test.go b/filter/filter_impl/auth/sign_util_test.go
index a4aaf2d..69203e6 100644
--- a/filter/filter_impl/auth/sign_util_test.go
+++ b/filter/filter_impl/auth/sign_util_test.go
@@ -56,7 +56,6 @@
key := "key"
signature := Sign(metadata, key)
assert.NotNil(t, signature)
-
}
func TestSignWithParams(t *testing.T) {
diff --git a/filter/filter_impl/execute_limit_filter.go b/filter/filter_impl/execute_limit_filter.go
index 3561161..fdd472c 100644
--- a/filter/filter_impl/execute_limit_filter.go
+++ b/filter/filter_impl/execute_limit_filter.go
@@ -134,8 +134,10 @@
atomic.AddInt64(&state.concurrentCount, -1)
}
-var executeLimitOnce sync.Once
-var executeLimitFilter *ExecuteLimitFilter
+var (
+ executeLimitOnce sync.Once
+ executeLimitFilter *ExecuteLimitFilter
+)
// GetExecuteLimitFilter returns the singleton ExecuteLimitFilter instance
func GetExecuteLimitFilter() filter.Filter {
diff --git a/filter/filter_impl/generic_filter.go b/filter/filter_impl/generic_filter.go
index cf307d0..f184bd3 100644
--- a/filter/filter_impl/generic_filter.go
+++ b/filter/filter_impl/generic_filter.go
@@ -38,7 +38,7 @@
const (
// GENERIC
- //generic module name
+ // generic module name
GENERIC = "generic"
)
@@ -115,14 +115,14 @@
return result
} else if t.Kind() == reflect.Slice {
value := reflect.ValueOf(obj)
- var newTemps = make([]interface{}, 0, value.Len())
+ newTemps := make([]interface{}, 0, value.Len())
for i := 0; i < value.Len(); i++ {
newTemp := struct2MapAll(value.Index(i).Interface())
newTemps = append(newTemps, newTemp)
}
return newTemps
} else if t.Kind() == reflect.Map {
- var newTempMap = make(map[interface{}]interface{}, v.Len())
+ newTempMap := make(map[interface{}]interface{}, v.Len())
iter := v.MapRange()
for iter.Next() {
if !iter.Value().CanInterface() {
diff --git a/filter/filter_impl/generic_service_filter_test.go b/filter/filter_impl/generic_service_filter_test.go
index c755a2d..6b80d21 100644
--- a/filter/filter_impl/generic_service_filter_test.go
+++ b/filter/filter_impl/generic_service_filter_test.go
@@ -93,7 +93,8 @@
hessian.Object(append(make([]map[string]interface{}, 1), m)),
hessian.Object("111"),
hessian.Object(append(make([]map[string]interface{}, 1), m)),
- hessian.Object("222")},
+ hessian.Object("222"),
+ },
}
s := &TestService{}
_, _ = common.ServiceMap.Register("com.test.Path", "testprotocol", "", "", s)
diff --git a/filter/filter_impl/graceful_shutdown_filter.go b/filter/filter_impl/graceful_shutdown_filter.go
index 4a4e8ce..f79123c 100644
--- a/filter/filter_impl/graceful_shutdown_filter.go
+++ b/filter/filter_impl/graceful_shutdown_filter.go
@@ -32,10 +32,10 @@
)
func init() {
- var consumerFiler = &gracefulShutdownFilter{
+ consumerFiler := &gracefulShutdownFilter{
shutdownConfig: config.GetConsumerConfig().ShutdownConfig,
}
- var providerFilter = &gracefulShutdownFilter{
+ providerFilter := &gracefulShutdownFilter{
shutdownConfig: config.GetProviderConfig().ShutdownConfig,
}
diff --git a/filter/filter_impl/graceful_shutdown_filter_test.go b/filter/filter_impl/graceful_shutdown_filter_test.go
index b16956e..870c808 100644
--- a/filter/filter_impl/graceful_shutdown_filter_test.go
+++ b/filter/filter_impl/graceful_shutdown_filter_test.go
@@ -72,5 +72,4 @@
})
assert.True(t, providerConfig.ShutdownConfig.RequestsFinished)
assert.Equal(t, rejectHandler, shutdownFilter.getRejectHandler())
-
}
diff --git a/filter/filter_impl/hystrix_filter.go b/filter/filter_impl/hystrix_filter.go
index d13e02c..3a7c0c4 100644
--- a/filter/filter_impl/hystrix_filter.go
+++ b/filter/filter_impl/hystrix_filter.go
@@ -23,11 +23,13 @@
"regexp"
"sync"
)
+
import (
"github.com/afex/hystrix-go/hystrix"
perrors "github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
+
import (
"github.com/apache/dubbo-go/common/extension"
"github.com/apache/dubbo-go/common/logger"
@@ -123,7 +125,7 @@
* "GetUser1": "userp_m"
*/
type HystrixFilter struct {
- COrP bool //true for consumer
+ COrP bool // true for consumer
res map[string][]*regexp.Regexp
ifNewMap sync.Map
}
@@ -179,7 +181,7 @@
}
return err
}, func(err error) error {
- //Return error and if it is caused by hystrix logic, so that it can be handled by previous filters.
+ // Return error and if it is caused by hystrix logic, so that it can be handled by previous filters.
_, ok := err.(hystrix.CircuitError)
logger.Debugf("[Hystrix Filter]Hystrix health check counted, error is: %v, failed by hystrix: %v; %s", err, ok, cmdName)
result = &protocol.RPCResult{}
@@ -197,7 +199,7 @@
// GetHystrixFilterConsumer returns HystrixFilter instance for consumer
func GetHystrixFilterConsumer() filter.Filter {
- //When first called, load the config in
+ // When first called, load the config in
consumerConfigOnce.Do(func() {
if err := initHystrixConfigConsumer(); err != nil {
logger.Warnf("[Hystrix Filter]Config load failed for consumer, error is: %v , will use default", err)
@@ -217,7 +219,7 @@
}
func getConfig(service string, method string, cOrP bool) CommandConfigWithError {
- //Find method level config
+ // Find method level config
var conf *HystrixFilterConfig
if cOrP {
conf = confConsumer
@@ -229,13 +231,13 @@
logger.Infof("[Hystrix Filter]Found method-level config for %s - %s", service, method)
return *getConf
}
- //Find service level config
+ // Find service level config
getConf = conf.Configs[conf.Services[service].ServiceConfig]
if getConf != nil {
logger.Infof("[Hystrix Filter]Found service-level config for %s - %s", service, method)
return *getConf
}
- //Find default config
+ // Find default config
getConf = conf.Configs[conf.Default]
if getConf != nil {
logger.Infof("[Hystrix Filter]Found global default config for %s - %s", service, method)
@@ -244,7 +246,6 @@
getConf = &CommandConfigWithError{}
logger.Infof("[Hystrix Filter]No config found for %s - %s, using default", service, method)
return *getConf
-
}
func initHystrixConfigConsumer() error {
diff --git a/filter/filter_impl/hystrix_filter_test.go b/filter/filter_impl/hystrix_filter_test.go
index 4973ce7..8bf7263 100644
--- a/filter/filter_impl/hystrix_filter_test.go
+++ b/filter/filter_impl/hystrix_filter_test.go
@@ -47,7 +47,7 @@
}
func mockInitHystrixConfig() {
- //Mock config
+ // Mock config
confConsumer = &HystrixFilterConfig{
make(map[string]*CommandConfigWithError),
"Default",
@@ -85,7 +85,6 @@
"GetUser": "userp_m",
},
}
-
}
func TestGetHystrixFilter(t *testing.T) {
@@ -117,7 +116,7 @@
func TestGetConfig3(t *testing.T) {
mockInitHystrixConfig()
- //This should use default
+ // This should use default
configGot := getConfig("Mock.Service", "GetMock", true)
assert.NotNil(t, configGot)
assert.Equal(t, 1000, configGot.Timeout)
@@ -186,7 +185,7 @@
resChan <- result
}()
}
- //This can not always pass the test when on travis due to concurrency, you can uncomment the code below and test it locally
+ // This can not always pass the test when on travis due to concurrency, you can uncomment the code below and test it locally
//var lastRest bool
//for i := 0; i < 50; i++ {
@@ -195,7 +194,6 @@
//Normally the last result should be true, which means the circuit has been opened
//
//assert.True(t, lastRest)
-
}
func TestHystricFilterInvokeCircuitBreakOmitException(t *testing.T) {
@@ -215,7 +213,7 @@
resChan <- result
}()
}
- //This can not always pass the test when on travis due to concurrency, you can uncomment the code below and test it locally
+ // This can not always pass the test when on travis due to concurrency, you can uncomment the code below and test it locally
//time.Sleep(time.Second * 6)
//var lastRest bool
@@ -224,7 +222,6 @@
//}
//
//assert.False(t, lastRest)
-
}
func TestGetHystrixFilterConsumer(t *testing.T) {
diff --git a/filter/filter_impl/metrics_filter.go b/filter/filter_impl/metrics_filter.go
index f473417..27eddfd 100644
--- a/filter/filter_impl/metrics_filter.go
+++ b/filter/filter_impl/metrics_filter.go
@@ -34,9 +34,7 @@
metricFilterName = "metrics"
)
-var (
- metricFilterInstance filter.Filter
-)
+var metricFilterInstance filter.Filter
// must initialized before using the filter and after loading configuration
func init() {
diff --git a/filter/filter_impl/metrics_filter_test.go b/filter/filter_impl/metrics_filter_test.go
index ac10d52..98fe129 100644
--- a/filter/filter_impl/metrics_filter_test.go
+++ b/filter/filter_impl/metrics_filter_test.go
@@ -39,7 +39,6 @@
)
func TestMetricsFilterInvoke(t *testing.T) {
-
// prepare the mock reporter
config.GetMetricConfig().Reporters = []string{"mock"}
mk := &mockReporter{}
diff --git a/filter/filter_impl/sentinel_filter.go b/filter/filter_impl/sentinel_filter.go
index 1de27ad..cbe1c38 100644
--- a/filter/filter_impl/sentinel_filter.go
+++ b/filter/filter_impl/sentinel_filter.go
@@ -186,9 +186,11 @@
func SetDubboConsumerFallback(f DubboFallback) {
sentinelDubboConsumerFallback = f
}
+
func SetDubboProviderFallback(f DubboFallback) {
sentinelDubboProviderFallback = f
}
+
func getDefaultDubboFallback() DubboFallback {
return func(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation, blockError *base.BlockError) protocol.Result {
result := &protocol.RPCResult{}
diff --git a/filter/filter_impl/sentinel_filter_test.go b/filter/filter_impl/sentinel_filter_test.go
index c6b6d42..ee0f0be 100644
--- a/filter/filter_impl/sentinel_filter_test.go
+++ b/filter/filter_impl/sentinel_filter_test.go
@@ -51,7 +51,7 @@
_, err = flow.LoadRules([]*flow.Rule{
{
Resource: interfaceResourceName,
- //MetricType: flow.QPS,
+ // MetricType: flow.QPS,
TokenCalculateStrategy: flow.Direct,
ControlBehavior: flow.Reject,
Threshold: 100,
diff --git a/filter/filter_impl/tps/tps_limit_fix_window_strategy.go b/filter/filter_impl/tps/tps_limit_fix_window_strategy.go
index d495e03..e992ece 100644
--- a/filter/filter_impl/tps/tps_limit_fix_window_strategy.go
+++ b/filter/filter_impl/tps/tps_limit_fix_window_strategy.go
@@ -68,7 +68,6 @@
// IsAllowable determines if the requests over the TPS limit within the interval.
// It is not thread-safe.
func (impl *FixedWindowTpsLimitStrategyImpl) IsAllowable() bool {
-
current := time.Now().UnixNano()
if impl.timestamp+impl.interval < current {
// it's a new window
diff --git a/filter/filter_impl/tps/tps_limiter_method_service.go b/filter/filter_impl/tps/tps_limiter_method_service.go
index f0c2764..76d06bd 100644
--- a/filter/filter_impl/tps/tps_limiter_method_service.go
+++ b/filter/filter_impl/tps/tps_limiter_method_service.go
@@ -121,7 +121,6 @@
// This implementation use concurrent map + loadOrStore to make implementation thread-safe
// You can image that even multiple threads create limiter, but only one could store the limiter into tpsState
func (limiter MethodServiceTpsLimiterImpl) IsAllowable(url *common.URL, invocation protocol.Invocation) bool {
-
methodConfigPrefix := "methods." + invocation.MethodName() + "."
methodLimitRateConfig := url.GetParam(methodConfigPrefix+constant.TPS_LIMIT_RATE_KEY, "")
@@ -193,15 +192,16 @@
// actually there is no method-level configuration, so we use the service-level configuration
result, err := strconv.ParseInt(url.GetParam(configKey, defaultVal), 0, 0)
-
if err != nil {
panic(fmt.Sprintf("Cannot parse the configuration %s, please check your configuration!", configKey))
}
return result
}
-var methodServiceTpsLimiterInstance *MethodServiceTpsLimiterImpl
-var methodServiceTpsLimiterOnce sync.Once
+var (
+ methodServiceTpsLimiterInstance *MethodServiceTpsLimiterImpl
+ methodServiceTpsLimiterOnce sync.Once
+)
// GetMethodServiceTpsLimiter will return an MethodServiceTpsLimiterImpl instance.
func GetMethodServiceTpsLimiter() filter.TpsLimiter {
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 5baa70a..cb9578f 100644
--- a/filter/filter_impl/tps/tps_limiter_method_service_test.go
+++ b/filter/filter_impl/tps/tps_limiter_method_service_test.go
@@ -21,6 +21,7 @@
"net/url"
"testing"
)
+
import (
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
diff --git a/filter/filter_impl/tps_limit_filter.go b/filter/filter_impl/tps_limit_filter.go
index ea1e3bc..210e157 100644
--- a/filter/filter_impl/tps_limit_filter.go
+++ b/filter/filter_impl/tps_limit_filter.go
@@ -20,6 +20,7 @@
import (
"context"
)
+
import (
"github.com/apache/dubbo-go/common/constant"
"github.com/apache/dubbo-go/common/extension"
@@ -53,8 +54,7 @@
* tps.limit.rejected.handler: "default", # optional, or the name of the implementation
* if the value of 'tps.limiter' is nil or empty string, the tps filter will do nothing
*/
-type TpsLimitFilter struct {
-}
+type TpsLimitFilter struct{}
// Invoke gets the configured limter to impose TPS limiting
func (t TpsLimitFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
diff --git a/filter/filter_impl/tps_limit_filter_test.go b/filter/filter_impl/tps_limit_filter_test.go
index 55a3a55..24f9827 100644
--- a/filter/filter_impl/tps_limit_filter_test.go
+++ b/filter/filter_impl/tps_limit_filter_test.go
@@ -52,7 +52,6 @@
[]interface{}{"OK"}, attch))
assert.Nil(t, result.Error())
assert.Nil(t, result.Result())
-
}
func TestGenericFilterInvokeWithDefaultTpsLimiter(t *testing.T) {
diff --git a/filter/filter_impl/tracing_filter.go b/filter/filter_impl/tracing_filter.go
index dcdbe5b..8a30c96 100644
--- a/filter/filter_impl/tracing_filter.go
+++ b/filter/filter_impl/tracing_filter.go
@@ -50,8 +50,7 @@
// if you wish to using opentracing, please add the this filter into your filter attribute in your configure file.
// notice that this could be used in both client-side and server-side.
-type tracingFilter struct {
-}
+type tracingFilter struct{}
func (tf *tracingFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result {
var (
@@ -95,9 +94,7 @@
return result
}
-var (
- tracingFilterInstance *tracingFilter
-)
+var tracingFilterInstance *tracingFilter
func newTracingFilter() filter.Filter {
if tracingFilterInstance == nil {
diff --git a/filter/handler/rejected_execution_handler_only_log.go b/filter/handler/rejected_execution_handler_only_log.go
index 5242b5b..5277b27 100644
--- a/filter/handler/rejected_execution_handler_only_log.go
+++ b/filter/handler/rejected_execution_handler_only_log.go
@@ -18,8 +18,9 @@
package handler
import (
- "github.com/apache/dubbo-go/filter"
"sync"
+
+ "github.com/apache/dubbo-go/filter"
)
import (
@@ -41,8 +42,10 @@
extension.SetRejectedExecutionHandler(constant.DEFAULT_KEY, GetOnlyLogRejectedExecutionHandler)
}
-var onlyLogHandlerInstance *OnlyLogRejectedExecutionHandler
-var onlyLogHandlerOnce sync.Once
+var (
+ onlyLogHandlerInstance *OnlyLogRejectedExecutionHandler
+ onlyLogHandlerOnce sync.Once
+)
// OnlyLogRejectedExecutionHandler implements the RejectedExecutionHandler
/**
@@ -59,8 +62,7 @@
* - name: "GetUser"
* OnlyLogRejectedExecutionHandler is designed to be singleton
*/
-type OnlyLogRejectedExecutionHandler struct {
-}
+type OnlyLogRejectedExecutionHandler struct{}
// RejectedExecution will do nothing, it only log the invocation.
func (handler *OnlyLogRejectedExecutionHandler) RejectedExecution(url *common.URL,
diff --git a/filter/handler/rejected_execution_handler_only_log_test.go b/filter/handler/rejected_execution_handler_only_log_test.go
index 7aa4aff..acc3a19 100644
--- a/filter/handler/rejected_execution_handler_only_log_test.go
+++ b/filter/handler/rejected_execution_handler_only_log_test.go
@@ -21,6 +21,7 @@
"net/url"
"testing"
)
+
import (
"github.com/apache/dubbo-go/common"
"github.com/apache/dubbo-go/common/constant"
diff --git a/metadata/definition/mock.go b/metadata/definition/mock.go
index ca9e125..02f969c 100644
--- a/metadata/definition/mock.go
+++ b/metadata/definition/mock.go
@@ -29,8 +29,7 @@
Time time.Time
}
-type UserProvider struct {
-}
+type UserProvider struct{}
func (u *UserProvider) GetUser(ctx context.Context, req []interface{}) (*User, error) {
rsp := User{"A001", "Alex Stocks", 18, time.Now()}
diff --git a/metadata/identifier/base_metadata_identifier.go b/metadata/identifier/base_metadata_identifier.go
index 2371f7c..47c2e93 100644
--- a/metadata/identifier/base_metadata_identifier.go
+++ b/metadata/identifier/base_metadata_identifier.go
@@ -68,7 +68,6 @@
withPathSeparator(mdi.Group) +
withPathSeparator(mdi.Side) +
joinParams(constant.PATH_SEPARATOR, params)
-
}
// serviceToPath uss URL encode to decode the @serviceInterface
@@ -82,7 +81,6 @@
}
return string(decoded)
}
-
}
// withPathSeparator return "/" + @path
diff --git a/metadata/mapping/dynamic/service_name_mapping_test.go b/metadata/mapping/dynamic/service_name_mapping_test.go
index af21704..d98a893 100644
--- a/metadata/mapping/dynamic/service_name_mapping_test.go
+++ b/metadata/mapping/dynamic/service_name_mapping_test.go
@@ -33,7 +33,6 @@
)
func TestDynamicConfigurationServiceNameMapping(t *testing.T) {
-
// mock data
appName := "myApp"
dc, err := (&config_center.MockDynamicConfigurationFactory{
diff --git a/metadata/mapping/memory/service_name_mapping.go b/metadata/mapping/memory/service_name_mapping.go
index 0965d52..8017ec7 100644
--- a/metadata/mapping/memory/service_name_mapping.go
+++ b/metadata/mapping/memory/service_name_mapping.go
@@ -24,6 +24,7 @@
import (
gxset "github.com/dubbogo/gost/container/set"
)
+
import (
"github.com/apache/dubbo-go/common/extension"
"github.com/apache/dubbo-go/config"
@@ -44,8 +45,10 @@
return gxset.NewSet(config.GetApplicationConfig().Name), nil
}
-var serviceNameMappingInstance *InMemoryServiceNameMapping
-var serviceNameMappingOnce sync.Once
+var (
+ serviceNameMappingInstance *InMemoryServiceNameMapping
+ serviceNameMappingOnce sync.Once
+)
func GetNameMappingInstance() mapping.ServiceNameMapping {
serviceNameMappingOnce.Do(func() {
diff --git a/metadata/report/consul/report.go b/metadata/report/consul/report.go
index e211f7f..0c9f9cb 100644
--- a/metadata/report/consul/report.go
+++ b/metadata/report/consul/report.go
@@ -29,9 +29,7 @@
"github.com/apache/dubbo-go/metadata/report/factory"
)
-var (
- emptyStrSlice = make([]string, 0)
-)
+var emptyStrSlice = make([]string, 0)
func init() {
mf := &consulMetadataReportFactory{}
@@ -111,8 +109,7 @@
return string(kv.Value), nil
}
-type consulMetadataReportFactory struct {
-}
+type consulMetadataReportFactory struct{}
// nolint
func (mf *consulMetadataReportFactory) CreateMetadataReport(url *common.URL) report.MetadataReport {
diff --git a/metadata/report/delegate/delegate_report.go b/metadata/report/delegate/delegate_report.go
index 56a22de..2cd9af8 100644
--- a/metadata/report/delegate/delegate_report.go
+++ b/metadata/report/delegate/delegate_report.go
@@ -125,7 +125,6 @@
url.GetParamInt(constant.RETRY_TIMES_KEY, defaultMetadataReportRetryTimes),
bmr.retry,
)
-
if err != nil {
return nil, err
}
@@ -139,7 +138,6 @@
bmr.allMetadataReportsLock.RLock()
bmr.doHandlerMetadataCollection(bmr.allMetadataReports)
bmr.allMetadataReportsLock.RUnlock()
-
})
if err != nil {
return nil, err
diff --git a/metadata/report/delegate/delegate_report_test.go b/metadata/report/delegate/delegate_report_test.go
index f60acf6..f2c7376 100644
--- a/metadata/report/delegate/delegate_report_test.go
+++ b/metadata/report/delegate/delegate_report_test.go
@@ -87,7 +87,7 @@
func TestMetadataReport_StoreProviderMetadata(t *testing.T) {
mtr := mockNewMetadataReport(t)
- var metadataId = &identifier.MetadataIdentifier{
+ metadataId := &identifier.MetadataIdentifier{
Application: "app",
BaseMetadataIdentifier: identifier.BaseMetadataIdentifier{
ServiceInterface: "com.ikurento.user.UserProvider",
diff --git a/metadata/report/etcd/report_test.go b/metadata/report/etcd/report_test.go
index 59d0975..5361494 100644
--- a/metadata/report/etcd/report_test.go
+++ b/metadata/report/etcd/report_test.go
@@ -105,7 +105,6 @@
Revision: "subscribe",
MetadataIdentifier: *newMetadataIdentifier("provider"),
}
-
}
func newServiceMetadataIdentifier() *identifier.ServiceMetadataIdentifier {
diff --git a/metadata/report/factory/report_factory.go b/metadata/report/factory/report_factory.go
index 9f00007..df2cf74 100644
--- a/metadata/report/factory/report_factory.go
+++ b/metadata/report/factory/report_factory.go
@@ -27,5 +27,4 @@
CreateMetadataReport(*common.URL) report.MetadataReport
}
-type BaseMetadataReportFactory struct {
-}
+type BaseMetadataReportFactory struct{}
diff --git a/metadata/report/nacos/report.go b/metadata/report/nacos/report.go
index 42e9859..f62d02f 100644
--- a/metadata/report/nacos/report.go
+++ b/metadata/report/nacos/report.go
@@ -173,8 +173,7 @@
return cfg, nil
}
-type nacosMetadataReportFactory struct {
-}
+type nacosMetadataReportFactory struct{}
// nolint
func (n *nacosMetadataReportFactory) CreateMetadataReport(url *common.URL) report.MetadataReport {
diff --git a/metadata/report/zookeeper/report.go b/metadata/report/zookeeper/report.go
index 472f50a..580be91 100644
--- a/metadata/report/zookeeper/report.go
+++ b/metadata/report/zookeeper/report.go
@@ -35,9 +35,7 @@
"github.com/apache/dubbo-go/metadata/report/factory"
)
-var (
- emptyStrSlice = make([]string, 0)
-)
+var emptyStrSlice = make([]string, 0)
func init() {
mf := &zookeeperMetadataReportFactory{}
@@ -110,8 +108,7 @@
return string(v), err
}
-type zookeeperMetadataReportFactory struct {
-}
+type zookeeperMetadataReportFactory struct{}
// nolint
func (mf *zookeeperMetadataReportFactory) CreateMetadataReport(url *common.URL) report.MetadataReport {
diff --git a/metadata/service/exporter/configurable/exporter_test.go b/metadata/service/exporter/configurable/exporter_test.go
index 7c2baa2..9b2c8e4 100644
--- a/metadata/service/exporter/configurable/exporter_test.go
+++ b/metadata/service/exporter/configurable/exporter_test.go
@@ -52,7 +52,8 @@
WaitTimeout: "1s",
MaxMsgLen: 10240000000,
SessionName: "server",
- }})
+ },
+ })
mockInitProviderWithSingleRegistry()
metadataService, _ := inmemory.NewMetadataService()
exported := NewMetadataServiceExporter(metadataService)
@@ -86,7 +87,8 @@
Module: "module",
Version: "1.0.0",
Owner: "dubbo",
- Environment: "test"},
+ Environment: "test",
+ },
},
Registry: &config.RegistryConfig{
diff --git a/metadata/service/inmemory/metadata_service_proxy_factory_test.go b/metadata/service/inmemory/metadata_service_proxy_factory_test.go
index f5e519c..5f62035 100644
--- a/metadata/service/inmemory/metadata_service_proxy_factory_test.go
+++ b/metadata/service/inmemory/metadata_service_proxy_factory_test.go
@@ -63,8 +63,7 @@
assert.NotNil(t, pxy)
}
-type mockProtocol struct {
-}
+type mockProtocol struct{}
func (m mockProtocol) Export(protocol.Invoker) protocol.Exporter {
panic("implement me")
@@ -78,8 +77,7 @@
panic("implement me")
}
-type mockInvoker struct {
-}
+type mockInvoker struct{}
func (m *mockInvoker) GetUrl() *common.URL {
panic("implement me")
diff --git a/metadata/service/inmemory/service_proxy.go b/metadata/service/inmemory/service_proxy.go
index 8b93aab..fadf998 100644
--- a/metadata/service/inmemory/service_proxy.go
+++ b/metadata/service/inmemory/service_proxy.go
@@ -40,11 +40,10 @@
// for now, only GetExportedURLs need to be implemented
type MetadataServiceProxy struct {
invkr protocol.Invoker
- //golangServer bool
+ // golangServer bool
}
func (m *MetadataServiceProxy) GetExportedURLs(serviceInterface string, group string, version string, protocol string) ([]interface{}, error) {
-
siV := reflect.ValueOf(serviceInterface)
gV := reflect.ValueOf(group)
vV := reflect.ValueOf(version)
diff --git a/metadata/service/inmemory/service_proxy_test.go b/metadata/service/inmemory/service_proxy_test.go
index 9278fd9..c697faf 100644
--- a/metadata/service/inmemory/service_proxy_test.go
+++ b/metadata/service/inmemory/service_proxy_test.go
@@ -35,13 +35,11 @@
)
func TestMetadataServiceProxy_GetExportedURLs(t *testing.T) {
-
pxy := createPxy()
assert.NotNil(t, pxy)
res, err := pxy.GetExportedURLs(constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE)
assert.Nil(t, err)
assert.Len(t, res, 1)
-
}
// TestNewMetadataService: those methods are not implemented
diff --git a/metadata/service/remote/service.go b/metadata/service/remote/service.go
index e2a7a64..95e5c7f 100644
--- a/metadata/service/remote/service.go
+++ b/metadata/service/remote/service.go
@@ -109,7 +109,7 @@
func (mts *MetadataService) UnsubscribeURL(url *common.URL) error {
// TODO remove call local.
return nil
- //return mts.UnsubscribeURL(url)
+ // return mts.UnsubscribeURL(url)
}
// PublishServiceDefinition will call remote metadata's StoreProviderMetadata to store url info and service definition
diff --git a/metadata/service/remote/service_proxy.go b/metadata/service/remote/service_proxy.go
index e0cd6e0..241b3fc 100644
--- a/metadata/service/remote/service_proxy.go
+++ b/metadata/service/remote/service_proxy.go
@@ -20,6 +20,7 @@
import (
"strings"
)
+
import (
"github.com/apache/dubbo-go/common"
"github.com/apache/dubbo-go/common/constant"
@@ -81,7 +82,6 @@
Revision: m.revision,
Protocol: protocol,
})
-
if err != nil {
return []interface{}{}, nil
}
diff --git a/metadata/service/remote/service_proxy_test.go b/metadata/service/remote/service_proxy_test.go
index 1899d02..6edbab5 100644
--- a/metadata/service/remote/service_proxy_test.go
+++ b/metadata/service/remote/service_proxy_test.go
@@ -20,6 +20,7 @@
import (
"testing"
)
+
import (
"github.com/stretchr/testify/assert"
)
@@ -79,7 +80,6 @@
}
func createProxy() service.MetadataService {
-
prepareTest()
ins := ®istry.DefaultServiceInstance{
@@ -102,15 +102,13 @@
instance.GetMetadataReportInstance(u)
}
-type mockMetadataReportFactory struct {
-}
+type mockMetadataReportFactory struct{}
func (m *mockMetadataReportFactory) CreateMetadataReport(*common.URL) report.MetadataReport {
return &mockMetadataReport{}
}
-type mockMetadataReport struct {
-}
+type mockMetadataReport struct{}
func (m mockMetadataReport) StoreProviderMetadata(*identifier.MetadataIdentifier, string) error {
panic("implement me")
diff --git a/metadata/service/remote/service_test.go b/metadata/service/remote/service_test.go
index d602815..d9e4d14 100644
--- a/metadata/service/remote/service_test.go
+++ b/metadata/service/remote/service_test.go
@@ -47,15 +47,13 @@
return &metadataReportFactory{}
}
-type metadataReportFactory struct {
-}
+type metadataReportFactory struct{}
func (mrf *metadataReportFactory) CreateMetadataReport(*common.URL) report.MetadataReport {
return &metadataReport{}
}
-type metadataReport struct {
-}
+type metadataReport struct{}
func (metadataReport) StoreProviderMetadata(*identifier.MetadataIdentifier, string) error {
return nil
diff --git a/protocol/dubbo/dubbo_codec.go b/protocol/dubbo/dubbo_codec.go
index 21376c3..6c367c7 100644
--- a/protocol/dubbo/dubbo_codec.go
+++ b/protocol/dubbo/dubbo_codec.go
@@ -36,7 +36,7 @@
"github.com/apache/dubbo-go/remoting"
)
-//SerialID serial ID
+// SerialID serial ID
type SerialID byte
func init() {
@@ -46,8 +46,7 @@
}
// DubboCodec. It is implements remoting.Codec
-type DubboCodec struct {
-}
+type DubboCodec struct{}
// encode request for transport
func (c *DubboCodec) EncodeRequest(request *remoting.Request) (*bytes.Buffer, error) {
@@ -129,7 +128,7 @@
// encode response
func (c *DubboCodec) EncodeResponse(response *remoting.Response) (*bytes.Buffer, error) {
- var ptype = impl.PackageResponse
+ ptype := impl.PackageResponse
if response.IsHeartbeat() {
ptype = impl.PackageHeartbeat
}
@@ -190,7 +189,7 @@
if err != nil {
originErr := perrors.Cause(err)
if originErr == hessian.ErrHeaderNotEnough || originErr == hessian.ErrBodyNotEnough {
- //FIXME
+ // FIXME
return nil, 0, originErr
}
logger.Errorf("pkg.Unmarshal(len(@data):%d) = error:%+v", buf.Len(), err)
@@ -207,19 +206,19 @@
// convert params of request
req := pkg.Body.(map[string]interface{})
- //invocation := request.Data.(*invocation.RPCInvocation)
+ // invocation := request.Data.(*invocation.RPCInvocation)
var methodName string
var args []interface{}
attachments := make(map[string]interface{})
if req[impl.DubboVersionKey] != nil {
- //dubbo version
+ // dubbo version
request.Version = req[impl.DubboVersionKey].(string)
}
- //path
+ // path
attachments[constant.PATH_KEY] = pkg.Service.Path
- //version
+ // version
attachments[constant.VERSION_KEY] = pkg.Service.Version
- //method
+ // method
methodName = pkg.Service.Method
args = req[impl.ArgsKey].([]interface{})
attachments = req[impl.AttachmentsKey].(map[string]interface{})
@@ -248,7 +247,7 @@
}
response := &remoting.Response{
ID: pkg.Header.ID,
- //Version: pkg.Header.,
+ // Version: pkg.Header.,
SerialID: pkg.Header.SerialID,
Status: pkg.Header.ResponseStatus,
Event: (pkg.Header.Type & impl.PackageHeartbeat) != 0,
@@ -264,7 +263,7 @@
} else {
logger.Debugf("get rpc heartbeat request{header: %#v, service: %#v, body: %#v}", pkg.Header, pkg.Service, pkg.Body)
response.Status = hessian.Response_OK
- //reply(session, p, hessian.PackageHeartbeat)
+ // reply(session, p, hessian.PackageHeartbeat)
}
return response, hessian.HEADER_LENGTH + pkg.Header.BodyLen, error
}
diff --git a/protocol/dubbo/dubbo_invoker.go b/protocol/dubbo/dubbo_invoker.go
index bc85d73..12bab31 100644
--- a/protocol/dubbo/dubbo_invoker.go
+++ b/protocol/dubbo/dubbo_invoker.go
@@ -39,10 +39,10 @@
"github.com/apache/dubbo-go/remoting"
)
-var (
- attachmentKey = []string{constant.INTERFACE_KEY, constant.GROUP_KEY, constant.TOKEN_KEY, constant.TIMEOUT_KEY,
- constant.VERSION_KEY}
-)
+var attachmentKey = []string{
+ constant.INTERFACE_KEY, constant.GROUP_KEY, constant.TOKEN_KEY, constant.TIMEOUT_KEY,
+ constant.VERSION_KEY,
+}
// DubboInvoker is implement of protocol.Invoker. A dubboInvoker refers to one service and ip.
type DubboInvoker struct {
@@ -141,7 +141,7 @@
logger.Errorf("ParseBool - error: %v", err)
async = false
}
- //response := NewResponse(inv.Reply(), nil)
+ // response := NewResponse(inv.Reply(), nil)
rest := &protocol.RPCResult{}
timeout := di.getTimeout(inv)
if async {
@@ -168,7 +168,7 @@
// get timeout including methodConfig
func (di *DubboInvoker) getTimeout(invocation *invocation_impl.RPCInvocation) time.Duration {
- var timeout = di.GetUrl().GetParam(strings.Join([]string{constant.METHOD_KEYS, invocation.MethodName(), constant.TIMEOUT_KEY}, "."), "")
+ timeout := di.GetUrl().GetParam(strings.Join([]string{constant.METHOD_KEYS, invocation.MethodName(), constant.TIMEOUT_KEY}, "."), "")
if len(timeout) != 0 {
if t, err := time.ParseDuration(timeout); err == nil {
// config timeout into attachment
diff --git a/protocol/dubbo/dubbo_invoker_test.go b/protocol/dubbo/dubbo_invoker_test.go
index fecb3b0..cfa81ca 100644
--- a/protocol/dubbo/dubbo_invoker_test.go
+++ b/protocol/dubbo/dubbo_invoker_test.go
@@ -70,7 +70,7 @@
r := response.(remoting.AsyncCallbackResponse)
rst := *r.Reply.(*remoting.Response).Result.(*protocol.RPCResult)
assert.Equal(t, User{Id: "1", Name: "username"}, *(rst.Rest.(*User)))
- //assert.Equal(t, User{ID: "1", Name: "username"}, *r.Reply.(*Response).reply.(*User))
+ // assert.Equal(t, User{ID: "1", Name: "username"}, *r.Reply.(*Response).reply.(*User))
lock.Unlock()
})
res = invoker.Invoke(context.Background(), inv)
@@ -94,7 +94,6 @@
}
func InitTest(t *testing.T) (protocol.Protocol, *common.URL) {
-
hessian.RegisterPOJO(&User{})
methods, err := common.ServiceMap.Register("com.ikurento.user.UserProvider", "dubbo", "", "", &UserProvider{})
@@ -139,7 +138,8 @@
WaitTimeout: "1s",
MaxMsgLen: 10240000000,
SessionName: "server",
- }})
+ },
+ })
// Export
proto := GetProtocol()
@@ -168,8 +168,7 @@
Name string `json:"name"`
}
- UserProvider struct {
- //user map[string]User
+ UserProvider struct { // user map[string]User
}
)
@@ -209,7 +208,6 @@
}
func (u *UserProvider) GetUser4(ctx context.Context, req []interface{}) ([]interface{}, error) {
-
return []interface{}{User{Id: req[0].([]interface{})[0].(string), Name: req[0].([]interface{})[1].(string)}}, nil
}
diff --git a/protocol/dubbo/dubbo_protocol.go b/protocol/dubbo/dubbo_protocol.go
index d6a71dc..ce0ce47 100644
--- a/protocol/dubbo/dubbo_protocol.go
+++ b/protocol/dubbo/dubbo_protocol.go
@@ -56,9 +56,7 @@
extension.SetProtocol(DUBBO, GetProtocol)
}
-var (
- dubboProtocol *DubboProtocol
-)
+var dubboProtocol *DubboProtocol
// It support dubbo protocol. It implements Protocol interface for dubbo protocol.
type DubboProtocol struct {
@@ -152,7 +150,7 @@
err := fmt.Errorf("don't have this exporter, key: %s", rpcInvocation.ServiceKey())
logger.Errorf(err.Error())
result.Err = err
- //reply(session, p, hessian.PackageResponse)
+ // reply(session, p, hessian.PackageResponse)
return result
}
invoker := exporter.(protocol.Exporter).GetInvoker()
@@ -163,12 +161,12 @@
invokeResult := invoker.Invoke(ctx, rpcInvocation)
if err := invokeResult.Error(); err != nil {
result.Err = invokeResult.Error()
- //p.Header.ResponseStatus = hessian.Response_OK
- //p.Body = hessian.NewResponse(nil, err, result.Attachments())
+ // p.Header.ResponseStatus = hessian.Response_OK
+ // p.Body = hessian.NewResponse(nil, err, result.Attachments())
} else {
result.Rest = invokeResult.Result()
- //p.Header.ResponseStatus = hessian.Response_OK
- //p.Body = hessian.NewResponse(res, nil, result.Attachments())
+ // p.Header.ResponseStatus = hessian.Response_OK
+ // p.Body = hessian.NewResponse(res, nil, result.Attachments())
}
} else {
result.Err = fmt.Errorf("don't have the invoker, key: %s", rpcInvocation.ServiceKey())
diff --git a/protocol/dubbo/dubbo_protocol_test.go b/protocol/dubbo/dubbo_protocol_test.go
index 9eba90e..f564c6d 100644
--- a/protocol/dubbo/dubbo_protocol_test.go
+++ b/protocol/dubbo/dubbo_protocol_test.go
@@ -58,7 +58,8 @@
WaitTimeout: "1s",
MaxMsgLen: 10240000000,
SessionName: "server",
- }})
+ },
+ })
getty.SetClientConf(getty.ClientConfig{
ConnectionNum: 1,
HeartbeatPeriod: "3s",
diff --git a/protocol/dubbo/hessian2/hessian_dubbo.go b/protocol/dubbo/hessian2/hessian_dubbo.go
index 5ffebde..f61733f 100644
--- a/protocol/dubbo/hessian2/hessian_dubbo.go
+++ b/protocol/dubbo/hessian2/hessian_dubbo.go
@@ -107,7 +107,6 @@
// ReadHeader uses hessian codec to read dubbo header
func (h *HessianCodec) ReadHeader(header *DubboHeader) error {
-
var err error
if h.reader.Size() < HEADER_LENGTH {
@@ -169,12 +168,10 @@
}
return perrors.WithStack(err)
-
}
// ReadBody uses hessian codec to read response body
func (h *HessianCodec) ReadBody(rspObj interface{}) error {
-
if h.reader.Buffered() < h.bodyLen {
return ErrBodyNotEnough
}
diff --git a/protocol/dubbo/hessian2/hessian_dubbo_test.go b/protocol/dubbo/hessian2/hessian_dubbo_test.go
index eaaf500..e603b00 100644
--- a/protocol/dubbo/hessian2/hessian_dubbo_test.go
+++ b/protocol/dubbo/hessian2/hessian_dubbo_test.go
@@ -54,7 +54,7 @@
return "com.test.casea"
}
-//JavaClassName java fully qualified path
+// JavaClassName java fully qualified path
func (c Case) JavaClassName() string {
return "com.test.case"
}
diff --git a/protocol/dubbo/hessian2/hessian_request.go b/protocol/dubbo/hessian2/hessian_request.go
index 94aa34d..7c4849f 100644
--- a/protocol/dubbo/hessian2/hessian_request.go
+++ b/protocol/dubbo/hessian2/hessian_request.go
@@ -274,7 +274,6 @@
// hessian decode request body
func unpackRequestBody(decoder *hessian.Decoder, reqObj interface{}) error {
-
if decoder == nil {
return perrors.Errorf("@decoder is nil")
}
diff --git a/protocol/dubbo/hessian2/hessian_response.go b/protocol/dubbo/hessian2/hessian_response.go
index b95e1c2..bed8dad 100644
--- a/protocol/dubbo/hessian2/hessian_response.go
+++ b/protocol/dubbo/hessian2/hessian_response.go
@@ -18,11 +18,12 @@
import (
"encoding/binary"
- "github.com/apache/dubbo-go/common/logger"
"math"
"reflect"
"strconv"
"strings"
+
+ "github.com/apache/dubbo-go/common/logger"
)
import (
@@ -64,9 +65,7 @@
// https://github.com/apache/dubbo/blob/dubbo-2.7.1/dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/codec/ExchangeCodec.java#L256
// hessian encode response
func packResponse(header DubboHeader, ret interface{}) ([]byte, error) {
- var (
- byteArray []byte
- )
+ var byteArray []byte
response := EnsureResponse(ret)
@@ -362,7 +361,7 @@
if !ok || len(version) == 0 {
return 0
}
- var v = 0
+ v := 0
varr := strings.Split(version, ".")
length := len(varr)
for key, value := range varr {
diff --git a/protocol/dubbo/hessian2/hessian_response_test.go b/protocol/dubbo/hessian2/hessian_response_test.go
index f5c84ba..86c2e43 100644
--- a/protocol/dubbo/hessian2/hessian_response_test.go
+++ b/protocol/dubbo/hessian2/hessian_response_test.go
@@ -93,7 +93,7 @@
var s1r []string
doTestReflectResponse(t, s1, &s1r)
- s2 := []rr{rr{"dubbo", 666}, rr{"go", 999}}
+ s2 := []rr{{"dubbo", 666}, {"go", 999}}
var s2r []rr
doTestReflectResponse(t, s2, &s2r)
@@ -221,5 +221,4 @@
v = version2Int("2.1.3.4.5")
assert.Equal(t, 201030405, v)
-
}
diff --git a/protocol/dubbo/impl/codec.go b/protocol/dubbo/impl/codec.go
index 6c9816f..d4f3804 100644
--- a/protocol/dubbo/impl/codec.go
+++ b/protocol/dubbo/impl/codec.go
@@ -238,9 +238,7 @@
}
func packResponse(p DubboPackage, serializer Serializer) ([]byte, error) {
- var (
- byteArray []byte
- )
+ var byteArray []byte
header := p.Header
hb := p.IsHeartBeat()
diff --git a/protocol/dubbo/impl/hessian.go b/protocol/dubbo/impl/hessian.go
index 4aaf67b..2f750c5 100644
--- a/protocol/dubbo/impl/hessian.go
+++ b/protocol/dubbo/impl/hessian.go
@@ -37,8 +37,7 @@
"github.com/apache/dubbo-go/common/logger"
)
-type HessianSerializer struct {
-}
+type HessianSerializer struct{}
func (h HessianSerializer) Marshal(p DubboPackage) ([]byte, error) {
encoder := hessian.NewEncoder()
@@ -178,7 +177,7 @@
}
func version2Int(version string) int {
- var v = 0
+ v := 0
varr := strings.Split(version, ".")
length := len(varr)
for key, value := range varr {
diff --git a/protocol/dubbo/opentracing.go b/protocol/dubbo/opentracing.go
index f45e6fd..bc27050 100644
--- a/protocol/dubbo/opentracing.go
+++ b/protocol/dubbo/opentracing.go
@@ -20,6 +20,7 @@
import (
"github.com/opentracing/opentracing-go"
)
+
import (
invocation_impl "github.com/apache/dubbo-go/protocol/invocation"
)
@@ -36,7 +37,7 @@
}
func filterContext(attachments map[string]interface{}) map[string]string {
- var traceAttchment = make(map[string]string)
+ traceAttchment := make(map[string]string)
for k, v := range attachments {
if r, ok := v.(string); ok {
traceAttchment[k] = r
diff --git a/protocol/grpc/client.go b/protocol/grpc/client.go
index b8a9143..567996b 100644
--- a/protocol/grpc/client.go
+++ b/protocol/grpc/client.go
@@ -36,9 +36,7 @@
"github.com/apache/dubbo-go/config"
)
-var (
- clientConf *ClientConfig
-)
+var clientConf *ClientConfig
func init() {
// load clientconfig from consumer_config
@@ -80,7 +78,6 @@
panic(err)
}
}
-
}
// Client is gRPC client include client connection and invoker
@@ -96,7 +93,7 @@
dialOpts := make([]grpc.DialOption, 0, 4)
maxMessageSize, _ := strconv.Atoi(url.GetParam(constant.MESSAGE_SIZE_KEY, "4"))
- //consumer config client connectTimeout
+ // consumer config client connectTimeout
connectTimeout := config.GetConsumerConfig().ConnectTimeout
dialOpts = append(dialOpts, grpc.WithInsecure(), grpc.WithBlock(), grpc.WithTimeout(connectTimeout), grpc.WithUnaryInterceptor(
@@ -107,7 +104,6 @@
grpc.MaxCallSendMsgSize(1024*1024*maxMessageSize)))
conn, err := grpc.Dial(url.Location, dialOpts...)
-
if err != nil {
logger.Errorf("grpc dail error: %v", err)
return nil, err
diff --git a/protocol/grpc/config.go b/protocol/grpc/config.go
index e8a9baa..d0a1920 100644
--- a/protocol/grpc/config.go
+++ b/protocol/grpc/config.go
@@ -23,8 +23,7 @@
type (
// ServerConfig currently is empty struct,for future expansion
- ServerConfig struct {
- }
+ ServerConfig struct{}
// ClientConfig wrap client call parameters
ClientConfig struct {
diff --git a/protocol/grpc/grpc_invoker.go b/protocol/grpc/grpc_invoker.go
index 7b33c67..79eb3ca 100644
--- a/protocol/grpc/grpc_invoker.go
+++ b/protocol/grpc/grpc_invoker.go
@@ -35,9 +35,7 @@
"github.com/apache/dubbo-go/protocol"
)
-var (
- errNoReply = errors.New("request need @response")
-)
+var errNoReply = errors.New("request need @response")
// nolint
type GrpcInvoker struct {
@@ -72,9 +70,7 @@
// Invoke is used to call service method by invocation
func (gi *GrpcInvoker) Invoke(ctx context.Context, invocation protocol.Invocation) protocol.Result {
- var (
- result protocol.RPCResult
- )
+ var result protocol.RPCResult
if !gi.BaseInvoker.IsAvailable() {
// Generally, the case will not happen, because the invoker has been removed
diff --git a/protocol/grpc/internal/client.go b/protocol/grpc/internal/client.go
index 3ce0f57..83b4586 100644
--- a/protocol/grpc/internal/client.go
+++ b/protocol/grpc/internal/client.go
@@ -34,7 +34,7 @@
}
// GrpcGreeterImpl
-//used for dubbo-grpc biz client
+// used for dubbo-grpc biz client
type GrpcGreeterImpl struct {
SayHello func(ctx context.Context, in *HelloRequest, out *HelloReply) error
}
diff --git a/protocol/grpc/internal/helloworld.pb.go b/protocol/grpc/internal/helloworld.pb.go
index 82537f5..2ea04fd 100644
--- a/protocol/grpc/internal/helloworld.pb.go
+++ b/protocol/grpc/internal/helloworld.pb.go
@@ -32,9 +32,11 @@
)
// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
+var (
+ _ = proto.Marshal
+ _ = fmt.Errorf
+ _ = math.Inf
+)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
@@ -60,15 +62,19 @@
func (m *HelloRequest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_HelloRequest.Unmarshal(m, b)
}
+
func (m *HelloRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_HelloRequest.Marshal(b, m, deterministic)
}
+
func (m *HelloRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_HelloRequest.Merge(m, src)
}
+
func (m *HelloRequest) XXX_Size() int {
return xxx_messageInfo_HelloRequest.Size(m)
}
+
func (m *HelloRequest) XXX_DiscardUnknown() {
xxx_messageInfo_HelloRequest.DiscardUnknown(m)
}
@@ -100,15 +106,19 @@
func (m *HelloReply) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_HelloReply.Unmarshal(m, b)
}
+
func (m *HelloReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_HelloReply.Marshal(b, m, deterministic)
}
+
func (m *HelloReply) XXX_Merge(src proto.Message) {
xxx_messageInfo_HelloReply.Merge(m, src)
}
+
func (m *HelloReply) XXX_Size() int {
return xxx_messageInfo_HelloReply.Size(m)
}
+
func (m *HelloReply) XXX_DiscardUnknown() {
xxx_messageInfo_HelloReply.DiscardUnknown(m)
}
@@ -145,8 +155,10 @@
}
// Reference imports to suppress errors if they are not otherwise used.
-var _ context.Context
-var _ grpc.ClientConn
+var (
+ _ context.Context
+ _ grpc.ClientConn
+)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
@@ -184,8 +196,7 @@
}
// UnimplementedGreeterServer can be embedded to have forward compatible implementations.
-type UnimplementedGreeterServer struct {
-}
+type UnimplementedGreeterServer struct{}
func (*UnimplementedGreeterServer) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented")
diff --git a/protocol/grpc/internal/server.go b/protocol/grpc/internal/server.go
index f7b99fa..6e17a4f 100644
--- a/protocol/grpc/internal/server.go
+++ b/protocol/grpc/internal/server.go
@@ -27,9 +27,7 @@
"google.golang.org/grpc"
)
-var (
- s *grpc.Server
-)
+var s *grpc.Server
// server is used to implement helloworld.GreeterServer.
type server struct {
diff --git a/protocol/grpc/protoc-gen-dubbo/examples/helloworld.pb.go b/protocol/grpc/protoc-gen-dubbo/examples/helloworld.pb.go
index 702391b..fe86b2b 100644
--- a/protocol/grpc/protoc-gen-dubbo/examples/helloworld.pb.go
+++ b/protocol/grpc/protoc-gen-dubbo/examples/helloworld.pb.go
@@ -38,9 +38,11 @@
)
// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
+var (
+ _ = proto.Marshal
+ _ = fmt.Errorf
+ _ = math.Inf
+)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
@@ -66,15 +68,19 @@
func (m *HelloRequest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_HelloRequest.Unmarshal(m, b)
}
+
func (m *HelloRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_HelloRequest.Marshal(b, m, deterministic)
}
+
func (m *HelloRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_HelloRequest.Merge(m, src)
}
+
func (m *HelloRequest) XXX_Size() int {
return xxx_messageInfo_HelloRequest.Size(m)
}
+
func (m *HelloRequest) XXX_DiscardUnknown() {
xxx_messageInfo_HelloRequest.DiscardUnknown(m)
}
@@ -106,15 +112,19 @@
func (m *HelloReply) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_HelloReply.Unmarshal(m, b)
}
+
func (m *HelloReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_HelloReply.Marshal(b, m, deterministic)
}
+
func (m *HelloReply) XXX_Merge(src proto.Message) {
xxx_messageInfo_HelloReply.Merge(m, src)
}
+
func (m *HelloReply) XXX_Size() int {
return xxx_messageInfo_HelloReply.Size(m)
}
+
func (m *HelloReply) XXX_DiscardUnknown() {
xxx_messageInfo_HelloReply.DiscardUnknown(m)
}
@@ -152,8 +162,10 @@
}
// Reference imports to suppress errors if they are not otherwise used.
-var _ context.Context
-var _ grpc.ClientConn
+var (
+ _ context.Context
+ _ grpc.ClientConn
+)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
@@ -191,8 +203,7 @@
}
// UnimplementedGreeterServer can be embedded to have forward compatible implementations.
-type UnimplementedGreeterServer struct {
-}
+type UnimplementedGreeterServer struct{}
func (*UnimplementedGreeterServer) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented")
diff --git a/protocol/jsonrpc/http.go b/protocol/jsonrpc/http.go
index 11051df..0ad76e0 100644
--- a/protocol/jsonrpc/http.go
+++ b/protocol/jsonrpc/http.go
@@ -56,7 +56,7 @@
service string
method string
args interface{}
- //contentType string
+ // contentType string
}
// ////////////////////////////////////////////
@@ -102,7 +102,6 @@
// NewRequest creates a new HTTP request with @service ,@method and @arguments.
func (c *HTTPClient) NewRequest(service *common.URL, method string, args interface{}) *Request {
-
return &Request{
ID: atomic.AddInt64(&c.ID, 1),
group: service.GetParam(constant.GROUP_KEY, ""),
diff --git a/protocol/jsonrpc/http_test.go b/protocol/jsonrpc/http_test.go
index 5ef4064..caf0d22 100644
--- a/protocol/jsonrpc/http_test.go
+++ b/protocol/jsonrpc/http_test.go
@@ -43,8 +43,7 @@
Name string `json:"name"`
}
- UserProvider struct {
- //user map[string]User
+ UserProvider struct { // user map[string]User
}
)
@@ -57,7 +56,6 @@
)
func TestHTTPClientCall(t *testing.T) {
-
methods, err := common.ServiceMap.Register("com.ikurento.user.UserProvider", "jsonrpc", "", "", &UserProvider{})
assert.NoError(t, err)
assert.Equal(t, "GetUser,GetUser0,GetUser1,GetUser2,GetUser3,GetUser4", methods)
@@ -165,7 +163,6 @@
// destroy
proto.Destroy()
-
}
func (u *UserProvider) GetUser(ctx context.Context, req []interface{}, rsp *User) error {
diff --git a/protocol/jsonrpc/json.go b/protocol/jsonrpc/json.go
index 81ca512..2383bf5 100644
--- a/protocol/jsonrpc/json.go
+++ b/protocol/jsonrpc/json.go
@@ -231,7 +231,7 @@
return perrors.New("bad request")
}
- var o = make(map[string]*json.RawMessage)
+ o := make(map[string]*json.RawMessage)
if err := json.Unmarshal(raw, &o); err != nil {
return perrors.New("bad request")
}
diff --git a/protocol/jsonrpc/json_test.go b/protocol/jsonrpc/json_test.go
index a3814e9..6d3e11b 100644
--- a/protocol/jsonrpc/json_test.go
+++ b/protocol/jsonrpc/json_test.go
@@ -54,7 +54,7 @@
assert.NoError(t, err)
assert.Equal(t, "test", rsp.Test)
- //error
+ // error
codec.pending[1] = "GetUser"
err = codec.Read([]byte("{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32000,\"message\":\"error\"}}\n"), rsp)
assert.EqualError(t, err, "{\"code\":-32000,\"message\":\"error\"}")
diff --git a/protocol/jsonrpc/jsonrpc_invoker_test.go b/protocol/jsonrpc/jsonrpc_invoker_test.go
index 12a5705..c604929 100644
--- a/protocol/jsonrpc/jsonrpc_invoker_test.go
+++ b/protocol/jsonrpc/jsonrpc_invoker_test.go
@@ -35,7 +35,6 @@
)
func TestJsonrpcInvokerInvoke(t *testing.T) {
-
methods, err := common.ServiceMap.Register("com.ikurento.user.UserProvider", "jsonrpc", "", "", &UserProvider{})
assert.NoError(t, err)
assert.Equal(t, "GetUser,GetUser0,GetUser1,GetUser2,GetUser3,GetUser4", methods)
diff --git a/protocol/jsonrpc/jsonrpc_protocol.go b/protocol/jsonrpc/jsonrpc_protocol.go
index 643bcde..313d32f 100644
--- a/protocol/jsonrpc/jsonrpc_protocol.go
+++ b/protocol/jsonrpc/jsonrpc_protocol.go
@@ -34,7 +34,7 @@
const (
// JSONRPC
- //module name
+ // module name
JSONRPC = "jsonrpc"
)
@@ -76,8 +76,8 @@
// Refer a remote JSON PRC service from registry
func (jp *JsonrpcProtocol) Refer(url *common.URL) protocol.Invoker {
- //default requestTimeout
- var requestTimeout = config.GetConsumerConfig().RequestTimeout
+ // default requestTimeout
+ requestTimeout := config.GetConsumerConfig().RequestTimeout
requestTimeoutStr := url.GetParam(constant.TIMEOUT_KEY, config.GetConsumerConfig().Request_Timeout)
if t, err := time.ParseDuration(requestTimeoutStr); err == nil {
diff --git a/protocol/jsonrpc/server.go b/protocol/jsonrpc/server.go
index 76901bf..c16f656 100644
--- a/protocol/jsonrpc/server.go
+++ b/protocol/jsonrpc/server.go
@@ -43,12 +43,10 @@
"github.com/apache/dubbo-go/protocol/invocation"
)
-var (
- // A value sent as a placeholder for the server's response value when the server
- // receives an invalid request. It is never decoded by the client since the Response
- // contains an error when it is used.
- invalidRequest = struct{}{}
-)
+// A value sent as a placeholder for the server's response value when the server
+// receives an invalid request. It is never decoded by the client since the Response
+// contains an error when it is used.
+var invalidRequest = struct{}{}
const (
// DefaultMaxSleepTime max sleep interval in accept
@@ -349,7 +347,8 @@
if invoker != nil {
result := invoker.Invoke(ctx, invocation.NewRPCInvocation(methodName, args, map[string]interface{}{
constant.PATH_KEY: path,
- constant.VERSION_KEY: codec.req.Version}))
+ constant.VERSION_KEY: codec.req.Version,
+ }))
if err := result.Error(); err != nil {
rspStream, codecErr := codec.Write(err.Error(), invalidRequest)
if codecErr != nil {
diff --git a/protocol/protocol.go b/protocol/protocol.go
index d03e70f..19ec8ed 100644
--- a/protocol/protocol.go
+++ b/protocol/protocol.go
@@ -137,7 +137,6 @@
// GetInvoker gets invoker
func (de *BaseExporter) GetInvoker() Invoker {
return de.invoker
-
}
// Unexport exported service.
diff --git a/protocol/protocolwrapper/protocol_filter_wrapper_test.go b/protocol/protocolwrapper/protocol_filter_wrapper_test.go
index b37d066..d096784 100644
--- a/protocol/protocolwrapper/protocol_filter_wrapper_test.go
+++ b/protocol/protocolwrapper/protocol_filter_wrapper_test.go
@@ -60,7 +60,7 @@
assert.True(t, ok)
}
-//the same as echo filter, for test
+// the same as echo filter, for test
func init() {
extension.SetFilter("echo", GetFilter)
}
diff --git a/protocol/rest/config/reader/rest_config_reader.go b/protocol/rest/config/reader/rest_config_reader.go
index 2338790..e545d85 100644
--- a/protocol/rest/config/reader/rest_config_reader.go
+++ b/protocol/rest/config/reader/rest_config_reader.go
@@ -43,8 +43,7 @@
extension.SetDefaultConfigReader(REST, REST)
}
-type RestConfigReader struct {
-}
+type RestConfigReader struct{}
func NewRestConfigReader() interfaces.ConfigReader {
return &RestConfigReader{}
diff --git a/protocol/rest/rest_invoker_test.go b/protocol/rest/rest_invoker_test.go
index b6bc980..5a5bd2c 100644
--- a/protocol/rest/rest_invoker_test.go
+++ b/protocol/rest/rest_invoker_test.go
@@ -199,7 +199,7 @@
assert.Equal(t, "username", res.Result().(*User).Name)
// test 3
inv = invocation.NewRPCInvocationWithOptions(invocation.WithMethodName("GetUserFour"),
- invocation.WithArguments([]interface{}{[]User{User{1, nil, int32(23), "username"}}}), invocation.WithReply(user))
+ invocation.WithArguments([]interface{}{[]User{{1, nil, int32(23), "username"}}}), invocation.WithReply(user))
res = invoker.Invoke(context.Background(), inv)
assert.NoError(t, res.Error())
assert.NotNil(t, res.Result())
diff --git a/protocol/rest/rest_protocol.go b/protocol/rest/rest_protocol.go
index d19bd00..a87eb09 100644
--- a/protocol/rest/rest_protocol.go
+++ b/protocol/rest/rest_protocol.go
@@ -37,9 +37,7 @@
_ "github.com/apache/dubbo-go/protocol/rest/server/server_impl"
)
-var (
- restProtocol *RestProtocol
-)
+var restProtocol *RestProtocol
const REST = "rest"
@@ -88,7 +86,7 @@
// Refer create rest service reference
func (rp *RestProtocol) Refer(url *common.URL) protocol.Invoker {
// create rest_invoker
- var requestTimeout = config.GetConsumerConfig().RequestTimeout
+ requestTimeout := config.GetConsumerConfig().RequestTimeout
requestTimeoutStr := url.GetParam(constant.TIMEOUT_KEY, config.GetConsumerConfig().Request_Timeout)
connectTimeout := config.GetConsumerConfig().ConnectTimeout
if t, err := time.ParseDuration(requestTimeoutStr); err == nil {
diff --git a/protocol/rest/rest_protocol_test.go b/protocol/rest/rest_protocol_test.go
index 580fc61..4809564 100644
--- a/protocol/rest/rest_protocol_test.go
+++ b/protocol/rest/rest_protocol_test.go
@@ -122,8 +122,7 @@
assert.False(t, ok)
}
-type UserProvider struct {
-}
+type UserProvider struct{}
func (p *UserProvider) Reference() string {
return "com.ikurento.user.UserProvider"
diff --git a/protocol/rest/server/server_impl/go_restful_server.go b/protocol/rest/server/server_impl/go_restful_server.go
index 4481f44..b42bb6e 100644
--- a/protocol/rest/server/server_impl/go_restful_server.go
+++ b/protocol/rest/server/server_impl/go_restful_server.go
@@ -87,7 +87,6 @@
// Publish a http api in go-restful server
// The routeFunc should be invoked when the server receive a request
func (grs *GoRestfulServer) Deploy(restMethodConfig *config.RestMethodConfig, routeFunc func(request server.RestServerRequest, response server.RestServerResponse)) {
-
rf := func(req *restful.Request, resp *restful.Response) {
routeFunc(NewGoRestfulRequestAdapter(req), resp)
}
diff --git a/protocol/rpc_status.go b/protocol/rpc_status.go
index 8fc5ddd..3994f8d 100644
--- a/protocol/rpc_status.go
+++ b/protocol/rpc_status.go
@@ -263,7 +263,7 @@
wg.Add(1)
go func(ivks []Invoker, i int) {
defer wg.Done()
- for j, _ := range ivks {
+ for j := range ivks {
if j%3-i == 0 && ivks[j].(Invoker).IsAvailable() {
RemoveInvokerUnhealthyStatus(ivks[i])
}
diff --git a/protocol/rpc_status_test.go b/protocol/rpc_status_test.go
index 6fd449c..568d5c5 100644
--- a/protocol/rpc_status_test.go
+++ b/protocol/rpc_status_test.go
@@ -45,7 +45,6 @@
assert.Equal(t, int32(1), methodStatus.active)
assert.Equal(t, int32(1), urlStatus.active)
assert.Equal(t, int32(0), methodStatus1.active)
-
}
func TestEndCount(t *testing.T) {
@@ -139,7 +138,6 @@
methodStatus1 := GetMethodStatus(url, "test1")
assert.Equal(t, int32(2), methodStatus.successiveRequestFailureCount)
assert.Equal(t, int32(3), methodStatus1.successiveRequestFailureCount)
-
}
func request(url *common.URL, method string, elapsed int64, active, succeeded bool) {
diff --git a/registry/base_configuration_listener.go b/registry/base_configuration_listener.go
index 31e859e..67dee9d 100644
--- a/registry/base_configuration_listener.go
+++ b/registry/base_configuration_listener.go
@@ -48,7 +48,7 @@
bcl.dynamicConfiguration = config.GetEnvInstance().GetDynamicConfiguration()
if bcl.dynamicConfiguration == nil {
- //set configurators to empty
+ // set configurators to empty
bcl.configurators = []config_center.Configurator{}
return
}
@@ -56,7 +56,7 @@
bcl.dynamicConfiguration.AddListener(key, listener)
if rawConfig, err := bcl.dynamicConfiguration.GetInternalProperty(key,
config_center.WithGroup(constant.DUBBO)); err != nil {
- //set configurators to empty
+ // set configurators to empty
bcl.configurators = []config_center.Configurator{}
return
} else if len(rawConfig) > 0 {
diff --git a/registry/base_registry.go b/registry/base_registry.go
index df8c8a3..a16a998 100644
--- a/registry/base_registry.go
+++ b/registry/base_registry.go
@@ -92,13 +92,13 @@
// 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
wg sync.WaitGroup // wg+done for zk restart
done chan struct{}
- cltLock sync.RWMutex //ctl lock is a lock for services map
+ cltLock sync.RWMutex // ctl lock is a lock for services map
services map[string]*common.URL // service name + protocol -> service config, for store the service registered
}
@@ -119,14 +119,14 @@
// Destroy for graceful down
func (r *BaseRegistry) Destroy() {
- //first step close registry's all listeners
+ // first step close registry's all listeners
r.facadeBasedRegistry.CloseListener()
// then close r.done to notify other program who listen to it
close(r.done)
// wait waitgroup done (wait listeners outside close over)
r.wg.Wait()
- //close registry client
+ // close registry client
r.closeRegisters()
}
@@ -209,7 +209,6 @@
// RestartCallBack for reregister when reconnect
func (r *BaseRegistry) RestartCallBack() bool {
-
// copy r.services
services := make([]*common.URL, 0, len(r.services))
for _, confIf := range r.services {
@@ -251,12 +250,12 @@
}
var (
err error
- //revision string
+ // revision string
params url.Values
rawURL string
encodedURL string
dubboPath string
- //conf config.URL
+ // conf config.URL
)
params = url.Values{}
@@ -267,7 +266,7 @@
params.Add("pid", processID)
params.Add("ip", localIP)
- //params.Add("timeout", fmt.Sprintf("%d", int64(r.Timeout)/1e6))
+ // params.Add("timeout", fmt.Sprintf("%d", int64(r.Timeout)/1e6))
role, _ := strconv.Atoi(r.URL.GetParam(constant.ROLE_KEY, ""))
switch role {
@@ -335,7 +334,7 @@
}
host += ":" + c.Port
- //delete empty param key
+ // delete empty param key
for key, val := range params {
if len(val) > 0 && val[0] == "" {
params.Del(key)
@@ -426,7 +425,6 @@
logger.Infof("update begin, service event: %v", serviceEvent.String())
notifyListener.Notify(serviceEvent)
}
-
}
sleepWait(n)
}
@@ -458,7 +456,6 @@
logger.Infof("update begin, service event: %v", serviceEvent.String())
notifyListener.Notify(serviceEvent)
}
-
}
return nil
}
diff --git a/registry/consul/service_discovery.go b/registry/consul/service_discovery.go
index fba142e..da5d8d0 100644
--- a/registry/consul/service_discovery.go
+++ b/registry/consul/service_discovery.go
@@ -50,9 +50,7 @@
watch_passingonly_true = true
)
-var (
- errConsulClientClosed = perrors.New("consul client is closed")
-)
+var errConsulClientClosed = perrors.New("consul client is closed")
// init will put the service discovery into extension
func init() {
@@ -241,7 +239,7 @@
consulClient *consul.Client
services map[string][]string
)
- var res = gxset.NewSet()
+ res := gxset.NewSet()
if consulClient = csd.getConsulClient(); consulClient == nil {
logger.Warnf("consul client is closed!")
return res
@@ -256,7 +254,6 @@
res.Add(service)
}
return res
-
}
// encodeConsulMetadata because consul validate key strictly.
@@ -370,7 +367,6 @@
}
func (csd *consulServiceDiscovery) AddListener(listener *registry.ServiceInstancesChangedListener) error {
-
params := make(map[string]interface{}, 8)
params[watch_type] = watch_type_service
params[watch_service] = listener.ServiceName
diff --git a/registry/consul/service_discovery_test.go b/registry/consul/service_discovery_test.go
index 3f97d84..68e8042 100644
--- a/registry/consul/service_discovery_test.go
+++ b/registry/consul/service_discovery_test.go
@@ -90,7 +90,7 @@
}()
prepareData()
- var eventDispatcher = MockEventDispatcher{Notify: make(chan struct{}, 1)}
+ eventDispatcher := MockEventDispatcher{Notify: make(chan struct{}, 1)}
extension.SetEventDispatcher("mock", func() observer.EventDispatcher {
return &eventDispatcher
})
@@ -110,8 +110,8 @@
err = serviceDiscovery.Register(instance)
assert.Nil(t, err)
- //sometimes nacos may be failed to push update of instance,
- //so it need 10s to pull, we sleep 10 second to make sure instance has been update
+ // sometimes nacos may be failed to push update of instance,
+ // so it need 10s to pull, we sleep 10 second to make sure instance has been update
time.Sleep(3 * time.Second)
page := serviceDiscovery.GetHealthyInstancesByPage(instance.GetServiceName(), 0, 10, true)
assert.NotNil(t, page)
@@ -146,8 +146,8 @@
assert.Equal(t, "bbb", v)
// test dispatcher event
- //err = serviceDiscovery.DispatchEventByServiceName(instanceResult.GetServiceName())
- //assert.Nil(t, err)
+ // err = serviceDiscovery.DispatchEventByServiceName(instanceResult.GetServiceName())
+ // assert.Nil(t, err)
// test AddListener
err = serviceDiscovery.AddListener(®istry.ServiceInstancesChangedListener{ServiceName: instance.GetServiceName()})
diff --git a/registry/consul/utils_test.go b/registry/consul/utils_test.go
index b7e2929..3319beb 100644
--- a/registry/consul/utils_test.go
+++ b/registry/consul/utils_test.go
@@ -19,13 +19,14 @@
import (
"fmt"
- "github.com/apache/dubbo-go/common/logger"
- "github.com/stretchr/testify/assert"
"net"
"net/url"
"strconv"
"sync"
"testing"
+
+ "github.com/apache/dubbo-go/common/logger"
+ "github.com/stretchr/testify/assert"
)
import (
diff --git a/registry/directory/directory.go b/registry/directory/directory.go
index b6f9322..3e6fbc7 100644
--- a/registry/directory/directory.go
+++ b/registry/directory/directory.go
@@ -63,8 +63,8 @@
configurators []config_center.Configurator
consumerConfigurationListener *consumerConfigurationListener
referenceConfigurationListener *referenceConfigurationListener
- //serviceKey string
- //forbidden atomic.Bool
+ // serviceKey string
+ // forbidden atomic.Bool
registerLock sync.Mutex // this lock if for register
}
diff --git a/registry/directory/directory_test.go b/registry/directory/directory_test.go
index b5d81eb..b6ee10d 100644
--- a/registry/directory/directory_test.go
+++ b/registry/directory/directory_test.go
@@ -88,18 +88,18 @@
dir, _ := NewRegistryDirectory(regurl, mockRegistry)
go dir.(*RegistryDirectory).subscribe(common.NewURLWithOptions(common.WithPath("testservice")))
- //for group1
+ // for group1
urlmap := url.Values{}
urlmap.Set(constant.GROUP_KEY, "group1")
- urlmap.Set(constant.CLUSTER_KEY, "failover") //to test merge url
+ urlmap.Set(constant.CLUSTER_KEY, "failover") // to test merge url
for i := 0; i < 3; i++ {
mockRegistry.(*registry.MockRegistry).MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: common.NewURLWithOptions(common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)), common.WithProtocol("dubbo"),
common.WithParams(urlmap))})
}
- //for group2
+ // for group2
urlmap2 := url.Values{}
urlmap2.Set(constant.GROUP_KEY, "group2")
- urlmap2.Set(constant.CLUSTER_KEY, "failover") //to test merge url
+ urlmap2.Set(constant.CLUSTER_KEY, "failover") // to test merge url
for i := 0; i < 3; i++ {
mockRegistry.(*registry.MockRegistry).MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: common.NewURLWithOptions(common.WithPath("TEST"+strconv.FormatInt(int64(i), 10)), common.WithProtocol("dubbo"),
common.WithParams(urlmap2))})
@@ -127,7 +127,6 @@
time.Sleep(6e9)
assert.Len(t, registryDirectory.List(&invocation.RPCInvocation{}), 3)
assert.Equal(t, true, registryDirectory.IsAvailable())
-
}
func Test_MergeProviderUrl(t *testing.T) {
@@ -142,7 +141,6 @@
if len(registryDirectory.cacheInvokers) > 0 {
assert.Equal(t, "mock", registryDirectory.cacheInvokers[0].GetUrl().GetParam(constant.CLUSTER_KEY, ""))
}
-
}
func Test_MergeOverrideUrl(t *testing.T) {
@@ -207,11 +205,13 @@
mockRegistry.MockEvent(®istry.ServiceEvent{Action: remoting.EventTypeAdd, Service: providerUrl})
time.Sleep(1e9)
assert.Len(t, registryDirectory.cacheInvokers, 4)
- mockRegistry.MockEvents([]*registry.ServiceEvent{®istry.ServiceEvent{Action: remoting.EventTypeUpdate, Service: providerUrl}})
+ mockRegistry.MockEvents([]*registry.ServiceEvent{{Action: remoting.EventTypeUpdate, Service: providerUrl}})
time.Sleep(1e9)
assert.Len(t, registryDirectory.cacheInvokers, 1)
- mockRegistry.MockEvents([]*registry.ServiceEvent{®istry.ServiceEvent{Action: remoting.EventTypeUpdate, Service: providerUrl},
- ®istry.ServiceEvent{Action: remoting.EventTypeUpdate, Service: providerUrl2}})
+ mockRegistry.MockEvents([]*registry.ServiceEvent{
+ {Action: remoting.EventTypeUpdate, Service: providerUrl},
+ {Action: remoting.EventTypeUpdate, Service: providerUrl2},
+ })
time.Sleep(1e9)
assert.Len(t, registryDirectory.cacheInvokers, 2)
// clear all address
diff --git a/registry/etcdv3/listener.go b/registry/etcdv3/listener.go
index f900495..6d72899 100644
--- a/registry/etcdv3/listener.go
+++ b/registry/etcdv3/listener.go
@@ -51,7 +51,6 @@
// DataChange processes the data change event from registry center of etcd
func (l *dataListener) DataChange(eventType remoting.Event) bool {
-
index := strings.Index(eventType.Path, "/providers/")
if index == -1 {
logger.Warnf("Listen with no url, event.path={%v}", eventType.Path)
diff --git a/registry/etcdv3/listener_test.go b/registry/etcdv3/listener_test.go
index ff7f63f..0028938 100644
--- a/registry/etcdv3/listener_test.go
+++ b/registry/etcdv3/listener_test.go
@@ -44,7 +44,6 @@
// start etcd server
func (suite *RegistryTestSuite) SetupSuite() {
-
t := suite.T()
cfg := embed.NewConfig()
@@ -75,7 +74,6 @@
}
func (suite *RegistryTestSuite) TestDataChange() {
-
t := suite.T()
listener := NewRegistryDataListener(&MockDataListener{})
diff --git a/registry/etcdv3/registry.go b/registry/etcdv3/registry.go
index 7ccf326..46ba6b6 100644
--- a/registry/etcdv3/registry.go
+++ b/registry/etcdv3/registry.go
@@ -73,7 +73,6 @@
}
func newETCDV3Registry(url *common.URL) (registry.Registry, error) {
-
timeout, err := time.ParseDuration(url.GetParam(constant.REGISTRY_TIMEOUT_KEY, constant.DEFAULT_REG_TIMEOUT))
if err != nil {
logger.Errorf("timeout config %v is invalid ,err is %v",
@@ -95,7 +94,7 @@
); err != nil {
return nil, err
}
- r.WaitGroup().Add(1) //etcdv3 client start successful, then wg +1
+ r.WaitGroup().Add(1) // etcdv3 client start successful, then wg +1
go etcdv3.HandleClientRestart(r)
@@ -165,7 +164,7 @@
r.listenerLock.Unlock()
}
- //register the svc to dataListener
+ // register the svc to dataListener
r.dataListener.AddInterestedURL(svc)
go r.listener.ListenServiceEvent(fmt.Sprintf("/dubbo/%s/"+constant.DEFAULT_CATEGORY, svc.Service()), r.dataListener)
diff --git a/registry/etcdv3/registry_test.go b/registry/etcdv3/registry_test.go
index d94eff6..dbbb7af 100644
--- a/registry/etcdv3/registry_test.go
+++ b/registry/etcdv3/registry_test.go
@@ -33,7 +33,6 @@
)
func initRegistry(t *testing.T) *etcdV3Registry {
-
regurl, err := common.NewURL("registry://127.0.0.1:2379", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
if err != nil {
t.Fatal(err)
@@ -51,7 +50,6 @@
}
func (suite *RegistryTestSuite) TestRegister() {
-
t := suite.T()
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
@@ -68,19 +66,18 @@
}
func (suite *RegistryTestSuite) TestSubscribe() {
-
t := suite.T()
regurl, _ := common.NewURL("registry://127.0.0.1:1111", common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
reg := initRegistry(t)
- //provider register
+ // provider register
err := reg.Register(url)
if err != nil {
t.Fatal(err)
}
- //consumer register
+ // consumer register
regurl.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER))
reg2 := initRegistry(t)
@@ -99,7 +96,6 @@
}
func (suite *RegistryTestSuite) TestConsumerDestroy() {
-
t := suite.T()
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
@@ -109,23 +105,21 @@
t.Fatal(err)
}
- //listener.Close()
+ // listener.Close()
time.Sleep(1e9)
reg.Destroy()
assert.Equal(t, false, reg.IsAvailable())
-
}
func (suite *RegistryTestSuite) TestProviderDestroy() {
-
t := suite.T()
reg := initRegistry(t)
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
err := reg.Register(url)
assert.NoError(t, err)
- //listener.Close()
+ // listener.Close()
time.Sleep(1e9)
reg.Destroy()
assert.Equal(t, false, reg.IsAvailable())
diff --git a/registry/etcdv3/service_discovery.go b/registry/etcdv3/service_discovery.go
index ca6016e..c9c3d43 100644
--- a/registry/etcdv3/service_discovery.go
+++ b/registry/etcdv3/service_discovery.go
@@ -45,9 +45,7 @@
ROOT = "/services"
)
-var (
- initLock sync.Mutex
-)
+var initLock sync.Mutex
func init() {
extension.SetServiceDiscovery(constant.ETCDV3_KEY, newEtcdV3ServiceDiscovery)
@@ -82,7 +80,6 @@
// Register will register an instance of ServiceInstance to registry
func (e *etcdV3ServiceDiscovery) Register(instance registry.ServiceInstance) error {
-
e.serviceInstance = &instance
path := toPath(instance)
@@ -147,7 +144,6 @@
// GetInstances will return all service instances with serviceName
func (e *etcdV3ServiceDiscovery) GetInstances(serviceName string) []registry.ServiceInstance {
-
if nil != e.client {
// get keys and values
_, vList, err := e.client.GetChildrenKVList(toParentPath(serviceName))
@@ -171,7 +167,6 @@
// GetInstancesByPage will return a page containing instances of ServiceInstance with the serviceName
// the page will start at offset
func (e *etcdV3ServiceDiscovery) GetInstancesByPage(serviceName string, offset int, pageSize int) gxpage.Pager {
-
all := e.GetInstances(serviceName)
res := make([]interface{}, 0, pageSize)
@@ -253,7 +248,6 @@
// register service watcher
func (e *etcdV3ServiceDiscovery) registerSreviceWatcher(serviceName string) error {
-
initLock.Lock()
defer initLock.Unlock()
@@ -273,7 +267,6 @@
// when child data change should DispatchEventByServiceName
func (e *etcdV3ServiceDiscovery) DataChange(eventType remoting.Event) bool {
-
if eventType.Action == remoting.EventTypeUpdate {
instance := ®istry.DefaultServiceInstance{}
err := jsonutil.DecodeJSON([]byte(eventType.Content), &instance)
@@ -291,7 +284,6 @@
// netEcdv3ServiceDiscovery
func newEtcdV3ServiceDiscovery(name string) (registry.ServiceDiscovery, error) {
-
initLock.Lock()
defer initLock.Unlock()
diff --git a/registry/event/customizable_service_instance_listener.go b/registry/event/customizable_service_instance_listener.go
index 07e84c1..65e56e6 100644
--- a/registry/event/customizable_service_instance_listener.go
+++ b/registry/event/customizable_service_instance_listener.go
@@ -32,8 +32,7 @@
}
// customizableServiceInstanceListener is singleton
-type customizableServiceInstanceListener struct {
-}
+type customizableServiceInstanceListener struct{}
// GetPriority return priority 9999,
// 9999 is big enough to make sure it will be last invoked
diff --git a/registry/event/customizable_service_instance_listener_test.go b/registry/event/customizable_service_instance_listener_test.go
index 1c81ece..b2dcd93 100644
--- a/registry/event/customizable_service_instance_listener_test.go
+++ b/registry/event/customizable_service_instance_listener_test.go
@@ -32,7 +32,6 @@
)
func TestGetCustomizableServiceInstanceListener(t *testing.T) {
-
prepareMetadataServiceForTest()
cus := GetCustomizableServiceInstanceListener()
@@ -50,8 +49,7 @@
assert.NotNil(t, tp)
}
-type mockEvent struct {
-}
+type mockEvent struct{}
func (m *mockEvent) String() string {
panic("implement me")
@@ -65,8 +63,7 @@
panic("implement me")
}
-type mockCustomizer struct {
-}
+type mockCustomizer struct{}
func (m *mockCustomizer) GetPriority() int {
return 0
diff --git a/registry/event/event_publishing_service_deiscovery_test.go b/registry/event/event_publishing_service_deiscovery_test.go
index 504f7b5..4979f1d 100644
--- a/registry/event/event_publishing_service_deiscovery_test.go
+++ b/registry/event/event_publishing_service_deiscovery_test.go
@@ -40,7 +40,6 @@
)
func TestEventPublishingServiceDiscovery_DispatchEvent(t *testing.T) {
-
// extension.SetMetadataService("local", inmemory.NewMetadataService)
config.GetApplicationConfig().MetadataType = "local"
@@ -69,7 +68,6 @@
si := ®istry.DefaultServiceInstance{Id: "testServiceInstance"}
err = dc.Register(si)
assert.Nil(t, err)
-
}
type TestServiceDiscoveryDestroyingEventListener struct {
@@ -113,8 +111,7 @@
return reflect.TypeOf(ServiceInstancePreRegisteredEvent{})
}
-type ServiceDiscoveryA struct {
-}
+type ServiceDiscoveryA struct{}
// String return mockServiceDiscovery
func (msd *ServiceDiscoveryA) String() string {
@@ -178,8 +175,7 @@
return nil
}
-type mockServiceNameMapping struct {
-}
+type mockServiceNameMapping struct{}
func (m *mockServiceNameMapping) Map(serviceInterface string, group string, version string, protocol string) error {
return nil
diff --git a/registry/event/event_publishing_service_discovery.go b/registry/event/event_publishing_service_discovery.go
index 773eee6..6c418c1 100644
--- a/registry/event/event_publishing_service_discovery.go
+++ b/registry/event/event_publishing_service_discovery.go
@@ -64,7 +64,6 @@
}
return epsd.executeWithEvents(NewServiceInstancePreRegisteredEvent(epsd.serviceDiscovery, instance),
f, NewServiceInstanceRegisteredEvent(epsd.serviceDiscovery, instance))
-
}
// Update returns the result of serviceDiscovery.Update
diff --git a/registry/event/log_event_listener.go b/registry/event/log_event_listener.go
index 0781a6d..c73ff29 100644
--- a/registry/event/log_event_listener.go
+++ b/registry/event/log_event_listener.go
@@ -33,8 +33,7 @@
}
// logEventListener is singleton
-type logEventListener struct {
-}
+type logEventListener struct{}
func (l *logEventListener) GetPriority() int {
return 0
@@ -49,8 +48,10 @@
return reflect.TypeOf(&observer.BaseEvent{})
}
-var logEventListenerInstance *logEventListener
-var logEventListenerOnce sync.Once
+var (
+ logEventListenerInstance *logEventListener
+ logEventListenerOnce sync.Once
+)
func GetLogEventListener() observer.EventListener {
logEventListenerOnce.Do(func() {
diff --git a/registry/event/metadata_service_url_params_customizer.go b/registry/event/metadata_service_url_params_customizer.go
index 6d8f99b..2274cac 100644
--- a/registry/event/metadata_service_url_params_customizer.go
+++ b/registry/event/metadata_service_url_params_customizer.go
@@ -42,7 +42,6 @@
// remove TIMESTAMP_KEY because it's nonsense
constant.TIMESTAMP_KEY)
extension.AddCustomizers(&metadataServiceURLParamsMetadataCustomizer{exceptKeys: exceptKeys})
-
}
type metadataServiceURLParamsMetadataCustomizer struct {
@@ -79,7 +78,6 @@
}
func (m *metadataServiceURLParamsMetadataCustomizer) convertToParams(urls []interface{}) map[string]map[string]string {
-
// usually there will be only one protocol
res := make(map[string]map[string]string, 1)
// those keys are useless
diff --git a/registry/event/metadata_service_url_params_customizer_test.go b/registry/event/metadata_service_url_params_customizer_test.go
index c041232..690c95d 100644
--- a/registry/event/metadata_service_url_params_customizer_test.go
+++ b/registry/event/metadata_service_url_params_customizer_test.go
@@ -44,7 +44,6 @@
}
func TestMetadataServiceURLParamsMetadataCustomizer(t *testing.T) {
-
prepareMetadataServiceForTest()
msup := &metadataServiceURLParamsMetadataCustomizer{exceptKeys: gxset.NewSet()}
diff --git a/registry/event/protocol_ports_metadata_customizer.go b/registry/event/protocol_ports_metadata_customizer.go
index a58471c..8f40149 100644
--- a/registry/event/protocol_ports_metadata_customizer.go
+++ b/registry/event/protocol_ports_metadata_customizer.go
@@ -35,8 +35,7 @@
}
// ProtocolPortsMetadataCustomizer will update the endpoints
-type ProtocolPortsMetadataCustomizer struct {
-}
+type ProtocolPortsMetadataCustomizer struct{}
// GetPriority will return 0, which means it will be invoked at the beginning
func (p *ProtocolPortsMetadataCustomizer) GetPriority() int {
diff --git a/registry/event/service_revision_customizer.go b/registry/event/service_revision_customizer.go
index 4793e91..5d9668c 100644
--- a/registry/event/service_revision_customizer.go
+++ b/registry/event/service_revision_customizer.go
@@ -39,8 +39,7 @@
extension.AddCustomizers(&subscribedServicesRevisionMetadataCustomizer{})
}
-type exportedServicesRevisionMetadataCustomizer struct {
-}
+type exportedServicesRevisionMetadataCustomizer struct{}
// GetPriority will return 1 so that it will be invoked in front of user defining Customizer
func (e *exportedServicesRevisionMetadataCustomizer) GetPriority() int {
@@ -56,7 +55,6 @@
}
urls, err := ms.GetExportedURLs(constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE, constant.ANY_VALUE)
-
if err != nil {
logger.Errorf("could not find the exported url", err)
}
@@ -68,8 +66,7 @@
instance.GetMetadata()[constant.EXPORTED_SERVICES_REVISION_PROPERTY_NAME] = revision
}
-type subscribedServicesRevisionMetadataCustomizer struct {
-}
+type subscribedServicesRevisionMetadataCustomizer struct{}
// GetPriority will return 2 so that it will be invoked in front of user defining Customizer
func (e *subscribedServicesRevisionMetadataCustomizer) GetPriority() int {
@@ -85,7 +82,6 @@
}
urls, err := ms.GetSubscribedURLs()
-
if err != nil {
logger.Errorf("could not find the subscribed url", err)
}
diff --git a/registry/file/listener.go b/registry/file/listener.go
index 3fe7400..5d2193a 100644
--- a/registry/file/listener.go
+++ b/registry/file/listener.go
@@ -20,10 +20,8 @@
import "github.com/apache/dubbo-go/config_center"
// RegistryConfigurationListener represent the processor of flie watcher
-type RegistryConfigurationListener struct {
-}
+type RegistryConfigurationListener struct{}
// Process submit the ConfigChangeEvent to the event chan to notify all observer
func (l *RegistryConfigurationListener) Process(configType *config_center.ConfigChangeEvent) {
-
}
diff --git a/registry/file/service_discovery.go b/registry/file/service_discovery.go
index 768a1c2..f68498d 100644
--- a/registry/file/service_discovery.go
+++ b/registry/file/service_discovery.go
@@ -265,7 +265,7 @@
// AddListener adds a new ServiceInstancesChangedListener
// client
func (fssd *fileSystemServiceDiscovery) AddListener(listener *registry.ServiceInstancesChangedListener) error {
- //fssd.dynamicConfiguration.AddListener(listener.ServiceName)
+ // fssd.dynamicConfiguration.AddListener(listener.ServiceName)
return nil
}
diff --git a/registry/file/service_discovery_test.go b/registry/file/service_discovery_test.go
index 0062eae..ee2ad27 100644
--- a/registry/file/service_discovery_test.go
+++ b/registry/file/service_discovery_test.go
@@ -35,9 +35,7 @@
"github.com/apache/dubbo-go/registry"
)
-var (
- testName = "test"
-)
+var testName = "test"
func TestNewFileSystemServiceDiscoveryAndDestroy(t *testing.T) {
prepareData()
diff --git a/registry/kubernetes/listener.go b/registry/kubernetes/listener.go
index e20b7c7..9b8075c 100644
--- a/registry/kubernetes/listener.go
+++ b/registry/kubernetes/listener.go
@@ -51,7 +51,6 @@
// DataChange
// notify listen, when interest event
func (l *dataListener) DataChange(eventType remoting.Event) bool {
-
index := strings.Index(eventType.Path, "/providers/")
if index == -1 {
logger.Warnf("Listen with no url, event.path={%v}", eventType.Path)
diff --git a/registry/kubernetes/listener_test.go b/registry/kubernetes/listener_test.go
index ef6e8fb..e70c15d 100644
--- a/registry/kubernetes/listener_test.go
+++ b/registry/kubernetes/listener_test.go
@@ -44,7 +44,6 @@
func (*MockDataListener) Process(configType *config_center.ConfigChangeEvent) {}
func TestDataChange(t *testing.T) {
-
listener := NewRegistryDataListener(&MockDataListener{})
url, _ := common.NewURL("jsonrpc%3A%2F%2F127.0.0.1%3A20001%2Fcom.ikurento.user.UserProvider%3Fanyhost%3Dtrue%26app.version%3D0.0.1%26application%3DBDTService%26category%3Dproviders%26cluster%3Dfailover%26dubbo%3Ddubbo-provider-golang-2.6.0%26environment%3Ddev%26group%3D%26interface%3Dcom.ikurento.user.UserProvider%26ip%3D10.32.20.124%26loadbalance%3Drandom%26methods.GetUser.loadbalance%3Drandom%26methods.GetUser.retries%3D1%26methods.GetUser.weight%3D0%26module%3Ddubbogo%2Buser-info%2Bserver%26name%3DBDTService%26organization%3Dikurento.com%26owner%3DZX%26pid%3D74500%26retries%3D0%26service.filter%3Decho%26side%3Dprovider%26timestamp%3D1560155407%26version%3D%26warmup%3D100")
listener.AddInterestedURL(url)
diff --git a/registry/kubernetes/registry.go b/registry/kubernetes/registry.go
index a26478f..9be6387 100644
--- a/registry/kubernetes/registry.go
+++ b/registry/kubernetes/registry.go
@@ -46,8 +46,8 @@
)
func init() {
- //processID = fmt.Sprintf("%d", os.Getpid())
- //localIP = common.GetLocalIp()
+ // processID = fmt.Sprintf("%d", os.Getpid())
+ // localIP = common.GetLocalIp()
extension.SetRegistry(Name, newKubernetesRegistry)
}
@@ -84,7 +84,6 @@
// CloseListener closes listeners
func (r *kubernetesRegistry) CloseListener() {
-
r.cltLock.Lock()
l := r.configListener
r.cltLock.Unlock()
@@ -113,10 +112,7 @@
// DoSubscribe actually subscribe the provider URL
func (r *kubernetesRegistry) DoSubscribe(svc *common.URL) (registry.Listener, error) {
-
- var (
- configListener *configurationListener
- )
+ var configListener *configurationListener
r.listenerLock.Lock()
configListener = r.configListener
@@ -137,7 +133,7 @@
r.listenerLock.Unlock()
}
- //register the svc to dataListener
+ // register the svc to dataListener
r.dataListener.AddInterestedURL(svc)
go r.listener.ListenServiceEvent(fmt.Sprintf("/dubbo/%s/"+constant.DEFAULT_CATEGORY, svc.Service()), r.dataListener)
@@ -157,7 +153,6 @@
}
func newKubernetesRegistry(url *common.URL) (registry.Registry, error) {
-
// actually, kubernetes use in-cluster config,
r := &kubernetesRegistry{}
@@ -196,7 +191,6 @@
// HandleClientRestart will reconnect to kubernetes registry center
func (r *kubernetesRegistry) HandleClientRestart() {
-
var (
err error
failTimes int
diff --git a/registry/kubernetes/registry_test.go b/registry/kubernetes/registry_test.go
index a816b03..7200dd5 100644
--- a/registry/kubernetes/registry_test.go
+++ b/registry/kubernetes/registry_test.go
@@ -202,7 +202,6 @@
`
func getTestRegistry(t *testing.T) *kubernetesRegistry {
-
const (
podNameKey = "HOSTNAME"
nameSpaceKey = "NAMESPACE"
@@ -240,7 +239,6 @@
}
func TestRegister(t *testing.T) {
-
r := getTestRegistry(t)
defer r.Destroy()
@@ -259,7 +257,6 @@
}
func TestSubscribe(t *testing.T) {
-
r := getTestRegistry(t)
defer r.Destroy()
@@ -276,7 +273,6 @@
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
-
defer wg.Done()
registerErr := r.Register(url)
if registerErr != nil {
@@ -294,7 +290,6 @@
}
func TestConsumerDestroy(t *testing.T) {
-
r := getTestRegistry(t)
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider",
@@ -306,16 +301,14 @@
t.Fatal(err)
}
- //listener.Close()
+ // listener.Close()
time.Sleep(1e9)
r.Destroy()
assert.Equal(t, false, r.IsAvailable())
-
}
func TestProviderDestroy(t *testing.T) {
-
r := getTestRegistry(t)
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider",
@@ -330,7 +323,6 @@
}
func TestNewRegistry(t *testing.T) {
-
regUrl, err := common.NewURL("registry://127.0.0.1:443",
common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.PROVIDER)))
if err != nil {
@@ -343,7 +335,6 @@
}
func TestHandleClientRestart(t *testing.T) {
-
r := getTestRegistry(t)
r.WaitGroup().Add(1)
go r.HandleClientRestart()
diff --git a/registry/mock_registry.go b/registry/mock_registry.go
index 6287bb0..953f428 100644
--- a/registry/mock_registry.go
+++ b/registry/mock_registry.go
@@ -141,7 +141,6 @@
}
func (*listener) Close() {
-
}
// nolint
diff --git a/registry/nacos/registry.go b/registry/nacos/registry.go
index e9a4bd3..4bc88d7 100644
--- a/registry/nacos/registry.go
+++ b/registry/nacos/registry.go
@@ -41,9 +41,7 @@
"github.com/apache/dubbo-go/registry"
)
-var (
- localIP = ""
-)
+var localIP = ""
const (
// RegistryConnDelay registry connection delay
@@ -293,7 +291,7 @@
clientConfig.Endpoint = url.GetParam(constant.NACOS_ENDPOINT, "")
clientConfig.NamespaceId = url.GetParam(constant.NACOS_NAMESPACE_ID, "")
- //enable local cache when nacos can not connect.
+ // enable local cache when nacos can not connect.
notLoadCache, err := strconv.ParseBool(url.GetParam(constant.NACOS_NOT_LOAD_LOCAL_CACHE, "false"))
if err != nil {
logger.Errorf("ParseBool - error: %v", err)
diff --git a/registry/nacos/registry_test.go b/registry/nacos/registry_test.go
index b828205..ab770fb 100644
--- a/registry/nacos/registry_test.go
+++ b/registry/nacos/registry_test.go
@@ -114,7 +114,6 @@
}
t.Logf("serviceEvent:%+v \n", serviceEvent)
assert.Regexp(t, ".*ServiceEvent{Action{add}.*", serviceEvent.String())
-
}
func TestNacosRegistry_Subscribe_del(t *testing.T) {
@@ -178,9 +177,11 @@
assert.Regexp(t, ".*ServiceEvent{Action{add}.*", serviceEvent2.String())
nacosReg := reg.(*nacosRegistry)
- //deregister instance to mock instance offline
- _, err = nacosReg.namingClient.DeregisterInstance(vo.DeregisterInstanceParam{Ip: "127.0.0.2", Port: 20000,
- ServiceName: "providers:com.ikurento.user.UserProvider:2.0.0:guangzhou-idc"})
+ // deregister instance to mock instance offline
+ _, err = nacosReg.namingClient.DeregisterInstance(vo.DeregisterInstanceParam{
+ Ip: "127.0.0.2", Port: 20000,
+ ServiceName: "providers:com.ikurento.user.UserProvider:2.0.0:guangzhou-idc",
+ })
assert.NoError(t, err)
serviceEvent3, _ := listener.Next()
diff --git a/registry/nacos/service_discovery.go b/registry/nacos/service_discovery.go
index 4533e7b..785e395 100644
--- a/registry/nacos/service_discovery.go
+++ b/registry/nacos/service_discovery.go
@@ -308,7 +308,6 @@
// newNacosServiceDiscovery will create new service discovery instance
// use double-check pattern to reduce race condition
func newNacosServiceDiscovery(name string) (registry.ServiceDiscovery, error) {
-
instance, ok := instanceMap[name]
if ok {
return instance, nil
diff --git a/registry/nacos/service_discovery_test.go b/registry/nacos/service_discovery_test.go
index b6902ed..a9bc27b 100644
--- a/registry/nacos/service_discovery_test.go
+++ b/registry/nacos/service_discovery_test.go
@@ -37,9 +37,7 @@
"github.com/apache/dubbo-go/registry"
)
-var (
- testName = "test"
-)
+var testName = "test"
func Test_newNacosServiceDiscovery(t *testing.T) {
name := "nacos1"
@@ -67,7 +65,6 @@
res, err := newNacosServiceDiscovery(name)
assert.Nil(t, err)
assert.NotNil(t, res)
-
}
func TestNacosServiceDiscovery_Destroy(t *testing.T) {
@@ -121,8 +118,8 @@
err = serviceDiscovery.Register(instance)
assert.Nil(t, err)
- //sometimes nacos may be failed to push update of instance,
- //so it need 10s to pull, we sleep 10 second to make sure instance has been update
+ // sometimes nacos may be failed to push update of instance,
+ // so it need 10s to pull, we sleep 10 second to make sure instance has been update
time.Sleep(11 * time.Second)
page := serviceDiscovery.GetHealthyInstancesByPage(serviceName, 0, 10, true)
assert.NotNil(t, page)
@@ -136,7 +133,7 @@
assert.Equal(t, host, instance.GetHost())
assert.Equal(t, port, instance.GetPort())
// TODO: console.nacos.io has updated to nacos 2.0 and serviceName has changed in 2.0, so ignore temporarily.
- //assert.Equal(t, serviceName, instance.GetServiceName())
+ // assert.Equal(t, serviceName, instance.GetServiceName())
assert.Equal(t, 0, len(instance.GetMetadata()))
instance.Metadata["a"] = "b"
diff --git a/registry/protocol/protocol.go b/registry/protocol/protocol.go
index 4fcdf93..3e6e629 100644
--- a/registry/protocol/protocol.go
+++ b/registry/protocol/protocol.go
@@ -131,8 +131,8 @@
// Refer provider service from registry center
func (proto *registryProtocol) Refer(url *common.URL) protocol.Invoker {
- var registryUrl = url
- var serviceUrl = registryUrl.SubURL
+ registryUrl := url
+ serviceUrl := registryUrl.SubURL
if registryUrl.Protocol == constant.REGISTRY_PROTOCOL {
registryUrl.Protocol = registryUrl.GetParam(constant.REGISTRY_KEY, "")
}
diff --git a/registry/protocol/protocol_test.go b/registry/protocol/protocol_test.go
index 0fca552..c425905 100644
--- a/registry/protocol/protocol_test.go
+++ b/registry/protocol/protocol_test.go
@@ -138,7 +138,6 @@
}
func TestExporter(t *testing.T) {
-
regProtocol := newRegistryProtocol()
exporterNormal(t, regProtocol)
}
@@ -295,5 +294,4 @@
assert.NotContains(t, providerUrl.GetParams(), ".c")
assert.NotContains(t, providerUrl.GetParams(), ".d")
assert.Contains(t, providerUrl.GetParams(), "a")
-
}
diff --git a/registry/servicediscovery/instance/random/random_service_instance_selector.go b/registry/servicediscovery/instance/random/random_service_instance_selector.go
index 7e4e0ee..95ca185 100644
--- a/registry/servicediscovery/instance/random/random_service_instance_selector.go
+++ b/registry/servicediscovery/instance/random/random_service_instance_selector.go
@@ -33,9 +33,8 @@
extension.SetServiceInstanceSelector("random", NewRandomServiceInstanceSelector)
}
-//the ServiceInstanceSelector implementation based on Random algorithm
-type RandomServiceInstanceSelector struct {
-}
+// the ServiceInstanceSelector implementation based on Random algorithm
+type RandomServiceInstanceSelector struct{}
func NewRandomServiceInstanceSelector() instance.ServiceInstanceSelector {
return &RandomServiceInstanceSelector{}
@@ -51,5 +50,4 @@
rand.Seed(time.Now().UnixNano())
index := rand.Intn(len(serviceInstances))
return serviceInstances[index]
-
}
diff --git a/registry/servicediscovery/instance/service_instance_selector.go b/registry/servicediscovery/instance/service_instance_selector.go
index 5690ab6..a5ad3db 100644
--- a/registry/servicediscovery/instance/service_instance_selector.go
+++ b/registry/servicediscovery/instance/service_instance_selector.go
@@ -23,6 +23,6 @@
)
type ServiceInstanceSelector interface {
- //Select an instance of ServiceInstance by the specified ServiceInstance service instances
+ // Select an instance of ServiceInstance by the specified ServiceInstance service instances
Select(url *common.URL, serviceInstances []registry.ServiceInstance) registry.ServiceInstance
}
diff --git a/registry/servicediscovery/service_discovery_registry.go b/registry/servicediscovery/service_discovery_registry.go
index c97a7f7..e3f2af3 100644
--- a/registry/servicediscovery/service_discovery_registry.go
+++ b/registry/servicediscovery/service_discovery_registry.go
@@ -73,7 +73,6 @@
}
func newServiceDiscoveryRegistry(url *common.URL) (registry.Registry, error) {
-
tryInitMetadataService(url)
serviceDiscovery, err := creatServiceDiscovery(url)
@@ -131,7 +130,7 @@
if len(literalServices) == 0 {
return set
}
- var splitServices = strings.Split(literalServices, ",")
+ splitServices := strings.Split(literalServices, ",")
for _, s := range splitServices {
if len(s) != 0 {
set.Add(s)
@@ -165,7 +164,6 @@
return nil
}
ok, err := s.metaDataService.ExportURL(url)
-
if err != nil {
logger.Errorf("The URL[%s] registry catch error:%s!", url.String(), err.Error())
return err
@@ -226,7 +224,6 @@
logger.Errorf("add listener[%s] catch error,url:%s err:%s", listenerId, url.String(), err.Error())
}
}
-
}
func getUrlKey(url *common.URL) string {
@@ -274,7 +271,6 @@
Service: url,
})
}
-
}
func (s *serviceDiscoveryRegistry) synthesizeSubscribedURLs(subscribedURL *common.URL, serviceInstances []registry.ServiceInstance) []*common.URL {
@@ -363,7 +359,6 @@
for _, ui := range result {
u, err := common.NewURL(ui.(string))
-
if err != nil {
logger.Errorf("could not parse the url string to URL structure: %s", ui.(string), err)
continue
@@ -522,7 +517,6 @@
}
}
return clonedExportedURLs
-
}
type endpoint struct {
@@ -549,6 +543,7 @@
}
return -1
}
+
func (s *serviceDiscoveryRegistry) getTemplateExportedURLs(url *common.URL, serviceInstance registry.ServiceInstance) []*common.URL {
exportedURLs := s.getRevisionExportedURLs(serviceInstance)
if len(exportedURLs) == 0 {
@@ -607,21 +602,17 @@
}
func (icn *InstanceChangeNotify) Notify(event observer.Event) {
-
if se, ok := event.(*registry.ServiceInstancesChangedEvent); ok {
sdr := icn.serviceDiscoveryRegistry
sdr.subscribe(sdr.url.SubURL, icn.notify, se.ServiceName, se.Instances)
}
}
-var (
- exporting = &atomic.Bool{}
-)
+var exporting = &atomic.Bool{}
// tryInitMetadataService will try to initialize metadata service
// TODO (move to somewhere)
func tryInitMetadataService(url *common.URL) {
-
ms, err := extension.GetMetadataService(config.GetApplicationConfig().MetadataType)
if err != nil {
logger.Errorf("could not init metadata service", err)
diff --git a/registry/servicediscovery/service_discovery_registry_test.go b/registry/servicediscovery/service_discovery_registry_test.go
index 391d92c..6e1f228 100644
--- a/registry/servicediscovery/service_discovery_registry_test.go
+++ b/registry/servicediscovery/service_discovery_registry_test.go
@@ -26,6 +26,7 @@
"github.com/dubbogo/gost/hash/page"
"github.com/stretchr/testify/assert"
)
+
import (
"github.com/apache/dubbo-go/common"
"github.com/apache/dubbo-go/common/extension"
@@ -83,8 +84,7 @@
assert.NoError(t, err)
}
-type mockEventDispatcher struct {
-}
+type mockEventDispatcher struct{}
func (m *mockEventDispatcher) AddEventListener(observer.EventListener) {
}
@@ -111,8 +111,7 @@
func (m *mockEventDispatcher) Dispatch(observer.Event) {
}
-type mockServiceNameMapping struct {
-}
+type mockServiceNameMapping struct{}
func (m *mockServiceNameMapping) Map(string, string, string, string) error {
return nil
@@ -122,8 +121,7 @@
panic("implement me")
}
-type mockServiceDiscovery struct {
-}
+type mockServiceDiscovery struct{}
func (m *mockServiceDiscovery) String() string {
panic("implement me")
@@ -185,8 +183,7 @@
panic("implement me")
}
-type mockMetadataService struct {
-}
+type mockMetadataService struct{}
func (m *mockMetadataService) Reference() string {
panic("implement me")
diff --git a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
index c6b3aea..a002aad 100644
--- a/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
+++ b/registry/servicediscovery/synthesizer/rest/rest_subscribed_urls_synthesizer.go
@@ -33,9 +33,8 @@
synthesizer.AddSynthesizer(NewRestSubscribedURLsSynthesizer())
}
-//SubscribedURLsSynthesizer implementation for rest protocol
-type RestSubscribedURLsSynthesizer struct {
-}
+// SubscribedURLsSynthesizer implementation for rest protocol
+type RestSubscribedURLsSynthesizer struct{}
func (r RestSubscribedURLsSynthesizer) Support(subscribedURL *common.URL) bool {
return "rest" == subscribedURL.Protocol
diff --git a/registry/zookeeper/listener.go b/registry/zookeeper/listener.go
index 5a7d14b..d8e7629 100644
--- a/registry/zookeeper/listener.go
+++ b/registry/zookeeper/listener.go
@@ -18,9 +18,10 @@
package zookeeper
import (
- gxzookeeper "github.com/dubbogo/gost/database/kv/zk"
"strings"
"sync"
+
+ gxzookeeper "github.com/dubbogo/gost/database/kv/zk"
)
import (
@@ -45,7 +46,8 @@
// NewRegistryDataListener constructs a new RegistryDataListener
func NewRegistryDataListener() *RegistryDataListener {
return &RegistryDataListener{
- subscribed: make(map[string]config_center.ConfigurationListener)}
+ subscribed: make(map[string]config_center.ConfigurationListener),
+ }
}
// SubscribeURL is used to set a watch listener for url
@@ -131,7 +133,8 @@
events: make(chan *config_center.ConfigChangeEvent, 32),
isClosed: false,
close: make(chan struct{}, 1),
- subscribeURL: conf}
+ subscribeURL: conf,
+ }
}
// Process submit the ConfigChangeEvent to the event chan to notify all observer
diff --git a/registry/zookeeper/listener_test.go b/registry/zookeeper/listener_test.go
index 20ec1cf..c41c831 100644
--- a/registry/zookeeper/listener_test.go
+++ b/registry/zookeeper/listener_test.go
@@ -39,8 +39,7 @@
assert.Equal(t, true, int)
}
-type MockConfigurationListener struct {
-}
+type MockConfigurationListener struct{}
func (*MockConfigurationListener) Process(configType *config_center.ConfigChangeEvent) {
}
diff --git a/registry/zookeeper/registry.go b/registry/zookeeper/registry.go
index 8b21aae..bef0ae5 100644
--- a/registry/zookeeper/registry.go
+++ b/registry/zookeeper/registry.go
@@ -60,7 +60,7 @@
listener *zookeeper.ZkEventListener
dataListener *RegistryDataListener
cltLock sync.Mutex
- //for provider
+ // for provider
zkPath map[string]int // key = protocol://ip:port/interface
}
@@ -101,7 +101,7 @@
err error
r *zkRegistry
c *zk.TestCluster
- //event <-chan zk.Event
+ // event <-chan zk.Event
)
r = &zkRegistry{
@@ -112,7 +112,7 @@
if err != nil {
return nil, nil, err
}
- r.WaitGroup().Add(1) //zk client start successful, then wg +1
+ r.WaitGroup().Add(1) // zk client start successful, then wg +1
go zookeeper.HandleClientRestart(r)
r.InitListeners()
return c, r, nil
@@ -243,7 +243,6 @@
}
func (r *zkRegistry) getListener(conf *common.URL) (*RegistryConfigurationListener, error) {
-
var zkListener *RegistryConfigurationListener
dataListener := r.dataListener
ttl := r.GetParam(constant.REGISTRY_TTL_KEY, constant.DEFAULT_REG_TTL)
@@ -280,7 +279,7 @@
r.listenerLock.Unlock()
}
- //Interested register to dataconfig.
+ // Interested register to dataconfig.
r.dataListener.SubscribeURL(conf, zkListener)
go r.listener.ListenServiceEvent(conf, fmt.Sprintf("/dubbo/%s/"+constant.DEFAULT_CATEGORY, url.QueryEscape(conf.Service())), r.dataListener)
@@ -289,7 +288,6 @@
}
func (r *zkRegistry) getCloseListener(conf *common.URL) (*RegistryConfigurationListener, error) {
-
var zkListener *RegistryConfigurationListener
r.dataListener.mutex.Lock()
configurationListener := r.dataListener.subscribed[conf.ServiceKey()]
@@ -308,7 +306,7 @@
return nil, perrors.New("listener is null can not close.")
}
- //Interested register to dataconfig.
+ // Interested register to dataconfig.
r.listenerLock.Lock()
listener := r.listener
r.listener = nil
diff --git a/registry/zookeeper/registry_test.go b/registry/zookeeper/registry_test.go
index 9e52dd7..172ffec 100644
--- a/registry/zookeeper/registry_test.go
+++ b/registry/zookeeper/registry_test.go
@@ -81,7 +81,7 @@
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
ts, reg, _ := newMockZkRegistry(regURL)
- //provider register
+ // provider register
err := reg.Register(url)
assert.NoError(t, err)
@@ -89,7 +89,7 @@
return
}
- //consumer register
+ // consumer register
regURL.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER))
_, reg2, _ := newMockZkRegistry(regURL, gxzookeeper.WithTestCluster(ts))
@@ -113,7 +113,7 @@
url, _ := common.NewURL("dubbo://127.0.0.1:20000/com.ikurento.user.UserProvider", common.WithParamsValue(constant.CLUSTER_KEY, "mock"), common.WithMethods([]string{"GetUser", "AddUser"}))
ts, reg, _ := newMockZkRegistry(regURL)
- //provider register
+ // provider register
err := reg.Register(url)
assert.NoError(t, err)
@@ -121,7 +121,7 @@
return
}
- //consumer register
+ // consumer register
regURL.SetParam(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER))
_, reg2, _ := newMockZkRegistry(regURL, gxzookeeper.WithTestCluster(ts))
@@ -159,7 +159,7 @@
_, err = reg.DoSubscribe(url)
assert.NoError(t, err)
- //listener.Close()
+ // listener.Close()
time.Sleep(1e9)
reg.Destroy()
assert.Equal(t, false, reg.IsAvailable())
@@ -178,7 +178,7 @@
err = reg.Register(url)
assert.Nil(t, err)
- //listener.Close()
+ // listener.Close()
time.Sleep(1e9)
reg.Destroy()
assert.Equal(t, false, reg.IsAvailable())
diff --git a/registry/zookeeper/service_discovery.go b/registry/zookeeper/service_discovery.go
index 06fe0f7..67c89a0 100644
--- a/registry/zookeeper/service_discovery.go
+++ b/registry/zookeeper/service_discovery.go
@@ -63,7 +63,7 @@
type zookeeperServiceDiscovery struct {
client *gxzookeeper.ZookeeperClient
csd *curator_discovery.ServiceDiscovery
- //listener *zookeeper.ZkEventListener
+ // listener *zookeeper.ZkEventListener
url *common.URL
wg sync.WaitGroup
cltLock sync.Mutex
@@ -112,7 +112,7 @@
if err != nil {
return nil, err
}
- zksd.WaitGroup().Add(1) //zk client start successful, then wg +1
+ zksd.WaitGroup().Add(1) // zk client start successful, then wg +1
go zookeeper.HandleClientRestart(zksd)
zksd.csd = curator_discovery.NewServiceDiscovery(zksd.client, rootPath)
return zksd, nil
diff --git a/remoting/codec.go b/remoting/codec.go
index 607d164..30e6309 100644
--- a/remoting/codec.go
+++ b/remoting/codec.go
@@ -32,9 +32,7 @@
Result interface{}
}
-var (
- codec = make(map[string]Codec, 2)
-)
+var codec = make(map[string]Codec, 2)
func RegistryCodec(protocol string, codecTmp Codec) {
codec[protocol] = codecTmp
diff --git a/remoting/etcdv3/client_test.go b/remoting/etcdv3/client_test.go
index 787c24d..4f4fa21 100644
--- a/remoting/etcdv3/client_test.go
+++ b/remoting/etcdv3/client_test.go
@@ -84,7 +84,6 @@
// start etcd server
func (suite *ClientTestSuite) SetupSuite() {
-
t := suite.T()
DefaultListenPeerURLs := "http://localhost:2382"
@@ -138,7 +137,6 @@
}
func (suite *ClientTestSuite) TestClientClose() {
-
c := suite.client
t := suite.T()
@@ -149,7 +147,6 @@
}
func (suite *ClientTestSuite) TestClientValid() {
-
c := suite.client
t := suite.T()
@@ -163,7 +160,6 @@
}
func (suite *ClientTestSuite) TestClientDone() {
-
c := suite.client
go func() {
@@ -179,7 +175,6 @@
}
func (suite *ClientTestSuite) TestClientCreateKV() {
-
tests := tests
c := suite.client
@@ -210,7 +205,6 @@
}
func (suite *ClientTestSuite) TestClientDeleteKV() {
-
tests := tests
c := suite.client
t := suite.T()
@@ -240,11 +234,9 @@
t.Fatal(err)
}
}
-
}
func (suite *ClientTestSuite) TestClientGetChildrenKVList() {
-
tests := tests
c := suite.client
@@ -278,11 +270,9 @@
}
t.Fatalf("expect keylist %v but got %v expect valueList %v but got %v ", expectKList, kList, expectVList, vList)
-
}
func (suite *ClientTestSuite) TestClientWatch() {
-
tests := tests
c := suite.client
@@ -292,7 +282,6 @@
wg.Add(1)
go func() {
-
defer wg.Done()
wc, err := c.watch(prefix)
@@ -304,7 +293,6 @@
var eCreate, eDelete mvccpb.Event
for e := range wc {
-
for _, event := range e.Events {
events = append(events, (mvccpb.Event)(*event))
if event.Type == mvccpb.PUT {
@@ -339,11 +327,9 @@
c.Close()
wg.Wait()
-
}
func (suite *ClientTestSuite) TestClientRegisterTemp() {
-
c := suite.client
observeC := suite.setUpClient()
t := suite.T()
@@ -364,7 +350,6 @@
var eCreate, eDelete mvccpb.Event
for e := range wc {
-
for _, event := range e.Events {
events = append(events, (mvccpb.Event)(*event))
if event.Type == mvccpb.DELETE {
diff --git a/remoting/etcdv3/facade.go b/remoting/etcdv3/facade.go
index 614ba9a..7a17691 100644
--- a/remoting/etcdv3/facade.go
+++ b/remoting/etcdv3/facade.go
@@ -37,15 +37,14 @@
Client() *Client
SetClient(*Client)
ClientLock() *sync.Mutex
- WaitGroup() *sync.WaitGroup //for wait group control, etcd client listener & etcd client container
- Done() chan struct{} //for etcd client control
+ WaitGroup() *sync.WaitGroup // for wait group control, etcd client listener & etcd client container
+ Done() chan struct{} // for etcd client control
RestartCallBack() bool
common.Node
}
// HandleClientRestart keeps the connection between client and server
func HandleClientRestart(r clientFacade) {
-
var (
err error
failTimes int
diff --git a/remoting/etcdv3/listener.go b/remoting/etcdv3/listener.go
index fd6f958..23ee727 100644
--- a/remoting/etcdv3/listener.go
+++ b/remoting/etcdv3/listener.go
@@ -97,7 +97,6 @@
// return true means the event type is DELETE
// return false means the event type is CREATE || UPDATE
func (l *EventListener) handleEvents(event *clientv3.Event, listeners ...remoting.DataListener) bool {
-
logger.Infof("got a etcd event {type: %s, key: %s}", event.Type, event.Kv.Key)
switch event.Type {
@@ -180,7 +179,6 @@
// |
// --------> listenServiceNodeEvent
func (l *EventListener) ListenServiceEvent(key string, listener remoting.DataListener) {
-
l.keyMapLock.RLock()
_, ok := l.keyMap[key]
l.keyMapLock.RUnlock()
diff --git a/remoting/etcdv3/listener_test.go b/remoting/etcdv3/listener_test.go
index 7da8581..cfd8bff 100644
--- a/remoting/etcdv3/listener_test.go
+++ b/remoting/etcdv3/listener_test.go
@@ -52,8 +52,7 @@
`
func (suite *ClientTestSuite) TestListener() {
-
- var tests = []struct {
+ tests := []struct {
input struct {
k string
v string
diff --git a/remoting/exchange.go b/remoting/exchange.go
index ad136a7..07dc549 100644
--- a/remoting/exchange.go
+++ b/remoting/exchange.go
@@ -119,7 +119,7 @@
ConnectTimeout time.Duration
}
-//AsyncCallbackResponse async response for dubbo
+// AsyncCallbackResponse async response for dubbo
type AsyncCallbackResponse struct {
common.CallbackResponse
Opts Options
diff --git a/remoting/exchange_client.go b/remoting/exchange_client.go
index f84cef1..4770285 100644
--- a/remoting/exchange_client.go
+++ b/remoting/exchange_client.go
@@ -81,14 +81,14 @@
return nil
}
if cl.client.Connect(url) != nil {
- //retry for a while
+ // retry for a while
time.Sleep(100 * time.Millisecond)
if cl.client.Connect(url) != nil {
logger.Errorf("Failed to connect server %+v " + url.Location)
return errors.New("Failed to connect server " + url.Location)
}
}
- //FIXME atomic operation
+ // FIXME atomic operation
cl.init = true
return nil
}
diff --git a/remoting/exchange_server.go b/remoting/exchange_server.go
index a8d7c73..41abe21 100644
--- a/remoting/exchange_server.go
+++ b/remoting/exchange_server.go
@@ -23,9 +23,9 @@
// It is interface of server for network communication.
// If you use getty as network communication, you should define GettyServer that implements this interface.
type Server interface {
- //invoke once for connection
+ // invoke once for connection
Start()
- //it is for destroy
+ // it is for destroy
Stop()
}
diff --git a/remoting/getty/config.go b/remoting/getty/config.go
index b6aa082..725aa94 100644
--- a/remoting/getty/config.go
+++ b/remoting/getty/config.go
@@ -134,7 +134,8 @@
WaitTimeout: "1s",
MaxMsgLen: 102400,
SessionName: "client",
- }}
+ },
+ }
}
// GetDefaultServerConfig gets server default configuration
diff --git a/remoting/getty/dubbo_codec_for_test.go b/remoting/getty/dubbo_codec_for_test.go
index 9afc18a..d227eca 100644
--- a/remoting/getty/dubbo_codec_for_test.go
+++ b/remoting/getty/dubbo_codec_for_test.go
@@ -42,8 +42,7 @@
remoting.RegistryCodec("dubbo", codec)
}
-type DubboTestCodec struct {
-}
+type DubboTestCodec struct{}
// encode request for transport
func (c *DubboTestCodec) EncodeRequest(request *remoting.Request) (*bytes.Buffer, error) {
@@ -123,7 +122,7 @@
// encode response
func (c *DubboTestCodec) EncodeResponse(response *remoting.Response) (*bytes.Buffer, error) {
- var ptype = impl.PackageResponse
+ ptype := impl.PackageResponse
if response.IsHeartbeat() {
ptype = impl.PackageHeartbeat
}
@@ -184,7 +183,7 @@
if err != nil {
originErr := perrors.Cause(err)
if originErr == hessian.ErrHeaderNotEnough || originErr == hessian.ErrBodyNotEnough {
- //FIXME
+ // FIXME
return nil, 0, originErr
}
return request, 0, perrors.WithStack(err)
@@ -199,19 +198,19 @@
// convert params of request
req := pkg.Body.(map[string]interface{})
- //invocation := request.Data.(*invocation.RPCInvocation)
+ // invocation := request.Data.(*invocation.RPCInvocation)
var methodName string
var args []interface{}
attachments := make(map[string]interface{})
if req[impl.DubboVersionKey] != nil {
- //dubbo version
+ // dubbo version
request.Version = req[impl.DubboVersionKey].(string)
}
- //path
+ // path
attachments[constant.PATH_KEY] = pkg.Service.Path
- //version
+ // version
attachments[constant.VERSION_KEY] = pkg.Service.Version
- //method
+ // method
methodName = pkg.Service.Method
args = req[impl.ArgsKey].([]interface{})
attachments = req[impl.AttachmentsKey].(map[string]interface{})
@@ -238,7 +237,7 @@
}
response := &remoting.Response{
ID: pkg.Header.ID,
- //Version: pkg.Header.,
+ // Version: pkg.Header.,
SerialID: pkg.Header.SerialID,
Status: pkg.Header.ResponseStatus,
Event: (pkg.Header.Type & impl.PackageHeartbeat) != 0,
@@ -251,7 +250,7 @@
}
} else {
response.Status = hessian.Response_OK
- //reply(session, p, hessian.PackageHeartbeat)
+ // reply(session, p, hessian.PackageHeartbeat)
}
return response, hessian.HEADER_LENGTH + pkg.Header.BodyLen, error
}
diff --git a/remoting/getty/getty_client_test.go b/remoting/getty/getty_client_test.go
index c32e0c2..3b59e9c 100644
--- a/remoting/getty/getty_client_test.go
+++ b/remoting/getty/getty_client_test.go
@@ -52,7 +52,6 @@
}
func testRequestOneWay(t *testing.T, svr *Server, url *common.URL, client *Client) {
-
request := remoting.NewRequest("2.0.2")
up := &UserProvider{}
invocation := createInvocation("GetUser", nil, nil, []interface{}{[]interface{}{"1", "username"}, up},
@@ -62,7 +61,7 @@
request.Data = invocation
request.Event = false
request.TwoWay = false
- //user := &User{}
+ // user := &User{}
err := client.Request(request, 3*time.Second, nil)
assert.NoError(t, err)
}
@@ -169,9 +168,7 @@
}
func testGetUser1(t *testing.T, c *Client) {
- var (
- err error
- )
+ var err error
request := remoting.NewRequest("2.0.2")
invocation := createInvocation("GetUser1", nil, nil, []interface{}{},
[]reflect.Value{})
@@ -189,9 +186,7 @@
}
func testGetUser2(t *testing.T, c *Client) {
- var (
- err error
- )
+ var err error
request := remoting.NewRequest("2.0.2")
invocation := createInvocation("GetUser2", nil, nil, []interface{}{},
[]reflect.Value{})
@@ -207,9 +202,7 @@
}
func testGetUser3(t *testing.T, c *Client) {
- var (
- err error
- )
+ var err error
request := remoting.NewRequest("2.0.2")
invocation := createInvocation("GetUser3", nil, nil, []interface{}{},
[]reflect.Value{})
@@ -230,9 +223,7 @@
}
func testGetUser4(t *testing.T, c *Client) {
- var (
- err error
- )
+ var err error
request := remoting.NewRequest("2.0.2")
invocation := invocation.NewRPCInvocation("GetUser4", []interface{}{[]interface{}{"1", "username"}}, nil)
attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
@@ -250,9 +241,7 @@
}
func testGetUser5(t *testing.T, c *Client) {
- var (
- err error
- )
+ var err error
request := remoting.NewRequest("2.0.2")
invocation := invocation.NewRPCInvocation("GetUser5", []interface{}{map[interface{}]interface{}{"id": "1", "name": "username"}}, nil)
attachment := map[string]string{INTERFACE_KEY: "com.ikurento.user.UserProvider"}
@@ -341,7 +330,6 @@
}
func InitTest(t *testing.T) (*Server, *common.URL) {
-
hessian.RegisterPOJO(&User{})
remoting.RegistryCodec("dubbo", &DubboTestCodec{})
@@ -388,7 +376,8 @@
WaitTimeout: "1s",
MaxMsgLen: 10240000000,
SessionName: "server",
- }})
+ },
+ })
assert.NoError(t, srvConf.CheckValidity())
url, err := common.NewURL("dubbo://127.0.0.1:20060/com.ikurento.user.UserProvider?anyhost=true&" +
@@ -405,7 +394,7 @@
BaseInvoker: *protocol.NewBaseInvoker(url),
}
handler := func(invocation *invocation.RPCInvocation) protocol.RPCResult {
- //result := protocol.RPCResult{}
+ // result := protocol.RPCResult{}
r := invoker.Invoke(context.Background(), invocation)
result := protocol.RPCResult{
Err: r.Error(),
@@ -432,8 +421,7 @@
Name string `json:"name"`
}
- UserProvider struct {
- //user map[string]User
+ UserProvider struct { // user map[string]User
}
)
@@ -473,7 +461,6 @@
}
func (u *UserProvider) GetUser4(ctx context.Context, req []interface{}) ([]interface{}, error) {
-
return []interface{}{User{Id: req[0].([]interface{})[0].(string), Name: req[0].([]interface{})[1].(string)}}, nil
}
diff --git a/remoting/getty/getty_server.go b/remoting/getty/getty_server.go
index 4930a6a..76eb478 100644
--- a/remoting/getty/getty_server.go
+++ b/remoting/getty/getty_server.go
@@ -40,9 +40,7 @@
"github.com/apache/dubbo-go/remoting"
)
-var (
- srvConf *ServerConfig
-)
+var srvConf *ServerConfig
func initServer(protocol string) {
// load clientconfig from provider_config
@@ -104,7 +102,7 @@
// NewServer create a new Server
func NewServer(url *common.URL, handlers func(*invocation.RPCInvocation) protocol.RPCResult) *Server {
- //init
+ // init
initServer(url.Protocol)
srvConf.SSLEnabled = url.GetParamBool(constant.SSL_ENABLED_KEY, false)
diff --git a/remoting/getty/listener.go b/remoting/getty/listener.go
index 5443d37..96df02b 100644
--- a/remoting/getty/listener.go
+++ b/remoting/getty/listener.go
@@ -289,7 +289,6 @@
}
reply(session, resp)
}
-
}()
invoc, ok := req.Data.(*invocation.RPCInvocation)
diff --git a/remoting/getty/opentracing.go b/remoting/getty/opentracing.go
index 4ba4fde..ab74c85 100644
--- a/remoting/getty/opentracing.go
+++ b/remoting/getty/opentracing.go
@@ -20,6 +20,7 @@
import (
"github.com/opentracing/opentracing-go"
)
+
import (
invocation_impl "github.com/apache/dubbo-go/protocol/invocation"
)
@@ -36,7 +37,7 @@
}
func filterContext(attachments map[string]interface{}) map[string]string {
- var traceAttchment = make(map[string]string)
+ traceAttchment := make(map[string]string)
for k, v := range attachments {
if r, ok := v.(string); ok {
traceAttchment[k] = r
diff --git a/remoting/getty/pool.go b/remoting/getty/pool.go
index 2b1cdfe..7e8cb13 100644
--- a/remoting/getty/pool.go
+++ b/remoting/getty/pool.go
@@ -39,7 +39,7 @@
type gettyRPCClient struct {
once sync.Once
- //protocol string
+ // protocol string
addr string
active int64 // zero, not create or be destroyed
@@ -50,9 +50,7 @@
sessions []*rpcSession
}
-var (
- errClientPoolClosed = perrors.New("client pool closed")
-)
+var errClientPoolClosed = perrors.New("client pool closed")
func newGettyRPCClientConn(pool *gettyRPCClientPool, addr string) (*gettyRPCClient, error) {
var (
@@ -384,7 +382,7 @@
conn = p.conns[0]
}
// This will recreate gettyRpcClient for remove last position
- //p.conns = p.conns[:len(p.conns)-1]
+ // p.conns = p.conns[:len(p.conns)-1]
if d := now - conn.getActive(); d > p.ttl {
p.remove(conn)
@@ -392,7 +390,7 @@
num = len(p.conns)
continue
}
- conn.updateActive(now) //update active time
+ conn.updateActive(now) // update active time
return conn, nil
}
return nil, nil
diff --git a/remoting/getty/readwriter.go b/remoting/getty/readwriter.go
index 61062df..c04437a 100644
--- a/remoting/getty/readwriter.go
+++ b/remoting/getty/readwriter.go
@@ -51,7 +51,7 @@
// and send to client each time. the Read can assemble it.
func (p *RpcClientPackageHandler) Read(ss getty.Session, data []byte) (interface{}, int, error) {
resp, length, err := (p.client.codec).Decode(data)
- //err := pkg.Unmarshal(buf, p.client)
+ // err := pkg.Unmarshal(buf, p.client)
if err != nil {
if errors.Is(err, hessian.ErrHeaderNotEnough) || errors.Is(err, hessian.ErrBodyNotEnough) {
return nil, 0, nil
@@ -112,7 +112,7 @@
// and send to client each time. the Read can assemble it.
func (p *RpcServerPackageHandler) Read(ss getty.Session, data []byte) (interface{}, int, error) {
req, length, err := (p.server.codec).Decode(data)
- //resp,len, err := (*p.).DecodeResponse(buf)
+ // resp,len, err := (*p.).DecodeResponse(buf)
if err != nil {
if errors.Is(err, hessian.ErrHeaderNotEnough) || errors.Is(err, hessian.ErrBodyNotEnough) {
return nil, 0, nil
@@ -150,5 +150,4 @@
logger.Errorf("illegal pkg:%+v\n, it is %+v", pkg, reflect.TypeOf(pkg))
return nil, perrors.New("invalid rpc response")
-
}
diff --git a/remoting/getty/readwriter_test.go b/remoting/getty/readwriter_test.go
index c54c385..db6dd8e 100644
--- a/remoting/getty/readwriter_test.go
+++ b/remoting/getty/readwriter_test.go
@@ -125,7 +125,8 @@
WaitTimeout: "1s",
MaxMsgLen: 10240000000,
SessionName: "server",
- }})
+ },
+ })
assert.NoError(t, srvConf.CheckValidity())
url, err := common.NewURL("dubbo://127.0.0.1:20061/com.ikurento.user.AdminProvider?anyhost=true&" +
@@ -142,7 +143,7 @@
BaseInvoker: *protocol.NewBaseInvoker(url),
}
handler := func(invocation *invocation.RPCInvocation) protocol.RPCResult {
- //result := protocol.RPCResult{}
+ // result := protocol.RPCResult{}
r := invoker.Invoke(context.Background(), invocation)
result := protocol.RPCResult{
Err: r.Error(),
@@ -159,8 +160,7 @@
return server, url
}
-type AdminProvider struct {
-}
+type AdminProvider struct{}
func (a *AdminProvider) GetAdmin(ctx context.Context, req []interface{}, rsp *User) error {
rsp.Id = req[0].(string)
diff --git a/remoting/kubernetes/client.go b/remoting/kubernetes/client.go
index ce6bccc..aabbc00 100644
--- a/remoting/kubernetes/client.go
+++ b/remoting/kubernetes/client.go
@@ -76,7 +76,6 @@
// Create creates k/v pair in watcher-set
func (c *Client) Create(k, v string) error {
-
// the read current pod must be lock, protect every
// create operation can be atomic
c.lock.Lock()
@@ -92,7 +91,6 @@
// GetChildren gets k children list from kubernetes-watcherSet
func (c *Client) GetChildren(k string) ([]string, []string, error) {
-
objectList, err := c.controller.watcherSet.Get(k, true)
if err != nil {
return nil, nil, perrors.WithMessagef(err, "get children from watcherSet on (%s)", k)
@@ -111,7 +109,6 @@
// Watch watches on spec key
func (c *Client) Watch(k string) (<-chan *WatcherEvent, <-chan struct{}, error) {
-
w, err := c.controller.watcherSet.Watch(k, false)
if err != nil {
return nil, nil, perrors.WithMessagef(err, "watch on (%s)", k)
@@ -122,7 +119,6 @@
// WatchWithPrefix watches on spec prefix
func (c *Client) WatchWithPrefix(prefix string) (<-chan *WatcherEvent, <-chan struct{}, error) {
-
w, err := c.controller.watcherSet.Watch(prefix, true)
if err != nil {
return nil, nil, perrors.WithMessagef(err, "watch on prefix (%s)", prefix)
@@ -133,7 +129,6 @@
// if returns false, the client is die
func (c *Client) Valid() bool {
-
select {
case <-c.Done():
return false
@@ -151,10 +146,9 @@
// nolint
func (c *Client) Close() {
-
select {
case <-c.ctx.Done():
- //already stopped
+ // already stopped
return
default:
}
@@ -167,7 +161,6 @@
// ValidateClient validates the kubernetes client
func ValidateClient(container clientFacade) error {
-
client := container.Client()
// new Client
diff --git a/remoting/kubernetes/client_test.go b/remoting/kubernetes/client_test.go
index 9cc4212..be72561 100644
--- a/remoting/kubernetes/client_test.go
+++ b/remoting/kubernetes/client_test.go
@@ -59,9 +59,8 @@
// test dataset prefix
const prefix = "name"
-var (
- watcherStopLog = "the watcherSet watcher was stopped"
-)
+var watcherStopLog = "the watcherSet watcher was stopped"
+
var clientPodListJsonData = `{
"apiVersion": "v1",
"items": [
@@ -228,7 +227,6 @@
`
func getTestClient(t *testing.T) *Client {
-
pl := &v1.PodList{}
// 1. install test data
if err := json.Unmarshal([]byte(clientPodListJsonData), &pl); err != nil {
@@ -257,7 +255,6 @@
}
func TestClientValid(t *testing.T) {
-
client := getTestClient(t)
defer client.Close()
@@ -272,7 +269,6 @@
}
func TestClientDone(t *testing.T) {
-
client := getTestClient(t)
go func() {
@@ -287,7 +283,6 @@
}
func TestClientCreateKV(t *testing.T) {
-
client := getTestClient(t)
defer client.Close()
@@ -304,7 +299,6 @@
}
func TestClientGetChildrenKVList(t *testing.T) {
-
client := getTestClient(t)
defer client.Close()
@@ -314,7 +308,6 @@
syncDataComplete := make(chan struct{})
go func() {
-
wc, done, err := client.WatchWithPrefix(prefix)
if err != nil {
t.Error(err)
@@ -374,23 +367,19 @@
}
for expectK, expectV := range expect {
-
if got[expectK] != expectV {
t.Fatalf("expect {%s: %s} but got {%s: %v}", expectK, expectV, expectK, got[expectK])
}
}
-
}
func TestClientWatchPrefix(t *testing.T) {
-
client := getTestClient(t)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
-
wc, done, err := client.WatchWithPrefix(prefix)
if err != nil {
t.Error(err)
@@ -426,14 +415,12 @@
}
func TestClientWatch(t *testing.T) {
-
client := getTestClient(t)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
-
wc, done, err := client.Watch(prefix)
if err != nil {
t.Error(err)
@@ -449,7 +436,6 @@
return
}
}
-
}()
// must wait the watch goroutine already start the watch goroutine
diff --git a/remoting/kubernetes/facade_test.go b/remoting/kubernetes/facade_test.go
index a6c6c02..d0d710c 100644
--- a/remoting/kubernetes/facade_test.go
+++ b/remoting/kubernetes/facade_test.go
@@ -30,8 +30,8 @@
type mockFacade struct {
*common.URL
client *Client
- //cltLock sync.Mutex
- //done chan struct{}
+ // cltLock sync.Mutex
+ // done chan struct{}
}
func (r *mockFacade) Client() *Client {
@@ -57,8 +57,8 @@
func (r *mockFacade) IsAvailable() bool {
return true
}
-func Test_Facade(t *testing.T) {
+func Test_Facade(t *testing.T) {
regUrl, err := common.NewURL("registry://127.0.0.1:443",
common.WithParamsValue(constant.ROLE_KEY, strconv.Itoa(common.CONSUMER)))
if err != nil {
diff --git a/remoting/kubernetes/listener.go b/remoting/kubernetes/listener.go
index a737f4e..2c4149b 100644
--- a/remoting/kubernetes/listener.go
+++ b/remoting/kubernetes/listener.go
@@ -86,7 +86,6 @@
// return true means the event type is DELETE
// return false means the event type is CREATE || UPDATE
func (l *EventListener) handleEvents(event *WatcherEvent, listeners ...remoting.DataListener) bool {
-
logger.Infof("got a kubernetes-watcherSet event {type: %d, key: %s}", event.EventType, event.Key)
switch event.EventType {
@@ -120,7 +119,6 @@
// Listen on a set of key with spec prefix
func (l *EventListener) ListenServiceNodeEventWithPrefix(prefix string, listener ...remoting.DataListener) {
-
defer l.wg.Done()
for {
wc, done, err := l.client.WatchWithPrefix(prefix)
@@ -157,7 +155,6 @@
// |
// --------> ListenServiceNodeEvent
func (l *EventListener) ListenServiceEvent(key string, listener remoting.DataListener) {
-
l.keyMapLock.RLock()
_, ok := l.keyMap[key]
l.keyMapLock.RUnlock()
diff --git a/remoting/kubernetes/listener_test.go b/remoting/kubernetes/listener_test.go
index 0b05b6e..4701b5d 100644
--- a/remoting/kubernetes/listener_test.go
+++ b/remoting/kubernetes/listener_test.go
@@ -69,8 +69,7 @@
}
func TestListener(t *testing.T) {
-
- var tests = []struct {
+ tests := []struct {
input struct {
k string
v string
diff --git a/remoting/kubernetes/registry_controller.go b/remoting/kubernetes/registry_controller.go
index f66163d..212549a 100644
--- a/remoting/kubernetes/registry_controller.go
+++ b/remoting/kubernetes/registry_controller.go
@@ -68,9 +68,7 @@
defaultResync = 5 * time.Minute
)
-var (
- ErrDubboLabelAlreadyExist = perrors.New("dubbo label already exist")
-)
+var ErrDubboLabelAlreadyExist = perrors.New("dubbo label already exist")
// dubboRegistryController works like a kubernetes controller
type dubboRegistryController struct {
@@ -96,7 +94,7 @@
listAndWatchStartResourceVersion uint64
namespacedInformerFactory map[string]informers.SharedInformerFactory
namespacedPodInformers map[string]informerscorev1.PodInformer
- queue workqueue.Interface //shared by namespaced informers
+ queue workqueue.Interface // shared by namespaced informers
}
func newDubboRegistryController(
@@ -146,7 +144,6 @@
// GetInClusterKubernetesClient
// current pod running in kubernetes-cluster
func GetInClusterKubernetesClient() (kubernetes.Interface, error) {
-
// read in-cluster config
cfg, err := rest.InClusterConfig()
if err != nil {
@@ -161,7 +158,6 @@
// 2. put every element to watcherSet
// 3. refresh watch book-mark
func (c *dubboRegistryController) initWatchSet() error {
-
req, err := labels.NewRequirement(DubboIOLabelKey, selection.In, []string{DubboIOConsumerLabelValue, DubboIOProviderLabelValue})
if err != nil {
return perrors.WithMessage(err, "new requirement")
@@ -193,7 +189,6 @@
// 1. current pod name
// 2. current pod working namespace
func (c *dubboRegistryController) readConfig() error {
-
// read current pod name && namespace
c.name = os.Getenv(podNameKey)
if len(c.name) == 0 {
@@ -207,7 +202,6 @@
}
func (c *dubboRegistryController) initNamespacedPodInformer(ns string) error {
-
req, err := labels.NewRequirement(DubboIOLabelKey, selection.In, []string{DubboIOConsumerLabelValue, DubboIOProviderLabelValue})
if err != nil {
return perrors.WithMessage(err, "new requirement")
@@ -237,7 +231,6 @@
}
func (c *dubboRegistryController) initPodInformer() error {
-
if c.role == common.PROVIDER {
return nil
}
@@ -323,7 +316,6 @@
// run
// controller process every event in work-queue
func (c *dubboRegistryController) run() {
-
if c.role == common.PROVIDER {
return
}
@@ -402,7 +394,6 @@
// unmarshalRecord unmarshals the kubernetes dubbo annotation value
func (c *dubboRegistryController) unmarshalRecord(record string) ([]*WatcherEvent, error) {
-
if len(record) == 0 {
// []*WatcherEvent is nil.
return nil, nil
@@ -497,7 +488,6 @@
// assembleDUBBOAnnotations assembles the dubbo kubernetes annotations
// accord the current pod && (k,v) assemble the old-pod, new-pod
func (c *dubboRegistryController) assembleDUBBOAnnotations(k, v string, currentPod *v1.Pod) (oldPod *v1.Pod, newPod *v1.Pod, err error) {
-
oldPod = &v1.Pod{}
newPod = &v1.Pod{}
oldPod.Annotations = make(map[string]string, 8)
@@ -563,7 +553,6 @@
// addAnnotationForCurrentPod adds annotation for current pod
func (c *dubboRegistryController) addAnnotationForCurrentPod(k string, v string) error {
-
c.lock.Lock()
defer c.lock.Unlock()
diff --git a/remoting/kubernetes/watch.go b/remoting/kubernetes/watch.go
index 7bb5ef1..34f5a34 100644
--- a/remoting/kubernetes/watch.go
+++ b/remoting/kubernetes/watch.go
@@ -46,7 +46,6 @@
)
func (e eventType) String() string {
-
switch e {
case Create:
return "CREATE"
@@ -143,9 +142,7 @@
// Put puts the watch event to watcher-set
func (s *watcherSetImpl) Put(watcherEvent *WatcherEvent) error {
-
blockSendMsg := func(object *WatcherEvent, w *watcher) {
-
select {
case <-w.done():
// the watcher already stop
@@ -212,7 +209,6 @@
// addWatcher
func (s *watcherSetImpl) addWatcher(key string, prefix bool) (Watcher, error) {
-
if err := s.valid(); err != nil {
return nil, err
}
@@ -239,7 +235,6 @@
// Get gets elements from watcher-set
func (s *watcherSetImpl) Get(key string, prefix bool) ([]*WatcherEvent, error) {
-
s.lock.RLock()
defer s.lock.RUnlock()
@@ -302,7 +297,6 @@
// nolint
func (w *watcher) stop() {
-
// double close will panic
w.closeOnce.Do(func() {
close(w.exit)
diff --git a/remoting/kubernetes/watch_test.go b/remoting/kubernetes/watch_test.go
index efefcc5..9a0139d 100644
--- a/remoting/kubernetes/watch_test.go
+++ b/remoting/kubernetes/watch_test.go
@@ -26,7 +26,6 @@
)
func TestWatchSet(t *testing.T) {
-
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
@@ -61,7 +60,6 @@
wg.Add(1)
go func() {
-
defer wg.Done()
w, err := s.Watch("key", true)
if err != nil {
diff --git a/remoting/listener.go b/remoting/listener.go
index eb27c71..a87e502 100644
--- a/remoting/listener.go
+++ b/remoting/listener.go
@@ -23,7 +23,7 @@
// DataListener defines common data listener interface
type DataListener interface {
- DataChange(eventType Event) bool //bool is return for interface implement is interesting
+ DataChange(eventType Event) bool // bool is return for interface implement is interesting
}
//////////////////////////////////////////
diff --git a/remoting/zookeeper/curator_discovery/service_discovery.go b/remoting/zookeeper/curator_discovery/service_discovery.go
index ebe784c..9c7488b 100644
--- a/remoting/zookeeper/curator_discovery/service_discovery.go
+++ b/remoting/zookeeper/curator_discovery/service_discovery.go
@@ -120,7 +120,6 @@
return perrors.New("[ServiceDiscovery] services value not entry")
}
data, err := json.Marshal(instance)
-
if err != nil {
return err
}
diff --git a/remoting/zookeeper/facade.go b/remoting/zookeeper/facade.go
index aeaa317..3bc7995 100644
--- a/remoting/zookeeper/facade.go
+++ b/remoting/zookeeper/facade.go
@@ -21,9 +21,11 @@
"sync"
"time"
)
+
import (
gxzookeeper "github.com/dubbogo/gost/database/kv/zk"
)
+
import (
"github.com/apache/dubbo-go/common"
"github.com/apache/dubbo-go/common/logger"
diff --git a/remoting/zookeeper/listener.go b/remoting/zookeeper/listener.go
index c24a4fc..5440127 100644
--- a/remoting/zookeeper/listener.go
+++ b/remoting/zookeeper/listener.go
@@ -38,9 +38,7 @@
"github.com/apache/dubbo-go/remoting"
)
-var (
- defaultTTL = 15 * time.Minute
-)
+var defaultTTL = 15 * time.Minute
// nolint
type ZkEventListener struct {
diff --git a/remoting/zookeeper/listener_test.go b/remoting/zookeeper/listener_test.go
index 1278665..67abd23 100644
--- a/remoting/zookeeper/listener_test.go
+++ b/remoting/zookeeper/listener_test.go
@@ -35,9 +35,7 @@
"github.com/apache/dubbo-go/remoting"
)
-var (
- dubboPropertiesPath = "/dubbo/dubbo.properties"
-)
+var dubboPropertiesPath = "/dubbo/dubbo.properties"
func initZkData(t *testing.T) (*zk.TestCluster, *gxzookeeper.ZookeeperClient, <-chan zk.Event) {
ts, client, event, err := gxzookeeper.NewMockZookeeperClient("test", 15*time.Second)
diff --git a/test/integrate/dubbo/go-client/client.go b/test/integrate/dubbo/go-client/client.go
index 4c62674..afe965e 100644
--- a/test/integrate/dubbo/go-client/client.go
+++ b/test/integrate/dubbo/go-client/client.go
@@ -37,9 +37,7 @@
_ "github.com/apache/dubbo-go/registry/zookeeper"
)
-var (
- survivalTimeout int = 10e9
-)
+var survivalTimeout int = 10e9
func println(format string, args ...interface{}) {
fmt.Printf("\033[32;40m"+format+"\033[0m\n", args...)
diff --git a/test/integrate/dubbo/go-client/version.go b/test/integrate/dubbo/go-client/version.go
index c613858..9297464 100644
--- a/test/integrate/dubbo/go-client/version.go
+++ b/test/integrate/dubbo/go-client/version.go
@@ -17,6 +17,4 @@
package main
-var (
- Version = "2.6.0"
-)
+var Version = "2.6.0"
diff --git a/test/integrate/dubbo/go-server/server.go b/test/integrate/dubbo/go-server/server.go
index a5d18db..0a38819 100644
--- a/test/integrate/dubbo/go-server/server.go
+++ b/test/integrate/dubbo/go-server/server.go
@@ -33,15 +33,12 @@
_ "github.com/apache/dubbo-go/registry/zookeeper"
)
-var (
- stopC = make(chan struct{})
-)
+var stopC = make(chan struct{})
// they are necessary:
// export CONF_PROVIDER_FILE_PATH="xxx"
// export APP_LOG_CONF_FILE="xxx"
func main() {
-
hessian.RegisterPOJO(&User{})
config.Load()
diff --git a/test/integrate/dubbo/go-server/user.go b/test/integrate/dubbo/go-server/user.go
index 7bff415..aace76c 100644
--- a/test/integrate/dubbo/go-server/user.go
+++ b/test/integrate/dubbo/go-server/user.go
@@ -41,8 +41,7 @@
Time time.Time
}
-type UserProvider struct {
-}
+type UserProvider struct{}
func (u *UserProvider) GetUser(ctx context.Context, req []interface{}) (*User, error) {
println("req:%#v", req)
diff --git a/test/integrate/dubbo/go-server/version.go b/test/integrate/dubbo/go-server/version.go
index c613858..9297464 100644
--- a/test/integrate/dubbo/go-server/version.go
+++ b/test/integrate/dubbo/go-server/version.go
@@ -17,6 +17,4 @@
package main
-var (
- Version = "2.6.0"
-)
+var Version = "2.6.0"
diff --git a/tools/cli/client/client.go b/tools/cli/client/client.go
index fd15939..b6ab019 100644
--- a/tools/cli/client/client.go
+++ b/tools/cli/client/client.go
@@ -68,7 +68,7 @@
return &TelnetClient{
tcpAddr: tcpAddr,
conn: conn,
- responseTimeout: time.Duration(timeout) * time.Millisecond, //default timeout
+ responseTimeout: time.Duration(timeout) * time.Millisecond, // default timeout
protocolName: protocolName,
pendingResponses: &sync.Map{},
proto: proto,
@@ -95,7 +95,7 @@
// ProcessRequests send all requests
func (t *TelnetClient) ProcessRequests(userPkg interface{}) {
- for i, _ := range t.requestList {
+ for i := range t.requestList {
t.processSingleRequest(t.requestList[i], userPkg)
}
}
diff --git a/tools/cli/common/protocol.go b/tools/cli/common/protocol.go
index dd2454a..d54d553 100644
--- a/tools/cli/common/protocol.go
+++ b/tools/cli/common/protocol.go
@@ -21,9 +21,7 @@
"github.com/apache/dubbo-go/tools/cli/protocol"
)
-var (
- protocols = make(map[string]func() protocol.Protocol, 8)
-)
+var protocols = make(map[string]func() protocol.Protocol, 8)
// SetProtocol sets the protocol extension with @name
func SetProtocol(name string, v func() protocol.Protocol) {
diff --git a/tools/cli/example/server/main.go b/tools/cli/example/server/main.go
index ed1ed52..00ea543 100644
--- a/tools/cli/example/server/main.go
+++ b/tools/cli/example/server/main.go
@@ -38,9 +38,7 @@
_ "github.com/apache/dubbo-go/registry/protocol"
)
-var (
- survivalTimeout = int(3e9)
-)
+var survivalTimeout = int(3e9)
// they are necessary:
// export CONF_PROVIDER_FILE_PATH="xxx"
diff --git a/tools/cli/example/server/user.go b/tools/cli/example/server/user.go
index 5835848..0bb25b5 100644
--- a/tools/cli/example/server/user.go
+++ b/tools/cli/example/server/user.go
@@ -34,8 +34,7 @@
hessian.RegisterPOJO(&CallUserStruct{})
}
-type UserProvider struct {
-}
+type UserProvider struct{}
func (u *UserProvider) GetUser(ctx context.Context, userStruct *CallUserStruct) (*User, error) {
fmt.Printf("=======================\nreq:%#v\n", userStruct)
diff --git a/tools/cli/main.go b/tools/cli/main.go
index 1f90f67..43ed374 100644
--- a/tools/cli/main.go
+++ b/tools/cli/main.go
@@ -27,16 +27,18 @@
"github.com/apache/dubbo-go/tools/cli/json_register"
)
-var host string
-var port int
-var protocolName string
-var InterfaceID string
-var version string
-var group string
-var method string
-var sendObjFilePath string
-var recvObjFilePath string
-var timeout int
+var (
+ host string
+ port int
+ protocolName string
+ InterfaceID string
+ version string
+ group string
+ method string
+ sendObjFilePath string
+ recvObjFilePath string
+ timeout int
+)
func init() {
flag.StringVar(&host, "h", "localhost", "target server host")
diff --git a/tools/cli/protocol/dubbo/codec.go b/tools/cli/protocol/dubbo/codec.go
index f73bf8e..ba5e6b4 100644
--- a/tools/cli/protocol/dubbo/codec.go
+++ b/tools/cli/protocol/dubbo/codec.go
@@ -33,7 +33,7 @@
hessian "github.com/apache/dubbo-go-hessian2"
)
-//SerialID serial ID
+// SerialID serial ID
type SerialID byte
const (
@@ -41,7 +41,7 @@
S_Dubbo SerialID = 2
)
-//CallType call type
+// CallType call type
type CallType int32
const (
diff --git a/tools/cli/protocol/dubbo/dubbo_protocol.go b/tools/cli/protocol/dubbo/dubbo_protocol.go
index 97a3ac7..f16f838 100644
--- a/tools/cli/protocol/dubbo/dubbo_protocol.go
+++ b/tools/cli/protocol/dubbo/dubbo_protocol.go
@@ -39,8 +39,7 @@
}
// RpcClientPackageHandler handle package for client in getty.
-type RpcClientPackageHandler struct {
-}
+type RpcClientPackageHandler struct{}
func NewRpcClientPackageHandler() protocol.Protocol {
return RpcClientPackageHandler{}