From e5bf1448f4275ea5b2a6c59c39fd95db9e25f950 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Sun, 14 Feb 2021 11:28:50 +0300 Subject: [PATCH] lint fixes Signed-off-by: Vasiliy Tolstov --- client/client.go | 40 ++++++++++++++++++------------------- client/options.go | 39 ++++++++++++++++-------------------- codec/codec.go | 2 +- config/default.go | 1 + config/options.go | 10 ++++++++++ errors/errors.go | 27 +++++++++++++------------ logger/logger.go | 2 +- metadata/metadata.go | 4 +++- network/transport/memory.go | 1 + register/options.go | 1 + resolver/dns/dns.go | 1 + resolver/dnssrv/dnssrv.go | 4 +++- server/server.go | 18 ++++++++--------- store/options.go | 7 +++++-- sync/memory.go | 3 ++- tracer/memory.go | 1 + util/reflect/reflect.go | 39 +++++++++++++++++++++++------------- 17 files changed, 114 insertions(+), 86 deletions(-) diff --git a/client/client.go b/client/client.go index d577b55f..16f049c3 100644 --- a/client/client.go +++ b/client/client.go @@ -11,8 +11,21 @@ import ( var ( // DefaultClient is the global default client - DefaultClient Client = NewClient() - DefaultContentType = "application/json" + DefaultClient Client = NewClient() + // DefaultContentType is the default content-type if not specified + DefaultContentType = "application/json" + // DefaultBackoff is the default backoff function for retries + DefaultBackoff = exponentialBackoff + // DefaultRetry is the default check-for-retry function for retries + DefaultRetry = RetryNever + // DefaultRetries is the default number of times a request is tried + DefaultRetries = 0 + // DefaultRequestTimeout is the default request timeout + DefaultRequestTimeout = time.Second * 5 + // DefaultPoolSize sets the connection pool size + DefaultPoolSize = 100 + // DefaultPoolTTL sets the connection pool ttl + DefaultPoolTTL = time.Minute ) // Client is the interface used to make requests to services. @@ -20,10 +33,10 @@ var ( // It also supports bidirectional streaming of requests. type Client interface { Name() string - Init(...Option) error + Init(opts ...Option) error Options() Options NewMessage(topic string, msg interface{}, opts ...MessageOption) Message - NewRequest(service, endpoint string, req interface{}, reqOpts ...RequestOption) Request + NewRequest(service string, endpoint string, req interface{}, opts ...RequestOption) Request Call(ctx context.Context, req Request, rsp interface{}, opts ...CallOption) error Stream(ctx context.Context, req Request, opts ...CallOption) (Stream, error) Publish(ctx context.Context, msg Message, opts ...PublishOption) error @@ -74,9 +87,9 @@ type Stream interface { // The response read Response() Response // Send will encode and send a request - Send(interface{}) error + Send(msg interface{}) error // Recv will decode and read a response - Recv(interface{}) error + Recv(msg interface{}) error // Error returns the stream error Error() error // Close closes the stream @@ -97,18 +110,3 @@ type MessageOption func(*MessageOptions) // RequestOption used by NewRequest type RequestOption func(*RequestOptions) - -var ( - // DefaultBackoff is the default backoff function for retries - DefaultBackoff = exponentialBackoff - // DefaultRetry is the default check-for-retry function for retries - DefaultRetry = RetryNever - // DefaultRetries is the default number of times a request is tried - DefaultRetries = 0 - // DefaultRequestTimeout is the default request timeout - DefaultRequestTimeout = time.Second * 5 - // DefaultPoolSize sets the connection pool size - DefaultPoolSize = 100 - // DefaultPoolTTL sets the connection pool ttl - DefaultPoolTTL = time.Minute -) diff --git a/client/options.go b/client/options.go index 767d15e0..23bbf0e2 100644 --- a/client/options.go +++ b/client/options.go @@ -64,13 +64,13 @@ type CallOptions struct { Address []string // Backoff func Backoff BackoffFunc - // Transport Dial Timeout + // DialTimeout is the transport Dial Timeout DialTimeout time.Duration - // Number of Call attempts + // Retries is the number of Call attempts Retries int - // Check if retriable func + // Retry func to be used for retries Retry RetryFunc - // Request/Response timeout + // RequestTimeout specifies request timeout RequestTimeout time.Duration // Router to use for this call Router router.Router @@ -78,15 +78,15 @@ type CallOptions struct { Selector selector.Selector // SelectOptions to use when selecting a route SelectOptions []selector.SelectOption - // Stream timeout for the stream + // StreamTimeout timeout for the stream StreamTimeout time.Duration - // Use the auth token as the authorization header + // AuthToken specifies the auth token as the authorization header AuthToken bool // Network to lookup the route within Network string - // Middleware for low level call func + // CallWrappers is for low level call func CallWrappers []CallWrapper - // Context is uded for non default options + // Context is used for non default options Context context.Context } @@ -110,8 +110,7 @@ func NewPublishOptions(opts ...PublishOption) PublishOptions { type PublishOptions struct { // Exchange is the routing exchange for the message Exchange string - // Other options for implementations of the interface - // can be stored in a context + // Context holds additional options Context context.Context } @@ -140,10 +139,11 @@ func NewRequestOptions(opts ...RequestOption) RequestOptions { // RequestOptions holds client request options type RequestOptions struct { + // ContentType specify content-type of request ContentType string - Stream bool - // Other options for implementations of the interface - // can be stored in a context + // Stream says that request is the streaming + Stream bool + // Context can hold other options Context context.Context } @@ -212,7 +212,7 @@ func Codec(contentType string, c codec.Codec) Option { } } -// Default content type of the client +// ContentType used by default if not specified func ContentType(ct string) Option { return func(o *Options) { o.ContentType = ct @@ -270,22 +270,21 @@ func Selector(s selector.Selector) Option { } } -// Adds a Wrapper to a list of options passed into the client +// Wrap adds a wrapper to the list of options passed into the client func Wrap(w Wrapper) Option { return func(o *Options) { o.Wrappers = append(o.Wrappers, w) } } -// Adds a Wrapper to the list of CallFunc wrappers +// WrapCall adds a wrapper to the list of CallFunc wrappers func WrapCall(cw ...CallWrapper) Option { return func(o *Options) { o.CallOptions.CallWrappers = append(o.CallOptions.CallWrappers, cw...) } } -// Backoff is used to set the backoff function used -// when retrying Calls +// Backoff is used to set the backoff function used when retrying Calls func Backoff(fn BackoffFunc) Option { return func(o *Options) { o.CallOptions.Backoff = fn @@ -307,7 +306,6 @@ func Lookup(l LookupFunc) Option { } // Retries sets the retry count when making the request. -// Should this be a Call Option? func Retries(i int) Option { return func(o *Options) { o.CallOptions.Retries = i @@ -322,7 +320,6 @@ func Retry(fn RetryFunc) Option { } // RequestTimeout is the request timeout. -// Should this be a Call Option? func RequestTimeout(d time.Duration) Option { return func(o *Options) { o.CallOptions.RequestTimeout = d @@ -463,8 +460,6 @@ func WithMessageContentType(ct string) MessageOption { } } -// Request Options - // WithContentType specifies request content type func WithContentType(ct string) RequestOption { return func(o *RequestOptions) { diff --git a/codec/codec.go b/codec/codec.go index a7c8922c..a893fd91 100644 --- a/codec/codec.go +++ b/codec/codec.go @@ -30,7 +30,7 @@ var ( DefaultCodec Codec = NewCodec() ) -// MessageType +// MessageType specifies message type for codec type MessageType int // Codec encodes/decodes various types of messages used within micro. diff --git a/config/default.go b/config/default.go index e8dbd74e..86692969 100644 --- a/config/default.go +++ b/config/default.go @@ -255,6 +255,7 @@ func (c *defaultConfig) Name() string { return c.opts.Name } +// NewConfig returns new default config source func NewConfig(opts ...Option) Config { options := NewOptions(opts...) if len(options.StructTag) == 0 { diff --git a/config/options.go b/config/options.go index 533c30cf..13fd2451 100644 --- a/config/options.go +++ b/config/options.go @@ -9,6 +9,7 @@ import ( "github.com/unistack-org/micro/v3/tracer" ) +// Options hold the config options type Options struct { Name string AllowFail bool @@ -32,8 +33,10 @@ type Options struct { Context context.Context } +// Option function signature type Option func(o *Options) +// NewOptions new options struct with filed values func NewOptions(opts ...Option) Options { options := Options{ Logger: logger.DefaultLogger, @@ -48,36 +51,42 @@ func NewOptions(opts ...Option) Options { return options } +// AllowFail allows config source to fail func AllowFail(b bool) Option { return func(o *Options) { o.AllowFail = b } } +// BeforeLoad run funcs before config load func BeforeLoad(fn ...func(context.Context, Config) error) Option { return func(o *Options) { o.BeforeLoad = fn } } +// AfterLoad run funcs after config load func AfterLoad(fn ...func(context.Context, Config) error) Option { return func(o *Options) { o.AfterLoad = fn } } +// BeforeSave run funcs before save func BeforeSave(fn ...func(context.Context, Config) error) Option { return func(o *Options) { o.BeforeSave = fn } } +// AfterSave run fncs after save func AfterSave(fn ...func(context.Context, Config) error) Option { return func(o *Options) { o.AfterSave = fn } } +// Context pass context func Context(ctx context.Context) Option { return func(o *Options) { o.Context = ctx @@ -91,6 +100,7 @@ func Codec(c codec.Codec) Option { } } +// Logger sets the logger func Logger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/errors/errors.go b/errors/errors.go index 95b65544..fab2c896 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -9,33 +9,33 @@ import ( ) var ( - // ErrBadRequest + // ErrBadRequest returns then requests contains invalid data ErrBadRequest = &Error{Code: 400} - // ErrUnauthorized + // ErrUnauthorized returns then user have unauthorized call ErrUnauthorized = &Error{Code: 401} - // ErrForbidden + // ErrForbidden returns then user have not access the resource ErrForbidden = &Error{Code: 403} - // ErrNotFound + // ErrNotFound returns then user specify invalid endpoint ErrNotFound = &Error{Code: 404} - // ErrMethodNotAllowed + // ErrMethodNotAllowed returns then user try to get invalid method ErrMethodNotAllowed = &Error{Code: 405} - // ErrTimeout + // ErrTimeout returns then timeout exceeded ErrTimeout = &Error{Code: 408} - // ErrConflict + // ErrConflict returns then request create duplicate resource ErrConflict = &Error{Code: 409} - // ErrInternalServerError + // ErrInternalServerError returns then server cant process request because of internal error ErrInternalServerError = &Error{Code: 500} - // ErNotImplemented + // ErNotImplemented returns then server does not have desired endpoint method ErNotImplemented = &Error{Code: 501} - // ErrBadGateway + // ErrBadGateway returns then server cant process request ErrBadGateway = &Error{Code: 502} - // ErrServiceUnavailable + // ErrServiceUnavailable returns then service unavailable ErrServiceUnavailable = &Error{Code: 503} - // ErrGatewayTimeout + // ErrGatewayTimeout returns then server have long time to process request ErrGatewayTimeout = &Error{Code: 504} ) -// Error tpye +// Error type type Error struct { Id string Code int32 @@ -43,6 +43,7 @@ type Error struct { Status string } +// Error satisfies error interface func (e *Error) Error() string { b, _ := json.Marshal(e) return string(b) diff --git a/logger/logger.go b/logger/logger.go index a3559868..3beea0ec 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -6,7 +6,7 @@ import "context" var ( // DefaultLogger variable DefaultLogger Logger = NewLogger() - // DefaultLogger level + // DefaultLevel used by logger DefaultLevel Level = InfoLevel ) diff --git a/metadata/metadata.go b/metadata/metadata.go index b1b46478..9428fe27 100644 --- a/metadata/metadata.go +++ b/metadata/metadata.go @@ -25,6 +25,7 @@ var ( defaultMetadataSize = 2 ) +// Iterator used to iterate over metadata with order type Iterator struct { cur int cnt int @@ -32,6 +33,7 @@ type Iterator struct { md Metadata } +// Next advance iterator to next element func (iter *Iterator) Next(k, v *string) bool { if iter.cur+1 > iter.cnt { return false @@ -43,7 +45,7 @@ func (iter *Iterator) Next(k, v *string) bool { return true } -// Iterate returns run user func with map key, val sorted by key +// Iterator returns the itarator for metadata in sorted order func (md Metadata) Iterator() *Iterator { iter := &Iterator{md: md, cnt: len(md)} iter.keys = make([]string, 0, iter.cnt) diff --git a/network/transport/memory.go b/network/transport/memory.go index a723356f..82084dd4 100644 --- a/network/transport/memory.go +++ b/network/transport/memory.go @@ -251,6 +251,7 @@ func (m *memoryTransport) Name() string { return m.opts.Name } +// NewTransport returns new memory transport with options func NewTransport(opts ...Option) Transport { options := NewOptions(opts...) diff --git a/register/options.go b/register/options.go index 33f49a00..1a650fb3 100644 --- a/register/options.go +++ b/register/options.go @@ -10,6 +10,7 @@ import ( "github.com/unistack-org/micro/v3/tracer" ) +// Options holds options for register type Options struct { Name string Addrs []string diff --git a/resolver/dns/dns.go b/resolver/dns/dns.go index 0fa2be90..53673b90 100644 --- a/resolver/dns/dns.go +++ b/resolver/dns/dns.go @@ -18,6 +18,7 @@ type Resolver struct { sync.RWMutex } +// Resolve tries to resolve endpoint address func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) { host, port, err := net.SplitHostPort(name) if err != nil { diff --git a/resolver/dnssrv/dnssrv.go b/resolver/dnssrv/dnssrv.go index 28247edb..a7cd3f09 100644 --- a/resolver/dnssrv/dnssrv.go +++ b/resolver/dnssrv/dnssrv.go @@ -9,7 +9,9 @@ import ( ) // Resolver is a DNS network resolve -type Resolver struct{} +type Resolver struct { + Address string +} // Resolve assumes ID is a domain name e.g micro.mu func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) { diff --git a/server/server.go b/server/server.go index fd498630..2521a9d6 100644 --- a/server/server.go +++ b/server/server.go @@ -50,13 +50,13 @@ type Server interface { // Retrieve the options Options() Options // Register a handler - Handle(Handler) error + Handle(h Handler) error // Create a new handler - NewHandler(interface{}, ...HandlerOption) Handler + NewHandler(h interface{}, opts ...HandlerOption) Handler // Create a new subscriber - NewSubscriber(string, interface{}, ...SubscriberOption) Subscriber + NewSubscriber(topic string, h interface{}, opts ...SubscriberOption) Subscriber // Register a subscriber - Subscribe(Subscriber) error + Subscribe(s Subscriber) error // Start the server Start() error // Stop the server @@ -68,9 +68,9 @@ type Server interface { // Router handle serving messages type Router interface { // ProcessMessage processes a message - ProcessMessage(context.Context, Message) error + ProcessMessage(ctx context.Context, msg Message) error // ServeRequest processes a request to completion - ServeRequest(context.Context, Request, Response) error + ServeRequest(ctx context.Context, req Request, rsp Response) error } // Message is an async message interface @@ -116,7 +116,7 @@ type Response interface { // Encoded writer Codec() codec.Codec // Write the header - WriteHeader(metadata.Metadata) + WriteHeader(md metadata.Metadata) // write a response directly to the client Write([]byte) error } @@ -128,8 +128,8 @@ type Response interface { type Stream interface { Context() context.Context Request() Request - Send(interface{}) error - Recv(interface{}) error + Send(msg interface{}) error + Recv(msg interface{}) error Error() error Close() error } diff --git a/store/options.go b/store/options.go index 1f968f8f..deddab3e 100644 --- a/store/options.go +++ b/store/options.go @@ -14,6 +14,7 @@ import ( // Options contains configuration for the Store type Options struct { + // Name specifies store name Name string // Nodes contains the addresses or other connection information of the backing storage. // For example, an etcd implementation would contain the nodes of the cluster. @@ -33,8 +34,7 @@ type Options struct { Tracer tracer.Tracer // TLSConfig specifies tls.Config for secure TLSConfig *tls.Config - - // Context should contain all implementation specific options, using context.WithValue. + // Context should contain all implementation specific options Context context.Context } @@ -292,13 +292,16 @@ func ListOffset(o uint) ListOption { } } +// ExistsOption specifies Exists call options type ExistsOption func(*ExistsOptions) +// ExistsOptions holds options for Exists method type ExistsOptions struct { Namespace string Context context.Context } +// NewExistsOptions helper for Exists method func NewExistsOptions(opts ...ExistsOption) ExistsOptions { options := ExistsOptions{ Context: context.Background(), diff --git a/sync/memory.go b/sync/memory.go index e510bcc8..bb6ca8d3 100644 --- a/sync/memory.go +++ b/sync/memory.go @@ -186,8 +186,9 @@ func (m *memorySync) String() string { return "memory" } +// NewSync return new memory sync func NewSync(opts ...Option) Sync { - var options Options + options := Options{} for _, o := range opts { o(&options) } diff --git a/tracer/memory.go b/tracer/memory.go index 266aa206..0988960c 100644 --- a/tracer/memory.go +++ b/tracer/memory.go @@ -89,6 +89,7 @@ func (t *tracer) Name() string { return t.opts.Name } +// NewTracer returns new memory tracer func NewTracer(opts ...Option) Tracer { return &tracer{ opts: NewOptions(opts...), diff --git a/util/reflect/reflect.go b/util/reflect/reflect.go index 7a5d60ab..21103f49 100644 --- a/util/reflect/reflect.go +++ b/util/reflect/reflect.go @@ -12,9 +12,14 @@ import ( ) var ( - bracketSplitter = regexp.MustCompile(`\[|\]`) + // ErrInvalidStruct specifies invalid struct error ErrInvalidStruct = errors.New("invalid struct specified") - ErrInvalidParam = errors.New("invalid url query param provided") + // ErrInvalidParam specifies invalid url query params + ErrInvalidParam = errors.New("invalid url query param provided") +) + +var ( + bracketSplitter = regexp.MustCompile(`\[|\]`) ) func fieldName(name string) string { @@ -38,6 +43,7 @@ func fieldName(name string) string { return string(newstr) } +// IsEmpty returns true if value empty func IsEmpty(v reflect.Value) bool { switch getKind(v) { case reflect.Array, reflect.Map, reflect.Slice, reflect.String: @@ -63,6 +69,7 @@ func IsEmpty(v reflect.Value) bool { return false } +// Zero creates new zero interface func Zero(src interface{}) (interface{}, error) { sv := reflect.ValueOf(src) @@ -79,6 +86,7 @@ func Zero(src interface{}) (interface{}, error) { return dst.Interface(), nil } +// StructFields returns slice of struct fields func StructFields(src interface{}) ([]reflect.StructField, error) { var fields []reflect.StructField @@ -149,6 +157,7 @@ func CopyFrom(a, b interface{}) { } } +// URLMap returns map of url query params func URLMap(query string) (map[string]interface{}, error) { var ( mp interface{} = make(map[string]interface{}) @@ -167,6 +176,7 @@ func URLMap(query string) (map[string]interface{}, error) { return mp.(map[string]interface{}), nil } +// FlattenMap expand key.subkey to nested map func FlattenMap(a map[string]interface{}) map[string]interface{} { // preprocess map nb := make(map[string]interface{}, len(a)) @@ -197,6 +207,7 @@ func FlattenMap(a map[string]interface{}) map[string]interface{} { return nb } +// MergeMap merges maps func MergeMap(a interface{}, b map[string]interface{}) error { var err error @@ -354,11 +365,11 @@ func mergeBool(va, vb reflect.Value) error { va.SetBool(true) } case reflect.String: - if b, err := strconv.ParseBool(vb.String()); err != nil { + b, err := strconv.ParseBool(vb.String()) + if err != nil { return err - } else { - va.SetBool(b) } + va.SetBool(b) default: return fmt.Errorf("cant merge %v %s with %v %s", va, va.Kind(), vb, vb.Kind()) } @@ -390,11 +401,11 @@ func mergeInt(va, vb reflect.Value) error { case reflect.Float32: va.SetInt(int64(vb.Float())) case reflect.String: - if f, err := strconv.ParseInt(vb.String(), 10, va.Type().Bits()); err != nil { + f, err := strconv.ParseInt(vb.String(), 10, va.Type().Bits()) + if err != nil { return err - } else { - va.SetInt(f) } + va.SetInt(f) default: return fmt.Errorf("cant merge %v %s with %v %s", va, va.Kind(), vb, vb.Kind()) } @@ -410,11 +421,11 @@ func mergeUint(va, vb reflect.Value) error { case reflect.Float32: va.SetUint(uint64(vb.Float())) case reflect.String: - if f, err := strconv.ParseUint(vb.String(), 10, va.Type().Bits()); err != nil { + f, err := strconv.ParseUint(vb.String(), 10, va.Type().Bits()) + if err != nil { return err - } else { - va.SetUint(f) } + va.SetUint(f) default: return fmt.Errorf("cant merge %v %s with %v %s", va, va.Kind(), vb, vb.Kind()) } @@ -430,11 +441,11 @@ func mergeFloat(va, vb reflect.Value) error { case reflect.Float32: va.Set(vb) case reflect.String: - if f, err := strconv.ParseFloat(vb.String(), va.Type().Bits()); err != nil { + f, err := strconv.ParseFloat(vb.String(), va.Type().Bits()) + if err != nil { return err - } else { - va.SetFloat(f) } + va.SetFloat(f) default: return fmt.Errorf("cant merge %v %s with %v %s", va, va.Kind(), vb, vb.Kind()) }