Merge pull request #1016 from unistack-org/lint

lint fixes mostly for prealloc also remove deadcode from grpc client
This commit is contained in:
Asim Aslam 2019-12-05 08:33:52 +00:00 committed by GitHub
commit b0626089f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
41 changed files with 76 additions and 80 deletions

View File

@ -8,7 +8,7 @@ import (
"github.com/forestgiant/sliceutil" "github.com/forestgiant/sliceutil"
"github.com/micro/go-micro/agent/input" "github.com/micro/go-micro/agent/input"
"github.com/micro/go-micro/util/log" "github.com/micro/go-micro/util/log"
"gopkg.in/telegram-bot-api.v4" tgbotapi "gopkg.in/telegram-bot-api.v4"
) )
type telegramConn struct { type telegramConn struct {

View File

@ -7,7 +7,7 @@ import (
"github.com/micro/cli" "github.com/micro/cli"
"github.com/micro/go-micro/agent/input" "github.com/micro/go-micro/agent/input"
"gopkg.in/telegram-bot-api.v4" tgbotapi "gopkg.in/telegram-bot-api.v4"
) )
type telegramInput struct { type telegramInput struct {

View File

@ -32,7 +32,7 @@ import (
"unicode" "unicode"
"github.com/google/uuid" "github.com/google/uuid"
"gopkg.in/go-playground/validator.v9" validator "gopkg.in/go-playground/validator.v9"
) )
const ( const (

View File

@ -7,7 +7,7 @@ import (
"testing" "testing"
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
"github.com/micro/go-micro/api/proto" go_api "github.com/micro/go-micro/api/proto"
) )
func TestRequestPayloadFromRequest(t *testing.T) { func TestRequestPayloadFromRequest(t *testing.T) {

View File

@ -81,8 +81,7 @@ func (s *storage) Delete(key string) error {
} }
func (s *storage) Exists(key string) bool { func (s *storage) Exists(key string) bool {
_, err := s.store.Read(key) if _, err := s.store.Read(key); err != nil {
if err != nil {
return false return false
} }
return true return true
@ -93,6 +92,8 @@ func (s *storage) List(prefix string, recursive bool) ([]string, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
//nolint:prealloc
var results []string var results []string
for _, r := range records { for _, r := range records {
if strings.HasPrefix(r.Key, prefix) { if strings.HasPrefix(r.Key, prefix) {

View File

@ -237,6 +237,7 @@ func (h *httpBroker) unsubscribe(s *httpSubscriber) error {
h.Lock() h.Lock()
defer h.Unlock() defer h.Unlock()
//nolint:prealloc
var subscribers []*httpSubscriber var subscribers []*httpSubscriber
// look for subscriber // look for subscriber
@ -325,6 +326,7 @@ func (h *httpBroker) ServeHTTP(w http.ResponseWriter, req *http.Request) {
p := &httpEvent{m: m, t: topic} p := &httpEvent{m: m, t: topic}
id := req.Form.Get("id") id := req.Form.Get("id")
//nolint:prealloc
var subs []Handler var subs []Handler
h.RLock() h.RLock()

View File

@ -70,6 +70,7 @@ func (n *natsBroker) Address() string {
} }
func setAddrs(addrs []string) []string { func setAddrs(addrs []string) []string {
//nolint:prealloc
var cAddrs []string var cAddrs []string
for _, addr := range addrs { for _, addr := range addrs {
if len(addr) == 0 { if len(addr) == 0 {

View File

@ -94,6 +94,5 @@ func TestInitAddrs(t *testing.T) {
} }
} }
}) })
} }
} }

View File

@ -11,8 +11,6 @@ import (
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"
"github.com/micro/go-micro/codec" "github.com/micro/go-micro/codec"
"github.com/micro/go-micro/codec/bytes" "github.com/micro/go-micro/codec/bytes"
"github.com/micro/go-micro/codec/jsonrpc"
"github.com/micro/go-micro/codec/protorpc"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/encoding" "google.golang.org/grpc/encoding"
) )
@ -36,14 +34,6 @@ var (
"application/grpc+bytes": bytesCodec{}, "application/grpc+bytes": bytesCodec{},
} }
defaultRPCCodecs = map[string]codec.NewCodec{
"application/json": jsonrpc.NewCodec,
"application/json-rpc": jsonrpc.NewCodec,
"application/protobuf": protorpc.NewCodec,
"application/proto-rpc": protorpc.NewCodec,
"application/octet-stream": protorpc.NewCodec,
}
json = jsoniter.ConfigCompatibleWithStandardLibrary json = jsoniter.ConfigCompatibleWithStandardLibrary
) )

View File

@ -282,16 +282,6 @@ func (g *grpcClient) newGRPCCodec(contentType string) (encoding.Codec, error) {
return nil, fmt.Errorf("Unsupported Content-Type: %s", contentType) return nil, fmt.Errorf("Unsupported Content-Type: %s", contentType)
} }
func (g *grpcClient) newCodec(contentType string) (codec.NewCodec, error) {
if c, ok := g.opts.Codecs[contentType]; ok {
return c, nil
}
if cf, ok := defaultRPCCodecs[contentType]; ok {
return cf, nil
}
return nil, fmt.Errorf("Unsupported Content-Type: %s", contentType)
}
func (g *grpcClient) Init(opts ...client.Option) error { func (g *grpcClient) Init(opts ...client.Option) error {
size := g.opts.PoolSize size := g.opts.PoolSize
ttl := g.opts.PoolTTL ttl := g.opts.PoolTTL

View File

@ -1,11 +1,11 @@
package grpc package grpc
import ( import (
"context"
"net" "net"
"testing" "testing"
"time" "time"
"context"
"google.golang.org/grpc" "google.golang.org/grpc"
pgrpc "google.golang.org/grpc" pgrpc "google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld" pb "google.golang.org/grpc/examples/helloworld/helloworld"

View File

@ -63,7 +63,7 @@ func (d *dnsSelector) Select(service string, opts ...selector.SelectOption) (sel
} }
} }
var nodes []*registry.Node nodes := make([]*registry.Node, 0, len(srv))
for _, node := range srv { for _, node := range srv {
nodes = append(nodes, &registry.Node{ nodes = append(nodes, &registry.Node{
Id: node.Target, Id: node.Target,
@ -99,13 +99,9 @@ func (d *dnsSelector) Select(service string, opts ...selector.SelectOption) (sel
return sopts.Strategy(services), nil return sopts.Strategy(services), nil
} }
func (d *dnsSelector) Mark(service string, node *registry.Node, err error) { func (d *dnsSelector) Mark(service string, node *registry.Node, err error) {}
return
}
func (d *dnsSelector) Reset(service string) { func (d *dnsSelector) Reset(service string) {}
return
}
func (d *dnsSelector) Close() error { func (d *dnsSelector) Close() error {
return nil return nil

View File

@ -176,12 +176,10 @@ func (r *routerSelector) Select(service string, opts ...selector.SelectOption) (
func (r *routerSelector) Mark(service string, node *registry.Node, err error) { func (r *routerSelector) Mark(service string, node *registry.Node, err error) {
// TODO: pass back metrics or information to the router // TODO: pass back metrics or information to the router
return
} }
func (r *routerSelector) Reset(service string) { func (r *routerSelector) Reset(service string) {
// TODO: reset the metrics or information at the router // TODO: reset the metrics or information at the router
return
} }
func (r *routerSelector) Close() error { func (r *routerSelector) Close() error {

View File

@ -3,6 +3,7 @@ package selector
import ( import (
"errors" "errors"
"github.com/micro/go-micro/registry" "github.com/micro/go-micro/registry"
) )

View File

@ -32,7 +32,7 @@ func Random(services []*registry.Service) Next {
// RoundRobin is a roundrobin strategy algorithm for node selection // RoundRobin is a roundrobin strategy algorithm for node selection
func RoundRobin(services []*registry.Service) Next { func RoundRobin(services []*registry.Service) Next {
var nodes []*registry.Node nodes := make([]*registry.Node, 0, len(services))
for _, service := range services { for _, service := range services {
nodes = append(nodes, service.Nodes...) nodes = append(nodes, service.Nodes...)

View File

@ -193,6 +193,7 @@ func (m *memory) Snapshot() (*loader.Snapshot, error) {
// Sync loads all the sources, calls the parser and updates the config // Sync loads all the sources, calls the parser and updates the config
func (m *memory) Sync() error { func (m *memory) Sync() error {
//nolint:prealloc
var sets []*source.ChangeSet var sets []*source.ChangeSet
m.Lock() m.Lock()

View File

@ -2,6 +2,7 @@
package options package options
import ( import (
"log"
"sync" "sync"
) )
@ -68,6 +69,8 @@ func WithString(s string) Option {
// NewOptions returns a new initialiser // NewOptions returns a new initialiser
func NewOptions(opts ...Option) Options { func NewOptions(opts ...Option) Options {
o := new(defaultOptions) o := new(defaultOptions)
o.Init(opts...) if err := o.Init(opts...); err != nil {
log.Fatal(err)
}
return o return o
} }

View File

@ -35,6 +35,7 @@ func WithPrefix(p ...string) source.Option {
} }
func appendUnderscore(prefixes []string) []string { func appendUnderscore(prefixes []string) []string {
//nolint:prealloc
var result []string var result []string
for _, p := range prefixes { for _, p := range prefixes {
if !strings.HasSuffix(p, "_") { if !strings.HasSuffix(p, "_") {

View File

@ -195,6 +195,7 @@ func (n *network) resolveNodes() ([]string, error) {
nodeMap := make(map[string]bool) nodeMap := make(map[string]bool)
// collect network node addresses // collect network node addresses
//nolint:prealloc
var nodes []string var nodes []string
var i int var i int

View File

@ -38,6 +38,7 @@ func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) {
return nil, err return nil, err
} }
//nolint:prealloc
var records []*resolver.Record var records []*resolver.Record
for _, answer := range rec.Answer { for _, answer := range rec.Answer {

View File

@ -17,7 +17,7 @@ func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
var records []*resolver.Record records := make([]*resolver.Record, len(addrs))
for _, addr := range addrs { for _, addr := range addrs {
address := addr.Target address := addr.Target
if addr.Port > 0 { if addr.Port > 0 {

View File

@ -29,10 +29,11 @@ func flatten(n network.Node, visited map[string]bool) []network.Node {
} }
// create new list of nodes // create new list of nodes
//nolint:prealloc
var nodes []network.Node var nodes []network.Node
// check if already visited // check if already visited
if visited[n.Id()] == false { if !visited[n.Id()] {
// append the current node // append the current node
nodes = append(nodes, n) nodes = append(nodes, n)
} }

View File

@ -83,7 +83,7 @@ func readLoop(r server.Request, s client.Stream) error {
// toNodes returns a list of node addresses from given routes // toNodes returns a list of node addresses from given routes
func toNodes(routes []router.Route) []string { func toNodes(routes []router.Route) []string {
var nodes []string nodes := make([]string, len(routes))
for _, node := range routes { for _, node := range routes {
address := node.Address address := node.Address
if len(node.Gateway) > 0 { if len(node.Gateway) > 0 {
@ -112,6 +112,7 @@ func (p *Proxy) filterRoutes(ctx context.Context, routes []router.Route) []route
return routes return routes
} }
//nolint:prealloc
var filteredRoutes []router.Route var filteredRoutes []router.Route
// filter the routes based on our headers // filter the routes based on our headers
@ -361,6 +362,7 @@ func (p *Proxy) ServeRequest(ctx context.Context, req server.Request, rsp server
routes = addr routes = addr
} }
//nolint:prealloc
var opts []client.CallOption var opts []client.CallOption
// set strategy to round robin // set strategy to round robin

View File

@ -335,9 +335,7 @@ func (e *etcdRegistry) GetService(name string) ([]*registry.Service, error) {
serviceMap[s.Version] = s serviceMap[s.Version] = s
} }
for _, node := range sn.Nodes { s.Nodes = append(s.Nodes, sn.Nodes...)
s.Nodes = append(s.Nodes, node)
}
} }
} }

View File

@ -13,10 +13,8 @@ type memoryWatcher struct {
func (m *memoryWatcher) Next() (*registry.Result, error) { func (m *memoryWatcher) Next() (*registry.Result, error) {
// not implement so we just block until exit // not implement so we just block until exit
select { <-m.exit
case <-m.exit:
return nil, errors.New("watcher stopped") return nil, errors.New("watcher stopped")
}
} }
func (m *memoryWatcher) Stop() { func (m *memoryWatcher) Stop() {

View File

@ -44,9 +44,13 @@ func recordToService(r *record) *registry.Service {
endpoints := make([]*registry.Endpoint, len(r.Endpoints)) endpoints := make([]*registry.Endpoint, len(r.Endpoints))
for i, e := range r.Endpoints { for i, e := range r.Endpoints {
request := new(registry.Value) request := new(registry.Value)
request = e.Request if e.Request != nil {
*request = *e.Request
}
response := new(registry.Value) response := new(registry.Value)
response = e.Response if e.Response != nil {
*response = *e.Response
}
metadata := make(map[string]string) metadata := make(map[string]string)
for k, v := range e.Metadata { for k, v := range e.Metadata {

View File

@ -127,6 +127,8 @@ func TestQuery(t *testing.T) {
routes, err := table.Query() routes, err := table.Query()
if err != nil { if err != nil {
t.Errorf("error looking up routes: %s", err) t.Errorf("error looking up routes: %s", err)
} else if len(routes) == 0 {
t.Errorf("error looking up routes: not found")
} }
// query routes particular network // query routes particular network

View File

@ -195,6 +195,7 @@ func (r *runtime) Read(opts ...ReadOption) ([]*Service, error) {
return k == v return k == v
} }
//nolint:prealloc
var services []*Service var services []*Service
for _, service := range r.services { for _, service := range r.services {
@ -258,10 +259,11 @@ func (r *runtime) Delete(s *Service) error {
// List returns a slice of all services tracked by the runtime // List returns a slice of all services tracked by the runtime
func (r *runtime) List() ([]*Service, error) { func (r *runtime) List() ([]*Service, error) {
var services []*Service
r.RLock() r.RLock()
defer r.RUnlock() defer r.RUnlock()
services := make([]*Service, 0, len(r.services))
for _, service := range r.services { for _, service := range r.services {
services = append(services, service.Service) services = append(services, service.Service)
} }

View File

@ -7,7 +7,7 @@ import (
"strings" "strings"
"github.com/micro/go-micro/runtime/source" "github.com/micro/go-micro/runtime/source"
"gopkg.in/src-d/go-git.v4" git "gopkg.in/src-d/go-git.v4"
) )
// Source retrieves source code // Source retrieves source code

View File

@ -178,7 +178,7 @@ func (g *grpcServer) handler(srv interface{}, stream grpc.ServerStream) error {
fullMethod, ok := grpc.MethodFromServerStream(stream) fullMethod, ok := grpc.MethodFromServerStream(stream)
if !ok { if !ok {
return grpc.Errorf(codes.Internal, "method does not exist in context") return status.Errorf(codes.Internal, "method does not exist in context")
} }
serviceName, methodName, err := mgrpc.ServiceMethod(fullMethod) serviceName, methodName, err := mgrpc.ServiceMethod(fullMethod)

View File

@ -880,13 +880,10 @@ func (s *rpcServer) Stop() error {
ch := make(chan error) ch := make(chan error)
s.exit <- ch s.exit <- ch
var err error err := <-ch
select {
case err = <-ch:
s.Lock() s.Lock()
s.started = false s.started = false
s.Unlock() s.Unlock()
}
return err return err
} }

View File

@ -136,6 +136,7 @@ func (w *workersKV) Read(keys ...string) ([]*store.Record, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel() defer cancel()
//nolint:prealloc
var records []*store.Record var records []*store.Record
for _, k := range keys { for _, k := range keys {

View File

@ -17,6 +17,7 @@ type ekv struct {
} }
func (e *ekv) Read(keys ...string) ([]*store.Record, error) { func (e *ekv) Read(keys ...string) ([]*store.Record, error) {
//nolint:prealloc
var values []*mvccpb.KeyValue var values []*mvccpb.KeyValue
for _, key := range keys { for _, key := range keys {
@ -73,10 +74,10 @@ func (e *ekv) List() ([]*store.Record, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
var vals []*store.Record
if keyval == nil || len(keyval.Kvs) == 0 { if keyval == nil || len(keyval.Kvs) == 0 {
return vals, nil return nil, nil
} }
vals := make([]*store.Record, 0, len(keyval.Kvs))
for _, keyv := range keyval.Kvs { for _, keyv := range keyval.Kvs {
vals = append(vals, &store.Record{ vals = append(vals, &store.Record{
Key: string(keyv.Key), Key: string(keyv.Key),

View File

@ -25,6 +25,7 @@ func (m *memoryStore) List() ([]*store.Record, error) {
m.RLock() m.RLock()
defer m.RUnlock() defer m.RUnlock()
//nolint:prealloc
var values []*store.Record var values []*store.Record
for _, v := range m.values { for _, v := range m.values {
@ -52,6 +53,7 @@ func (m *memoryStore) Read(keys ...string) ([]*store.Record, error) {
m.RLock() m.RLock()
defer m.RUnlock() defer m.RUnlock()
//nolint:prealloc
var records []*store.Record var records []*store.Record
for _, key := range keys { for _, key := range keys {

View File

@ -76,20 +76,20 @@ func TestSQL(t *testing.T) {
records, err = sqlStore.Read("test") records, err = sqlStore.Read("test")
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} else { }
t.Logf("%# v\n", pretty.Formatter(records)) t.Logf("%# v\n", pretty.Formatter(records))
if string(records[0].Value) != "bar" { if string(records[0].Value) != "bar" {
t.Error("Expected bar, got ", string(records[0].Value)) t.Error("Expected bar, got ", string(records[0].Value))
} }
}
time.Sleep(61 * time.Second) time.Sleep(61 * time.Second)
records, err = sqlStore.Read("test") _, err = sqlStore.Read("test")
if err == nil { switch err {
case nil:
t.Error("Key test should have expired") t.Error("Key test should have expired")
} else { default:
if err != store.ErrNotFound {
t.Error(err) t.Error(err)
} case store.ErrNotFound:
break
} }
} }

View File

@ -30,7 +30,7 @@ func (s *Store) Read(ctx context.Context, req *pb.ReadRequest, rsp *pb.ReadRespo
} }
func (s *Store) Write(ctx context.Context, req *pb.WriteRequest, rsp *pb.WriteResponse) error { func (s *Store) Write(ctx context.Context, req *pb.WriteRequest, rsp *pb.WriteResponse) error {
var records []*store.Record records := make([]*store.Record, 0, len(req.Records))
for _, record := range req.Records { for _, record := range req.Records {
records = append(records, &store.Record{ records = append(records, &store.Record{

View File

@ -60,7 +60,8 @@ func (s *serviceStore) Read(keys ...string) ([]*store.Record, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
var records []*store.Record
records := make([]*store.Record, 0, len(rsp.Records))
for _, val := range rsp.Records { for _, val := range rsp.Records {
records = append(records, &store.Record{ records = append(records, &store.Record{
Key: val.Key, Key: val.Key,
@ -73,7 +74,7 @@ func (s *serviceStore) Read(keys ...string) ([]*store.Record, error) {
// Write a record // Write a record
func (s *serviceStore) Write(recs ...*store.Record) error { func (s *serviceStore) Write(recs ...*store.Record) error {
var records []*pb.Record records := make([]*pb.Record, 0, len(recs))
for _, record := range recs { for _, record := range recs {
records = append(records, &pb.Record{ records = append(records, &pb.Record{

View File

@ -61,7 +61,7 @@ func (m *memoryLock) Acquire(id string, opts ...lock.AcquireOption) error {
// set a timer for the leftover ttl // set a timer for the leftover ttl
if live > lk.ttl { if live > lk.ttl {
// release the lock if it expired // release the lock if it expired
m.Release(id) _ = m.Release(id)
} else { } else {
ttl = time.After(live) ttl = time.After(live)
} }
@ -94,7 +94,7 @@ lockLoop:
break lockLoop break lockLoop
case <-ttl: case <-ttl:
// ttl exceeded // ttl exceeded
m.Release(id) _ = m.Release(id)
// TODO: check the ttl again above // TODO: check the ttl again above
ttl = nil ttl = nil
// try acquire // try acquire

View File

@ -7,7 +7,7 @@ import (
"encoding/gob" "encoding/gob"
"time" "time"
"github.com/lucas-clemente/quic-go" quic "github.com/lucas-clemente/quic-go"
"github.com/micro/go-micro/transport" "github.com/micro/go-micro/transport"
utls "github.com/micro/go-micro/util/tls" utls "github.com/micro/go-micro/util/tls"
) )

View File

@ -105,6 +105,7 @@ func (t *tun) listChannels() []string {
t.RLock() t.RLock()
defer t.RUnlock() defer t.RUnlock()
//nolint:prealloc
var channels []string var channels []string
for _, session := range t.sessions { for _, session := range t.sessions {
if session.session != "listener" { if session.session != "listener" {

View File

@ -39,6 +39,7 @@ func Extract(addr string) (string, error) {
return "", fmt.Errorf("Failed to get interfaces! Err: %v", err) return "", fmt.Errorf("Failed to get interfaces! Err: %v", err)
} }
//nolint:prealloc
var addrs []net.Addr var addrs []net.Addr
var loAddrs []net.Addr var loAddrs []net.Addr
for _, iface := range ifaces { for _, iface := range ifaces {