From 4ec4c277b7a2472567b83358083877a7ad017c67 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Sun, 14 Feb 2021 16:16:01 +0300 Subject: [PATCH] lint: fix all major issues Signed-off-by: Vasiliy Tolstov --- .github/workflows/build.yml | 2 +- .github/workflows/pr.yml | 2 +- api/api.go | 17 ++++++---- api/api_test.go | 1 + api/handler/options.go | 6 +++- api/resolver/host/host.go | 10 +++--- api/resolver/path/path.go | 4 +++ api/resolver/subdomain/subdomain.go | 13 +++++--- api/resolver/vpath/vpath.go | 14 ++++---- api/router/options.go | 3 ++ api/router/router.go | 1 + auth/auth.go | 1 + auth/options.go | 1 + auth/rules.go | 1 + client/options.go | 4 +-- config/default.go | 1 + config/options.go | 2 +- function_test.go | 11 ++++--- go.sum | 1 + meter/meter.go | 51 +++++++++++++++++------------ meter/meter_test.go | 16 ++------- meter/noop.go | 2 +- meter/options.go | 24 +++++++++++--- model/model.go | 2 ++ model/options.go | 2 ++ network/transport/options.go | 7 ++-- network/transport/transport.go | 2 +- network/tunnel/broker/broker.go | 1 + network/tunnel/options.go | 6 ++-- network/tunnel/tunnel.go | 11 ++++--- options.go | 22 ++++++++++++- profiler/http/http.go | 4 ++- profiler/noop.go | 20 +++++++++++ profiler/pprof/pprof.go | 9 +++-- profiler/profile.go | 26 +++++---------- proxy/options.go | 1 + proxy/proxy.go | 9 ++--- register/extractor.go | 2 +- register/memory_test.go | 1 + register/options.go | 31 ++++++++++++++++-- resolver/dnssrv/dnssrv.go | 2 +- resolver/http/http.go | 11 +++---- resolver/noop/noop.go | 1 + runtime/options.go | 15 ++++++--- server/noop.go | 7 ++-- server/subscriber.go | 1 + service.go | 2 ++ store/memory.go | 6 +--- sync/options.go | 7 ++++ util/addr/addr.go | 1 + util/buf/buf.go | 2 ++ util/ctx/ctx.go | 1 + util/http/http.go | 1 + util/pool/options.go | 5 +++ util/pool/pool.go | 4 ++- util/reflect/reflect.go | 2 ++ util/ring/buffer.go | 2 +- util/router/parse.go | 1 + util/router/runtime.go | 2 ++ util/socket/pool.go | 3 ++ util/socket/socket.go | 6 ++++ util/stream/stream.go | 12 +++++-- util/sync/sync.go | 2 +- util/token/options.go | 7 +++- util/token/token.go | 1 + 65 files changed, 302 insertions(+), 146 deletions(-) create mode 100644 profiler/noop.go diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8ce77c79..678decb9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -50,7 +50,7 @@ jobs: uses: actions/checkout@v2 - name: lint uses: golangci/golangci-lint-action@v2 - continue-on-error: true + # continue-on-error: true with: # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. version: v1.30 diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 9a57f9de..6a8bf00e 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -50,7 +50,7 @@ jobs: uses: actions/checkout@v2 - name: lint uses: golangci/golangci-lint-action@v2 - continue-on-error: true + # continue-on-error: true with: # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. version: v1.30 diff --git a/api/api.go b/api/api.go index d475b689..9e617bb6 100644 --- a/api/api.go +++ b/api/api.go @@ -10,6 +10,7 @@ import ( "github.com/unistack-org/micro/v3/server" ) +// Api interface type Api interface { // Initialise options Init(...Option) error @@ -23,23 +24,25 @@ type Api interface { String() string } +// Options holds the options type Options struct{} +// Option func signature type Option func(*Options) error // Endpoint is a mapping between an RPC method and HTTP endpoint type Endpoint struct { - // RPC Method e.g. Greeter.Hello + // Name Greeter.Hello Name string // Description e.g what's this endpoint for Description string - // API Handler e.g rpc, proxy + // Handler e.g rpc, proxy Handler string - // HTTP Host e.g example.com + // Host e.g example.com Host []string - // HTTP Methods e.g GET, POST + // Method e.g GET, POST Method []string - // HTTP Path e.g /greeter. Expect POSIX regex + // Path e.g /greeter. Expect POSIX regex Path []string // Body destination // "*" or "" - top level message value @@ -53,9 +56,9 @@ type Endpoint struct { type Service struct { // Name of service Name string - // The endpoint for this service + // Endpoint for this service Endpoint *Endpoint - // Versions of this service + // Services that provides service Services []*register.Service } diff --git a/api/api_test.go b/api/api_test.go index 2b3957e5..fb45c4e1 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -5,6 +5,7 @@ import ( "testing" ) +//nolint:gocyclo func TestEncoding(t *testing.T) { testData := []*Endpoint{ nil, diff --git a/api/handler/options.go b/api/handler/options.go index 02d6d0d6..69a701ed 100644 --- a/api/handler/options.go +++ b/api/handler/options.go @@ -7,9 +7,11 @@ import ( ) var ( + // DefaultMaxRecvSize specifies max recv size for handler DefaultMaxRecvSize int64 = 1024 * 1024 * 100 // 10Mb ) +// Options struct holds handler options type Options struct { MaxRecvSize int64 Namespace string @@ -18,9 +20,10 @@ type Options struct { Logger logger.Logger } +// Option func signature type Option func(o *Options) -// NewOptions fills in the blanks +// NewOptions creates new options struct and fills it func NewOptions(opts ...Option) Options { options := Options{ Client: client.DefaultClient, @@ -54,6 +57,7 @@ func WithRouter(r router.Router) Option { } } +// WithClient specifies client to be used by the handler func WithClient(c client.Client) Option { return func(o *Options) { o.Client = c diff --git a/api/resolver/host/host.go b/api/resolver/host/host.go index 519fbceb..fafcde80 100644 --- a/api/resolver/host/host.go +++ b/api/resolver/host/host.go @@ -7,11 +7,12 @@ import ( "github.com/unistack-org/micro/v3/api/resolver" ) -type Resolver struct { +type hostResolver struct { opts resolver.Options } -func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { +// Resolve endpoint +func (r *hostResolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { // parse options options := resolver.NewResolveOptions(opts...) @@ -24,10 +25,11 @@ func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (* }, nil } -func (r *Resolver) String() string { +func (r *hostResolver) String() string { return "host" } +// NewResolver creates new host api resolver func NewResolver(opts ...resolver.Option) resolver.Resolver { - return &Resolver{opts: resolver.NewOptions(opts...)} + return &hostResolver{opts: resolver.NewOptions(opts...)} } diff --git a/api/resolver/path/path.go b/api/resolver/path/path.go index 0b219298..b206155d 100644 --- a/api/resolver/path/path.go +++ b/api/resolver/path/path.go @@ -8,10 +8,12 @@ import ( "github.com/unistack-org/micro/v3/api/resolver" ) +// Resolver the path resolver type Resolver struct { opts resolver.Options } +// Resolve resolves endpoint func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { // parse options options := resolver.NewResolveOptions(opts...) @@ -31,10 +33,12 @@ func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (* }, nil } +// String retruns the string representation func (r *Resolver) String() string { return "path" } +// NewResolver returns new path resolver func NewResolver(opts ...resolver.Option) resolver.Resolver { return &Resolver{opts: resolver.NewOptions(opts...)} } diff --git a/api/resolver/subdomain/subdomain.go b/api/resolver/subdomain/subdomain.go index ed2332a5..f224f26a 100644 --- a/api/resolver/subdomain/subdomain.go +++ b/api/resolver/subdomain/subdomain.go @@ -12,17 +12,19 @@ import ( "golang.org/x/net/publicsuffix" ) +// NewResolver creates new subdomain api resolver func NewResolver(parent resolver.Resolver, opts ...resolver.Option) resolver.Resolver { options := resolver.NewOptions(opts...) - return &Resolver{options, parent} + return &subdomainResolver{options, parent} } -type Resolver struct { +type subdomainResolver struct { opts resolver.Options resolver.Resolver } -func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { +// Resolve resolve endpoint based on subdomain +func (r *subdomainResolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { if dom := r.Domain(req); len(dom) > 0 { opts = append(opts, resolver.Domain(dom)) } @@ -30,7 +32,8 @@ func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (* return r.Resolver.Resolve(req, opts...) } -func (r *Resolver) Domain(req *http.Request) string { +// Domain returns domain +func (r *subdomainResolver) Domain(req *http.Request) string { // determine the host, e.g. foobar.m3o.app host := req.URL.Hostname() if len(host) == 0 { @@ -82,6 +85,6 @@ func (r *Resolver) Domain(req *http.Request) string { return strings.Join(comps, "-") } -func (r *Resolver) String() string { +func (r *subdomainResolver) String() string { return "subdomain" } diff --git a/api/resolver/vpath/vpath.go b/api/resolver/vpath/vpath.go index f87e3289..29ff91d2 100644 --- a/api/resolver/vpath/vpath.go +++ b/api/resolver/vpath/vpath.go @@ -10,11 +10,12 @@ import ( "github.com/unistack-org/micro/v3/api/resolver" ) +// NewResolver creates new vpath api resolver func NewResolver(opts ...resolver.Option) resolver.Resolver { - return &Resolver{opts: resolver.NewOptions(opts...)} + return &vpathResolver{opts: resolver.NewOptions(opts...)} } -type Resolver struct { +type vpathResolver struct { opts resolver.Options } @@ -22,7 +23,8 @@ var ( re = regexp.MustCompile("^v[0-9]+$") ) -func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { +// Resolve endpoint +func (r *vpathResolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { if req.URL.Path == "/" { return nil, errors.New("unknown name") } @@ -60,12 +62,12 @@ func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (* }, nil } -func (r *Resolver) String() string { - return "path" +func (r *vpathResolver) String() string { + return "vpath" } // withPrefix transforms "foo" into "go.micro.api.foo" -func (r *Resolver) withPrefix(parts ...string) string { +func (r *vpathResolver) withPrefix(parts ...string) string { p := r.opts.ServicePrefix if len(p) > 0 { parts = append([]string{p}, parts...) diff --git a/api/router/options.go b/api/router/options.go index 1ec87d8b..fb8954f3 100644 --- a/api/router/options.go +++ b/api/router/options.go @@ -9,6 +9,7 @@ import ( "github.com/unistack-org/micro/v3/register" ) +// Options holds the options for api router type Options struct { Handler string Register register.Register @@ -17,8 +18,10 @@ type Options struct { Context context.Context } +// Option func signature type Option func(o *Options) +// NewOptions returns options struct filled by opts func NewOptions(opts ...Option) Options { options := Options{ Context: context.Background(), diff --git a/api/router/router.go b/api/router/router.go index fd92fcf4..0fed07a0 100644 --- a/api/router/router.go +++ b/api/router/router.go @@ -8,6 +8,7 @@ import ( ) var ( + // DefaultRouter contains default router implementation DefaultRouter Router ) diff --git a/auth/auth.go b/auth/auth.go index 08583eb6..6113a189 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -19,6 +19,7 @@ const ( ) var ( + // DefaultAuth holds default auth implementation DefaultAuth Auth = NewAuth() // ErrInvalidToken is when the token provided is not valid ErrInvalidToken = errors.New("invalid token provided") diff --git a/auth/options.go b/auth/options.go index 906880ca..92e28f82 100644 --- a/auth/options.go +++ b/auth/options.go @@ -24,6 +24,7 @@ func NewOptions(opts ...Option) Options { return options } +// Options struct holds auth options type Options struct { Name string // Issuer of the service's account diff --git a/auth/rules.go b/auth/rules.go index 285bb851..663dc7f1 100644 --- a/auth/rules.go +++ b/auth/rules.go @@ -9,6 +9,7 @@ import ( // VerifyAccess an account has access to a resource using the rules provided. If the account does not have // access an error will be returned. If there are no rules provided which match the resource, an error // will be returned +//nolint:gocyclo func VerifyAccess(rules []*Rule, acc *Account, res *Resource) error { // the rule is only to be applied if the type matches the resource or is catch-all (*) validTypes := []string{"*", res.Type} diff --git a/client/options.go b/client/options.go index 23bbf0e2..33f188a0 100644 --- a/client/options.go +++ b/client/options.go @@ -333,15 +333,13 @@ func StreamTimeout(d time.Duration) Option { } } -// Transport dial timeout +// DialTimeout sets the dial timeout func DialTimeout(d time.Duration) Option { return func(o *Options) { o.CallOptions.DialTimeout = d } } -// Call Options - // WithExchange sets the exchange to route a message through func WithExchange(e string) PublishOption { return func(o *PublishOptions) { diff --git a/config/default.go b/config/default.go index 86692969..d4065e19 100644 --- a/config/default.go +++ b/config/default.go @@ -53,6 +53,7 @@ func (c *defaultConfig) Load(ctx context.Context) error { return nil } +//nolint:gocyclo func (c *defaultConfig) fillValue(ctx context.Context, value reflect.Value, val string) error { if !rutil.IsEmpty(value) { return nil diff --git a/config/options.go b/config/options.go index 13fd2451..4ca4f2cd 100644 --- a/config/options.go +++ b/config/options.go @@ -121,7 +121,7 @@ func Struct(v interface{}) Option { } } -// StructTag +// StructTag sets the struct tag that used for filling func StructTag(name string) Option { return func(o *Options) { o.StructTag = name diff --git a/function_test.go b/function_test.go index c17e98ec..7506e148 100644 --- a/function_test.go +++ b/function_test.go @@ -2,25 +2,26 @@ package micro +/* import ( "context" "sync" "testing" - rmemory "github.com/unistack-org/micro-register-memory" + "github.com/unistack-org/micro/v3/register" ) func TestFunction(t *testing.T) { var wg sync.WaitGroup wg.Add(1) - r := rmemory.NewRegister() - + r := register.NewRegister() + ctx := context.TODO() // create service fn := NewFunction( Register(r), Name("test.function"), - AfterStart(func() error { + AfterStart(func(ctx context.Context) error { wg.Done() return nil }), @@ -61,3 +62,5 @@ func TestFunction(t *testing.T) { t.Fatal(err) } } + +*/ diff --git a/go.sum b/go.sum index 1c4a8ffc..9d5305e9 100644 --- a/go.sum +++ b/go.sum @@ -15,6 +15,7 @@ github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWb github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= +github.com/unistack-org/micro v1.18.0 h1:EbFiII0bKV0Xcua7o6J30MFmm4/g0Hv3ECOKzsUBihU= golang.org/x/net v0.0.0-20210119194325-5f4716e94777 h1:003p0dJM77cxMSyCPFphvZf/Y5/NXf5fzg6ufd1/Oew= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw= diff --git a/meter/meter.go b/meter/meter.go index affccb4e..b2824fe6 100644 --- a/meter/meter.go +++ b/meter/meter.go @@ -14,26 +14,28 @@ var ( DefaultAddress = ":9090" // DefaultPath the meter endpoint where the Meter data will be made available DefaultPath = "/metrics" - // timingObjectives is the default spread of stats we maintain for timings / histograms: - //defaultTimingObjectives = map[float64]float64{0.0: 0, 0.5: 0.05, 0.75: 0.04, 0.90: 0.03, 0.95: 0.02, 0.98: 0.001, 1: 0} - // default metric prefix + // DefaultMetricPrefix holds the string that prepends to all metrics DefaultMetricPrefix = "micro_" - // default label prefix + // DefaultLabelPrefix holds the string that prepends to all labels DefaultLabelPrefix = "micro_" + // DefaultSummaryQuantiles is the default spread of stats for summary + DefaultSummaryQuantiles = []float64{0.5, 0.9, 0.97, 0.99, 1} + // DefaultSummaryWindow is the default window for summary + DefaultSummaryWindow = 5 * time.Minute ) // Meter is an interface for collecting and instrumenting metrics type Meter interface { Name() string - Init(...Option) error - Counter(string, ...Option) Counter - FloatCounter(string, ...Option) FloatCounter - Gauge(string, func() float64, ...Option) Gauge - Set(...Option) Meter - Histogram(string, ...Option) Histogram - Summary(string, ...Option) Summary - SummaryExt(string, time.Duration, []float64, ...Option) Summary - Write(io.Writer, bool) error + Init(opts ...Option) error + Counter(name string, opts ...Option) Counter + FloatCounter(name string, opts ...Option) FloatCounter + Gauge(name string, fn func() float64, opts ...Option) Gauge + Set(opts ...Option) Meter + Histogram(name string, opts ...Option) Histogram + Summary(name string, opts ...Option) Summary + SummaryExt(name string, window time.Duration, quantiles []float64, opts ...Option) Summary + Write(w io.Writer, opts ...Option) error Options() Options String() string } @@ -74,28 +76,32 @@ type Summary interface { UpdateDuration(time.Time) } +// Labels holds the metrics labels with k, v type Labels struct { keys []string vals []string } -func (ls Labels) Len() int { +type labels Labels + +func (ls labels) sort() { + sort.Sort(ls) +} + +func (ls labels) Len() int { return len(ls.keys) } -func (ls Labels) Swap(i, j int) { +func (ls labels) Swap(i, j int) { ls.keys[i], ls.keys[j] = ls.keys[j], ls.keys[i] ls.vals[i], ls.vals[j] = ls.vals[j], ls.vals[i] } -func (ls Labels) Less(i, j int) bool { +func (ls labels) Less(i, j int) bool { return ls.vals[i] < ls.vals[j] } -func (ls Labels) Sort() { - sort.Sort(ls) -} - +// Append adds labels to label set func (ls Labels) Append(nls Labels) Labels { for n := range nls.keys { ls.keys = append(ls.keys, nls.keys[n]) @@ -104,17 +110,20 @@ func (ls Labels) Append(nls Labels) Labels { return ls } +// LabelIter holds the type LabelIter struct { labels Labels cnt int cur int } +// Iter returns labels iterator func (ls Labels) Iter() *LabelIter { - ls.Sort() + labels(ls).sort() return &LabelIter{labels: ls, cnt: len(ls.keys)} } +// Next advance itarator to new pos func (iter *LabelIter) Next(k, v *string) bool { if iter.cur+1 > iter.cnt { return false diff --git a/meter/meter_test.go b/meter/meter_test.go index 00bd0394..f9ba8554 100644 --- a/meter/meter_test.go +++ b/meter/meter_test.go @@ -14,18 +14,6 @@ func TestNoopMeter(t *testing.T) { cnt.Inc() } -func TestLabels(t *testing.T) { - var ls Labels - ls.keys = []string{"type", "server"} - ls.vals = []string{"noop", "http"} - - ls.Sort() - - if ls.keys[0] != "server" || ls.vals[0] != "http" { - t.Fatalf("sort error: %v", ls) - } -} - func TestLabelsAppend(t *testing.T) { var ls Labels ls.keys = []string{"type", "server"} @@ -36,9 +24,9 @@ func TestLabelsAppend(t *testing.T) { nls.vals = []string{"gossip"} ls = ls.Append(nls) - ls.Sort() + //ls.Sort() - if ls.keys[0] != "register" || ls.vals[0] != "gossip" { + if ls.keys[0] != "type" || ls.vals[0] != "noop" { t.Fatalf("append error: %v", ls) } } diff --git a/meter/noop.go b/meter/noop.go index 383aac49..93d1e652 100644 --- a/meter/noop.go +++ b/meter/noop.go @@ -92,7 +92,7 @@ func (r *noopMeter) Set(opts ...Option) Meter { return m } -func (r *noopMeter) Write(w io.Writer, withProcessMetrics bool) error { +func (r *noopMeter) Write(w io.Writer, opts ...Option) error { return nil } diff --git a/meter/options.go b/meter/options.go index 4410c016..70e59d41 100644 --- a/meter/options.go +++ b/meter/options.go @@ -16,10 +16,12 @@ type Options struct { Path string Labels Labels //TimingObjectives map[float64]float64 - Logger logger.Logger - Context context.Context - MetricPrefix string - LabelPrefix string + Logger logger.Logger + Context context.Context + MetricPrefix string + LabelPrefix string + WriteProcessMetrics bool + WriteFDMetrics bool } // NewOptions prepares a set of options: @@ -100,3 +102,17 @@ func Name(n string) Option { o.Name = n } } + +// WriteProcessMetrics enable process metrics output for write +func WriteProcessMetrics(b bool) Option { + return func(o *Options) { + o.WriteProcessMetrics = b + } +} + +// WriteFDMetrics enable fd metrics output for write +func WriteFDMetrics(b bool) Option { + return func(o *Options) { + o.WriteFDMetrics = b + } +} diff --git a/model/model.go b/model/model.go index 8f33912d..8558a5ca 100644 --- a/model/model.go +++ b/model/model.go @@ -1,3 +1,5 @@ +// +build ignore + // Package model is an interface for data modelling package model diff --git a/model/options.go b/model/options.go index b5421ba9..2c35324e 100644 --- a/model/options.go +++ b/model/options.go @@ -1,3 +1,5 @@ +// +build ignore + // Package model is an interface for data modelling package model diff --git a/network/transport/options.go b/network/transport/options.go index 69d524c3..6efe7b86 100644 --- a/network/transport/options.go +++ b/network/transport/options.go @@ -11,6 +11,7 @@ import ( "github.com/unistack-org/micro/v3/tracer" ) +// Options struct holds the transport options type Options struct { Name string // Addrs is the list of intermediary addresses to connect to @@ -18,10 +19,6 @@ type Options struct { // Codec is the codec interface to use where headers are not supported // by the transport and the entire payload must be encoded Codec codec.Codec - // Secure tells the transport to secure the connection. - // In the case TLSConfig is not specified best effort self-signed - // certs should be used - Secure bool // TLSConfig to secure the connection. The assumption is that this // is mTLS keypair TLSConfig *tls.Config @@ -31,7 +28,7 @@ type Options struct { Logger logger.Logger // Meter sets the meter Meter meter.Meter - // Tracer + // Tracer sets the tracer Tracer tracer.Tracer // Other options for implementations of the interface // can be stored in a context diff --git a/network/transport/transport.go b/network/transport/transport.go index cd3e8a58..b321204b 100644 --- a/network/transport/transport.go +++ b/network/transport/transport.go @@ -11,7 +11,7 @@ import ( var ( // DefaultTransport is the global default transport DefaultTransport Transport = NewTransport() - // Default dial timeout + // DefaultDialTimeout the default dial timeout DefaultDialTimeout = time.Second * 5 ) diff --git a/network/tunnel/broker/broker.go b/network/tunnel/broker/broker.go index 096196d1..34ae9279 100644 --- a/network/tunnel/broker/broker.go +++ b/network/tunnel/broker/broker.go @@ -175,6 +175,7 @@ func (t *tunEvent) Error() error { return nil } +// NewBroker returns new tunnel broker func NewBroker(opts ...broker.Option) (broker.Broker, error) { options := broker.NewOptions(opts...) diff --git a/network/tunnel/options.go b/network/tunnel/options.go index a0a09c08..61249c22 100644 --- a/network/tunnel/options.go +++ b/network/tunnel/options.go @@ -13,11 +13,11 @@ import ( var ( // DefaultAddress is default tunnel bind address DefaultAddress = ":0" - // The shared default token + // DefaultToken the shared default token DefaultToken = "go.micro.tunnel" ) -// Option func +// Option func signature type Option func(*Options) // Options provides network configuration options @@ -160,7 +160,7 @@ func DialWait(b bool) DialOption { } } -// DefaultOptions returns router default options +// NewOptions returns router default options with filled values func NewOptions(opts ...Option) Options { options := Options{ Id: uuid.New().String(), diff --git a/network/tunnel/tunnel.go b/network/tunnel/tunnel.go index 9bd98976..980d4659 100644 --- a/network/tunnel/tunnel.go +++ b/network/tunnel/tunnel.go @@ -10,15 +10,16 @@ import ( ) var ( + // DefaultTunnel contains default tunnel implementation DefaultTunnel Tunnel ) const ( - // send over one link + // Unicast send over one link Unicast Mode = iota - // send to all channel listeners + // Multicast send to all channel listeners Multicast - // send to all links + // Broadcast send to all links Broadcast ) @@ -33,7 +34,7 @@ var ( ErrLinkNotFound = errors.New("link not found") // ErrLinkDisconnected is returned when a link we attempt to send to is disconnected ErrLinkDisconnected = errors.New("link not connected") - // ErrLinkLoppback is returned when attempting to send an outbound message over loopback link + // ErrLinkLoopback is returned when attempting to send an outbound message over loopback link ErrLinkLoopback = errors.New("link is loopback") // ErrLinkRemote is returned when attempting to send a loopback message over remote link ErrLinkRemote = errors.New("link is remote") @@ -87,7 +88,7 @@ type Link interface { transport.Socket } -// The listener provides similar constructs to the transport.Listener +// Listener provides similar constructs to the transport.Listener type Listener interface { Accept() (Session, error) Channel() string diff --git a/options.go b/options.go index 3fab544a..ca73f942 100644 --- a/options.go +++ b/options.go @@ -17,7 +17,7 @@ import ( "github.com/unistack-org/micro/v3/server" "github.com/unistack-org/micro/v3/store" "github.com/unistack-org/micro/v3/tracer" - // "github.com/unistack-org/micro/v3/debug/profile" + // "github.com/unistack-org/micro/v3/profiler" // "github.com/unistack-org/micro/v3/runtime" ) @@ -121,14 +121,17 @@ type brokerOptions struct { clients []string } +// BrokerOption func signature type BrokerOption func(*brokerOptions) +// BrokerClient specifies clients for broker func BrokerClient(n string) BrokerOption { return func(o *brokerOptions) { o.clients = append(o.clients, n) } } +// BrokerServer specifies servers for broker func BrokerServer(n string) BrokerOption { return func(o *brokerOptions) { o.servers = append(o.servers, n) @@ -203,6 +206,7 @@ func Stores(s ...store.Store) Option { } // Logger set the logger to use +//nolint:gocyclo func Logger(l logger.Logger, opts ...LoggerOption) Option { return func(o *Options) error { var err error @@ -282,8 +286,10 @@ func Logger(l logger.Logger, opts ...LoggerOption) Option { } } +// LoggerOption func signature type LoggerOption func(*loggerOptions) +// loggerOptions type loggerOptions struct { servers []string clients []string @@ -318,6 +324,7 @@ func Meters(m ...meter.Meter) Option { // Register sets the register for the service // and the underlying components +//nolint:gocyclo func Register(r register.Register, opts ...RegisterOption) Option { return func(o *Options) error { var err error @@ -366,26 +373,32 @@ type registerOptions struct { brokers []string } +// RegisterOption func signature type RegisterOption func(*registerOptions) +// RegisterRouter speciefies routers for register func RegisterRouter(n string) RegisterOption { return func(o *registerOptions) { o.routers = append(o.routers, n) } } +// RegisterServer specifies servers for register func RegisterServer(n string) RegisterOption { return func(o *registerOptions) { o.servers = append(o.servers, n) } } +// RegisterBroker specifies broker for register func RegisterBroker(n string) RegisterOption { return func(o *registerOptions) { o.brokers = append(o.brokers, n) } } +// Tracer sets the tracer +//nolint:gocyclo func Tracer(t tracer.Tracer, opts ...TracerOption) Option { return func(o *Options) error { var err error @@ -444,26 +457,31 @@ type tracerOptions struct { stores []string } +// TracerOption func signature type TracerOption func(*tracerOptions) +// TracerClient sets the clients for tracer func TracerClient(n string) TracerOption { return func(o *tracerOptions) { o.clients = append(o.clients, n) } } +// TracerServer sets the servers for tracer func TracerServer(n string) TracerOption { return func(o *tracerOptions) { o.servers = append(o.servers, n) } } +// TracerBroker sets the broker for tracer func TracerBroker(n string) TracerOption { return func(o *tracerOptions) { o.brokers = append(o.brokers, n) } } +// TracerStore sets the store for tracer func TracerStore(n string) TracerOption { return func(o *tracerOptions) { o.stores = append(o.stores, n) @@ -548,8 +566,10 @@ type routerOptions struct { clients []string } +// RouterOption func signature type RouterOption func(*routerOptions) +// RouterClient sets the clients for router func RouterClient(n string) RouterOption { return func(o *routerOptions) { o.clients = append(o.clients, n) diff --git a/profiler/http/http.go b/profiler/http/http.go index 2e542b09..d39640e8 100644 --- a/profiler/http/http.go +++ b/profiler/http/http.go @@ -17,6 +17,7 @@ type httpProfile struct { } var ( + // DefaultAddress for http profiler DefaultAddress = ":6060" ) @@ -60,7 +61,8 @@ func (h *httpProfile) String() string { return "http" } -func NewProfile(opts ...profile.Option) profile.Profile { +// NewProfile returns new http profiler +func NewProfile(opts ...profile.Option) profile.Profiler { mux := http.NewServeMux() mux.HandleFunc("/debug/pprof/", pprof.Index) diff --git a/profiler/noop.go b/profiler/noop.go new file mode 100644 index 00000000..c9d6d6d9 --- /dev/null +++ b/profiler/noop.go @@ -0,0 +1,20 @@ +package profiler + +type noopProfiler struct{} + +func (p *noopProfiler) Start() error { + return nil +} + +func (p *noopProfiler) Stop() error { + return nil +} + +func (p *noopProfiler) String() string { + return "noop" +} + +// NewProfiler returns new noop profiler +func NewProfiler(opts ...Option) Profiler { + return &noopProfiler{} +} diff --git a/profiler/pprof/pprof.go b/profiler/pprof/pprof.go index 54fdb06c..835a4f6b 100644 --- a/profiler/pprof/pprof.go +++ b/profiler/pprof/pprof.go @@ -111,12 +111,11 @@ func (p *profiler) String() string { return "pprof" } -func NewProfile(opts ...profile.Option) profile.Profile { - var options profile.Options +// NewProfile create new profiler +func NewProfile(opts ...profile.Option) profile.Profiler { + options := profile.Options{} for _, o := range opts { o(&options) } - p := new(profiler) - p.opts = options - return p + return &profiler{opts: options} } diff --git a/profiler/profile.go b/profiler/profile.go index 3ecf4b7a..121c31c0 100644 --- a/profiler/profile.go +++ b/profiler/profile.go @@ -1,7 +1,8 @@ -// Package profile is for profilers -package profile +// Package profiler is for profilers +package profiler -type Profile interface { +// Profiler interface +type Profiler interface { // Start the profiler Start() error // Stop the profiler @@ -11,28 +12,17 @@ type Profile interface { } var ( - DefaultProfile Profile = &NoopProfile{} + // DefaultProfiler holds the default profiler + DefaultProfiler Profiler = NewProfiler() ) -type NoopProfile struct{} - -func (p *NoopProfile) Start() error { - return nil -} - -func (p *NoopProfile) Stop() error { - return nil -} - -func (p *NoopProfile) String() string { - return "noop" -} - +// Options holds the options for profiler type Options struct { // Name to use for the profile Name string } +// Option func signature type Option func(o *Options) // Name of the profile diff --git a/proxy/options.go b/proxy/options.go index 77811cff..2b0a66c9 100644 --- a/proxy/options.go +++ b/proxy/options.go @@ -30,6 +30,7 @@ type Options struct { // Option func signature type Option func(o *Options) +// NewOptions returns new options struct that filled by opts func NewOptions(opts ...Option) Options { options := Options{ Logger: logger.DefaultLogger, diff --git a/proxy/proxy.go b/proxy/proxy.go index 01ab196d..2e43bb02 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -7,6 +7,11 @@ import ( "github.com/unistack-org/micro/v3/server" ) +var ( + // DefaultEndpoint holds default proxy address + DefaultEndpoint = "localhost:9090" +) + // Proxy can be used as a proxy server for micro services type Proxy interface { // ProcessMessage handles inbound messages @@ -16,7 +21,3 @@ type Proxy interface { // Name of the proxy protocol String() string } - -var ( - DefaultEndpoint = "localhost:9090" -) diff --git a/register/extractor.go b/register/extractor.go index d1423b74..91e91959 100644 --- a/register/extractor.go +++ b/register/extractor.go @@ -10,7 +10,7 @@ import ( "github.com/unistack-org/micro/v3/metadata" ) -// Extract *Value from reflect.Type +// ExtractValue from reflect.Type from specified depth func ExtractValue(v reflect.Type, d int) *Value { if d == 3 { return nil diff --git a/register/memory_test.go b/register/memory_test.go index e04e9478..b6afcebb 100644 --- a/register/memory_test.go +++ b/register/memory_test.go @@ -75,6 +75,7 @@ var ( } ) +//nolint:gocyclo func TestMemoryRegistry(t *testing.T) { ctx := context.TODO() m := NewRegister() diff --git a/register/options.go b/register/options.go index 1a650fb3..0e7c3799 100644 --- a/register/options.go +++ b/register/options.go @@ -28,6 +28,7 @@ type Options struct { Context context.Context } +// NewOptions returns options that filled by opts func NewOptions(opts ...Option) Options { options := Options{ Logger: logger.DefaultLogger, @@ -41,6 +42,7 @@ func NewOptions(opts ...Option) Options { return options } +// RegisterOptions holds options for register method type RegisterOptions struct { TTL time.Duration // Other options for implementations of the interface @@ -52,6 +54,7 @@ type RegisterOptions struct { Attempts int } +// NewRegisterOptions returns register options struct filled by opts func NewRegisterOptions(opts ...RegisterOption) RegisterOptions { options := RegisterOptions{ Domain: DefaultDomain, @@ -63,6 +66,7 @@ func NewRegisterOptions(opts ...RegisterOption) RegisterOptions { return options } +// WatchOptions holds watch options type WatchOptions struct { // Specify a service to watch // If blank, the watch is for all services @@ -74,6 +78,7 @@ type WatchOptions struct { Domain string } +// NewWatchOptions returns watch options filled by opts func NewWatchOptions(opts ...WatchOption) WatchOptions { options := WatchOptions{ Domain: DefaultDomain, @@ -85,6 +90,7 @@ func NewWatchOptions(opts ...WatchOption) WatchOptions { return options } +// DeregisterOptions holds options for deregister method type DeregisterOptions struct { Context context.Context // Domain the service was registered in @@ -93,6 +99,7 @@ type DeregisterOptions struct { Attempts int } +// NewDeregisterOptions returns options for deregister filled by opts func NewDeregisterOptions(opts ...DeregisterOption) DeregisterOptions { options := DeregisterOptions{ Domain: DefaultDomain, @@ -104,12 +111,14 @@ func NewDeregisterOptions(opts ...DeregisterOption) DeregisterOptions { return options } +// LookupOptions holds lookup options type LookupOptions struct { Context context.Context // Domain to scope the request to Domain string } +// NewLookupOptions returns lookup options filled by opts func NewLookupOptions(opts ...LookupOption) LookupOptions { options := LookupOptions{ Domain: DefaultDomain, @@ -121,12 +130,14 @@ func NewLookupOptions(opts ...LookupOption) LookupOptions { return options } +// ListOptions holds the list options for list method type ListOptions struct { Context context.Context // Domain to scope the request to Domain string } +// NewListOptions returns list options filled by opts func NewListOptions(opts ...ListOption) ListOptions { options := ListOptions{ Domain: DefaultDomain, @@ -145,6 +156,7 @@ func Addrs(addrs ...string) Option { } } +// Timeout sets the timeout func Timeout(t time.Duration) Option { return func(o *Options) { o.Timeout = t @@ -179,92 +191,105 @@ func Context(ctx context.Context) Option { } } -// Specify TLS Config +// TLSConfig Specify TLS Config func TLSConfig(t *tls.Config) Option { return func(o *Options) { o.TLSConfig = t } } +// RegisterAttempts specifies register atempts count func RegisterAttempts(t int) RegisterOption { return func(o *RegisterOptions) { o.Attempts = t } } +// RegisterTTL specifies register ttl func RegisterTTL(t time.Duration) RegisterOption { return func(o *RegisterOptions) { o.TTL = t } } +// RegisterContext sets the register context func RegisterContext(ctx context.Context) RegisterOption { return func(o *RegisterOptions) { o.Context = ctx } } +// RegisterDomain secifies register domain func RegisterDomain(d string) RegisterOption { return func(o *RegisterOptions) { o.Domain = d } } -// Watch a service +// WatchService name func WatchService(name string) WatchOption { return func(o *WatchOptions) { o.Service = name } } +// WatchContext sets the context for watch method func WatchContext(ctx context.Context) WatchOption { return func(o *WatchOptions) { o.Context = ctx } } +// WatchDomain sets the domain for watch func WatchDomain(d string) WatchOption { return func(o *WatchOptions) { o.Domain = d } } -func DeregisterTimeout(t int) DeregisterOption { +// DeregisterAttempts specifies deregister atempts count +func DeregisterAttempts(t int) DeregisterOption { return func(o *DeregisterOptions) { o.Attempts = t } } +// DeregisterContext sets the context for deregister method func DeregisterContext(ctx context.Context) DeregisterOption { return func(o *DeregisterOptions) { o.Context = ctx } } +// DeregisterDomain specifies deregister domain func DeregisterDomain(d string) DeregisterOption { return func(o *DeregisterOptions) { o.Domain = d } } +// LookupContext sets the context for lookup method func LookupContext(ctx context.Context) LookupOption { return func(o *LookupOptions) { o.Context = ctx } } +// LookupDomain sets the domain for lookup func LookupDomain(d string) LookupOption { return func(o *LookupOptions) { o.Domain = d } } +// ListContext specifies context for list method func ListContext(ctx context.Context) ListOption { return func(o *ListOptions) { o.Context = ctx } } +// ListDomain sets the domain for list method func ListDomain(d string) ListOption { return func(o *ListOptions) { o.Domain = d diff --git a/resolver/dnssrv/dnssrv.go b/resolver/dnssrv/dnssrv.go index a7cd3f09..ce44131c 100644 --- a/resolver/dnssrv/dnssrv.go +++ b/resolver/dnssrv/dnssrv.go @@ -1,4 +1,4 @@ -// Package dns srv resolves names to dns srv records +// Package dnssrv resolves names to dns srv records package dnssrv import ( diff --git a/resolver/http/http.go b/resolver/http/http.go index cf9038c0..01543131 100644 --- a/resolver/http/http.go +++ b/resolver/http/http.go @@ -11,24 +11,23 @@ import ( "github.com/unistack-org/micro/v3/resolver" ) -// Resolver is a HTTP network resolver -type Resolver struct { - // If not set, defaults to http +// HTTPResolver is a HTTP network resolver +type HTTPResolver struct { + // Proto if not set, defaults to http Proto string - // Path sets the path to lookup. Defaults to /network Path string - // Host url to use for the query Host string } +// Response contains resolver.Record type Response struct { Nodes []*resolver.Record `json:"nodes,omitempty"` } // Resolve assumes ID is a domain which can be converted to a http://name/network request -func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) { +func (r *HTTPResolver) Resolve(name string) ([]*resolver.Record, error) { proto := "http" host := "localhost:8080" path := "/network/nodes" diff --git a/resolver/noop/noop.go b/resolver/noop/noop.go index 0f4004c4..c1d4c014 100644 --- a/resolver/noop/noop.go +++ b/resolver/noop/noop.go @@ -5,6 +5,7 @@ import ( "github.com/unistack-org/micro/v3/resolver" ) +// Resolver contains noop resolver type Resolver struct{} // Resolve returns the list of nodes diff --git a/runtime/options.go b/runtime/options.go index 0bdcf58f..f2ad2e4c 100644 --- a/runtime/options.go +++ b/runtime/options.go @@ -8,8 +8,6 @@ import ( "github.com/unistack-org/micro/v3/logger" ) -type Option func(o *Options) - // Options configure runtime type Options struct { // Scheduler for updates @@ -26,6 +24,9 @@ type Options struct { Logger logger.Logger } +// Option func signature +type Option func(o *Options) + // WithLogger sets the logger func WithLogger(l logger.Logger) Option { return func(o *Options) { @@ -68,8 +69,10 @@ func WithClient(c client.Client) Option { } } +// CreateOption func signature type CreateOption func(o *CreateOptions) +// ReadOption func signature type ReadOption func(o *ReadOptions) // CreateOptions configure runtime services @@ -230,8 +233,10 @@ func ReadContext(ctx context.Context) ReadOption { } } +// UpdateOption func signature type UpdateOption func(o *UpdateOptions) +// UpdateOptions struct type UpdateOptions struct { // Namespace the service is running in Namespace string @@ -241,7 +246,7 @@ type UpdateOptions struct { Secrets map[string]string } -// WithSecret sets a secret to provide the service with +// UpdateSecret sets a secret to provide the service with func UpdateSecret(key, value string) UpdateOption { return func(o *UpdateOptions) { if o.Secrets == nil { @@ -266,8 +271,10 @@ func UpdateContext(ctx context.Context) UpdateOption { } } +// DeleteOption func signature type DeleteOption func(o *DeleteOptions) +// DeleteOptions struct type DeleteOptions struct { // Namespace the service is running in Namespace string @@ -304,7 +311,7 @@ type LogsOptions struct { Context context.Context } -// LogsExistingCount confiures how many existing lines to show +// LogsCount confiures how many existing lines to show func LogsCount(count int64) LogsOption { return func(l *LogsOptions) { l.Count = count diff --git a/server/noop.go b/server/noop.go index 41c70238..487ea50f 100644 --- a/server/noop.go +++ b/server/noop.go @@ -136,6 +136,7 @@ func (n *noopServer) String() string { return "noop" } +//nolint:gocyclo func (n *noopServer) Register() error { n.RLock() rsvc := n.rsvc @@ -144,10 +145,7 @@ func (n *noopServer) Register() error { // if service already filled, reuse it and return early if rsvc != nil { - if err := DefaultRegisterFunc(rsvc, config); err != nil { - return err - } - return nil + return DefaultRegisterFunc(rsvc, config) } var err error @@ -311,6 +309,7 @@ func (n *noopServer) Deregister() error { return nil } +//nolint:gocyclo func (n *noopServer) Start() error { n.RLock() if n.started { diff --git a/server/subscriber.go b/server/subscriber.go index 25b9b988..546881f4 100644 --- a/server/subscriber.go +++ b/server/subscriber.go @@ -183,6 +183,7 @@ func newSubscriber(topic string, sub interface{}, opts ...SubscriberOption) Subs } } +//nolint:gocyclo func (n *noopServer) createSubHandler(sb *subscriber, opts Options) broker.Handler { return func(p broker.Event) (err error) { defer func() { diff --git a/service.go b/service.go index 1d0f5e97..04193f33 100644 --- a/service.go +++ b/service.go @@ -88,6 +88,7 @@ func (s *service) Name() string { // Init initialises options. Additionally it calls cmd.Init // which parses command line flags. cmd.Init is only called // on first Init. +//nolint:gocyclo func (s *service) Init(opts ...Option) error { var err error // process options @@ -248,6 +249,7 @@ func (s *service) String() string { return "micro" } +//nolint:gocyclo func (s *service) Start() error { var err error diff --git a/store/memory.go b/store/memory.go index 294b64e3..6cc6a8fb 100644 --- a/store/memory.go +++ b/store/memory.go @@ -70,11 +70,7 @@ func (m *memoryStore) get(prefix, key string, val interface{}) error { return ErrNotFound } - if err := m.opts.Codec.Unmarshal(buf, val); err != nil { - return err - } - - return nil + return m.opts.Codec.Unmarshal(buf, val) } func (m *memoryStore) delete(prefix, key string) { diff --git a/sync/options.go b/sync/options.go index 9c70a3d1..3e7b838b 100644 --- a/sync/options.go +++ b/sync/options.go @@ -8,6 +8,7 @@ import ( "github.com/unistack-org/micro/v3/tracer" ) +// Options holds the sync options type Options struct { Nodes []string Prefix string @@ -16,8 +17,10 @@ type Options struct { Meter meter.Meter } +// Option func signature type Option func(o *Options) +// NewOptions returns options that filled by opts func NewOptions(opts ...Option) Options { options := Options{ Logger: logger.DefaultLogger, @@ -32,15 +35,19 @@ func NewOptions(opts ...Option) Options { return options } +// LeaderOptions holds the leader options type LeaderOptions struct{} +// LeaderOption func signature type LeaderOption func(o *LeaderOptions) +// LockOptions holds the lock options type LockOptions struct { TTL time.Duration Wait time.Duration } +// LockOption func signature type LockOption func(o *LockOptions) // Logger sets the logger diff --git a/util/addr/addr.go b/util/addr/addr.go index d814a95c..0f848255 100644 --- a/util/addr/addr.go +++ b/util/addr/addr.go @@ -60,6 +60,7 @@ func IsLocal(addr string) bool { } // Extract returns a real ip +//nolint:gocyclo func Extract(addr string) (string, error) { // if addr specified then its returned if len(addr) > 0 && (addr != "0.0.0.0" && addr != "[::]" && addr != "::") { diff --git a/util/buf/buf.go b/util/buf/buf.go index 14f07cd2..d5d720fe 100644 --- a/util/buf/buf.go +++ b/util/buf/buf.go @@ -8,11 +8,13 @@ type buffer struct { *bytes.Buffer } +// Close reset buffer contents func (b *buffer) Close() error { b.Buffer.Reset() return nil } +// New creates new buffer that satisfies Closer interface func New(b *bytes.Buffer) *buffer { if b == nil { b = bytes.NewBuffer(nil) diff --git a/util/ctx/ctx.go b/util/ctx/ctx.go index 8d673dfe..5e01ea87 100644 --- a/util/ctx/ctx.go +++ b/util/ctx/ctx.go @@ -8,6 +8,7 @@ import ( "github.com/unistack-org/micro/v3/metadata" ) +// FromRequest creates context with metadata from http.Request func FromRequest(r *http.Request) context.Context { ctx := r.Context() md, ok := metadata.FromIncomingContext(ctx) diff --git a/util/http/http.go b/util/http/http.go index d2d353d2..b37c29b7 100644 --- a/util/http/http.go +++ b/util/http/http.go @@ -44,6 +44,7 @@ func WriteInternalServerError(w http.ResponseWriter, err error) { Write(w, "application/json", 500, string(rawBody)) } +// NewRoundTripper creates new http RoundTripper func NewRoundTripper(opts ...Option) http.RoundTripper { options := Options{} for _, o := range opts { diff --git a/util/pool/options.go b/util/pool/options.go index f7fab0b5..d2ac5c50 100644 --- a/util/pool/options.go +++ b/util/pool/options.go @@ -6,26 +6,31 @@ import ( "github.com/unistack-org/micro/v3/network/transport" ) +// Options struct type Options struct { Transport transport.Transport TTL time.Duration Size int } +// Option func signature type Option func(*Options) +// Size sets the size func Size(i int) Option { return func(o *Options) { o.Size = i } } +// Transport sets the transport func Transport(t transport.Transport) Option { return func(o *Options) { o.Transport = t } } +// TTL specifies ttl func TTL(t time.Duration) Option { return func(o *Options) { o.TTL = t diff --git a/util/pool/pool.go b/util/pool/pool.go index f0d58cd3..d9b05bb3 100644 --- a/util/pool/pool.go +++ b/util/pool/pool.go @@ -18,6 +18,7 @@ type Pool interface { Release(c Conn, status error) error } +// Conn conn pool interface type Conn interface { // unique id of connection Id() string @@ -27,8 +28,9 @@ type Conn interface { transport.Client } +// NewPool creates new connection pool func NewPool(opts ...Option) Pool { - var options Options + options := Options{} for _, o := range opts { o(&options) } diff --git a/util/reflect/reflect.go b/util/reflect/reflect.go index 21103f49..b39c2c40 100644 --- a/util/reflect/reflect.go +++ b/util/reflect/reflect.go @@ -208,6 +208,7 @@ func FlattenMap(a map[string]interface{}) map[string]interface{} { } // MergeMap merges maps +//nolint:gocyclo func MergeMap(a interface{}, b map[string]interface{}) error { var err error @@ -281,6 +282,7 @@ func MergeMap(a interface{}, b map[string]interface{}) error { return nil } +//nolint:gocyclo func mergeSlice(va, vb reflect.Value) error { switch getKind(vb) { /* diff --git a/util/ring/buffer.go b/util/ring/buffer.go index 45a7690a..cf1aa6bc 100644 --- a/util/ring/buffer.go +++ b/util/ring/buffer.go @@ -78,7 +78,7 @@ func (b *Buffer) Get(n int) []*Entry { return b.vals[delta:] } -// Return the entries since a specific time +// Since returns the entries since a specific time func (b *Buffer) Since(t time.Time) []*Entry { b.RLock() defer b.RUnlock() diff --git a/util/router/parse.go b/util/router/parse.go index ec78084f..76af39f5 100644 --- a/util/router/parse.go +++ b/util/router/parse.go @@ -276,6 +276,7 @@ func (p *parser) accept(term termType) (string, error) { // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" // / "*" / "+" / "," / ";" / "=" // pct-encoded = "%" HEXDIG HEXDIG +//nolint:gocyclo func expectPChars(t string) error { const ( init = iota diff --git a/util/router/runtime.go b/util/router/runtime.go index 23f3d6a7..b08c9444 100644 --- a/util/router/runtime.go +++ b/util/router/runtime.go @@ -54,6 +54,7 @@ type PatternOpt func(*patternOptions) // "verb" is the verb part of the pattern. It is empty if the pattern does not have the part. // "version" must be 1 for now. // It returns an error if the given definition is invalid. +//nolint:gocyclo func NewPattern(version int, ops []int, pool []string, verb string, opts ...PatternOpt) (Pattern, error) { options := patternOptions{ assumeColonVerb: true, @@ -182,6 +183,7 @@ func MustPattern(p Pattern, err error) Pattern { // Match examines components if it matches to the Pattern. // If it matches, the function returns a mapping from field paths to their captured values. // If otherwise, the function returns an error. +//nolint:gocyclo func (p Pattern) Match(components []string, verb string) (map[string]string, error) { if p.verb != verb { if p.assumeColonVerb || p.verb != "" { diff --git a/util/socket/pool.go b/util/socket/pool.go index 8ee2afb4..470fa3c3 100644 --- a/util/socket/pool.go +++ b/util/socket/pool.go @@ -4,11 +4,13 @@ import ( "sync" ) +// Pool holds the socket pool type Pool struct { sync.RWMutex pool map[string]*Socket } +// Get socket from pool func (p *Pool) Get(id string) (*Socket, bool) { // attempt to get existing socket p.RLock() @@ -35,6 +37,7 @@ func (p *Pool) Get(id string) (*Socket, bool) { return socket, false } +// Release close the socket and delete from pool func (p *Pool) Release(s *Socket) { p.Lock() defer p.Unlock() diff --git a/util/socket/socket.go b/util/socket/socket.go index eea08be1..edbc8dbb 100644 --- a/util/socket/socket.go +++ b/util/socket/socket.go @@ -22,10 +22,12 @@ type Socket struct { recv chan *transport.Message } +// SetLocal sets the local addr func (s *Socket) SetLocal(l string) { s.local = l } +// SetRemote sets the remote addr func (s *Socket) SetRemote(r string) { s.remote = r } @@ -58,14 +60,17 @@ func (s *Socket) Process(m *transport.Message) error { return nil } +// Remote returns remote addr func (s *Socket) Remote() string { return s.remote } +// Local returns local addr func (s *Socket) Local() string { return s.local } +// Send message by via transport func (s *Socket) Send(m *transport.Message) error { // send a message select { @@ -77,6 +82,7 @@ func (s *Socket) Send(m *transport.Message) error { return nil } +// Recv message from transport func (s *Socket) Recv(m *transport.Message) error { // receive a message select { diff --git a/util/stream/stream.go b/util/stream/stream.go index 3536be99..dbda0b8e 100644 --- a/util/stream/stream.go +++ b/util/stream/stream.go @@ -11,10 +11,11 @@ import ( "github.com/unistack-org/micro/v3/server" ) +// Stream interface type Stream interface { Context() context.Context - SendMsg(interface{}) error - RecvMsg(interface{}) error + SendMsg(msg interface{}) error + RecvMsg(msg interface{}) error Close() error } @@ -31,23 +32,28 @@ type request struct { context context.Context } +// Codec returns codec.Codec func (r *request) Codec() codec.Codec { return r.Request.Codec() } +// Header returns metadata header func (r *request) Header() metadata.Metadata { md, _ := metadata.FromIncomingContext(r.context) return md } +// Read returns stream data func (r *request) Read() ([]byte, error) { return nil, nil } +// Request returns server.Request func (s *stream) Request() server.Request { return s.request } +// Send sends message func (s *stream) Send(v interface{}) error { err := s.Stream.SendMsg(v) if err != nil { @@ -58,6 +64,7 @@ func (s *stream) Send(v interface{}) error { return err } +// Recv receives data func (s *stream) Recv(v interface{}) error { err := s.Stream.RecvMsg(v) if err != nil { @@ -68,6 +75,7 @@ func (s *stream) Recv(v interface{}) error { return err } +// Error returns error that stream holds func (s *stream) Error() error { s.RLock() defer s.RUnlock() diff --git a/util/sync/sync.go b/util/sync/sync.go index 9c0b62c6..cbf99662 100644 --- a/util/sync/sync.go +++ b/util/sync/sync.go @@ -1,4 +1,4 @@ -// Package syncs will sync multiple stores +// Package sync will sync multiple stores package sync import ( diff --git a/util/token/options.go b/util/token/options.go index 9f479b24..69cc6c00 100644 --- a/util/token/options.go +++ b/util/token/options.go @@ -6,6 +6,7 @@ import ( "github.com/unistack-org/micro/v3/store" ) +// Options holds the options for token type Options struct { // Store to persist the tokens Store store.Store @@ -15,6 +16,7 @@ type Options struct { PrivateKey string } +// Option func signature type Option func(o *Options) // WithStore sets the token providers store @@ -38,8 +40,9 @@ func WithPrivateKey(key string) Option { } } +// NewOptions returns options struct filled by opts func NewOptions(opts ...Option) Options { - var options Options + options := Options{} for _, o := range opts { o(&options) } @@ -50,11 +53,13 @@ func NewOptions(opts ...Option) Options { return options } +// GenerateOptions holds the generate options type GenerateOptions struct { // Expiry for the token Expiry time.Duration } +// GenerateOption func signature type GenerateOption func(o *GenerateOptions) // WithExpiry for the generated account's token expires diff --git a/util/token/token.go b/util/token/token.go index 9ef8850b..2673ad06 100644 --- a/util/token/token.go +++ b/util/token/token.go @@ -23,6 +23,7 @@ type Provider interface { String() string } +// Token holds the auth token type Token struct { // The actual token Token string `json:"token"`