lint fixes #72

Merged
vtolstov merged 4 commits from master into v3 2022-01-10 16:48:28 +03:00
23 changed files with 190 additions and 85 deletions
Showing only changes of commit c26a7db47c - Show all commits

View File

@ -1,4 +1,4 @@
# Micro [![License](https://img.shields.io/:license-apache-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Doc](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/github.com/unistack-org/micro/v3?tab=overview) [![Status](https://github.com/unistack-org/micro/workflows/build/badge.svg?branch=master)](https://github.com/unistack-org/micro/actions?query=workflow%3Abuild+branch%3Amaster+event%3Apush) [![Lint](https://goreportcard.com/badge/github.com/unistack-org/micro)](https://goreportcard.com/report/github.com/unistack-org/micro) [![Slack](https://img.shields.io/static/v1?label=micro&message=slack&color=blueviolet)](https://unistack-org.slack.com/messages/default) # Micro [![License](https://img.shields.io/:license-apache-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Doc](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/github.com/unistack-org/micro/v3?tab=overview) [![Status](https://github.com/unistack-org/micro/workflows/build/badge.svg?branch=master)](https://github.com/unistack-org/micro/actions?query=workflow%3Abuild+branch%3Amaster+event%3Apush) [![Lint](https://goreportcard.com/report/go.unistack.org/micro/v3)](https://goreportcard.com/report/go.unistack.org/micro/v3) [![Slack](https://img.shields.io/static/v1?label=micro&message=slack&color=blueviolet)](https://unistack-org.slack.com/messages/default)
Micro is a standard library for microservices. Micro is a standard library for microservices.

View File

@ -92,10 +92,16 @@ type Stream interface {
Send(msg interface{}) error Send(msg interface{}) error
// Recv will decode and read a response // Recv will decode and read a response
Recv(msg interface{}) error Recv(msg interface{}) error
// SendMsg will encode and send a request
SendMsg(msg interface{}) error
// RecvMsg will decode and read a response
RecvMsg(msg interface{}) error
// Error returns the stream error // Error returns the stream error
Error() error Error() error
// Close closes the stream // Close closes the stream
Close() error Close() error
// CloseSend closes the send direction of the stream
CloseSend() error
} }
// Option used by the Client // Option used by the Client

View File

@ -119,6 +119,14 @@ func (n *noopStream) Recv(interface{}) error {
return nil return nil
} }
func (n *noopStream) SendMsg(interface{}) error {
return nil
}
func (n *noopStream) RecvMsg(interface{}) error {
return nil
}
func (n *noopStream) Error() error { func (n *noopStream) Error() error {
return nil return nil
} }
@ -127,6 +135,10 @@ func (n *noopStream) Close() error {
return nil return nil
} }
func (n *noopStream) CloseSend() error {
return nil
}
func (n *noopMessage) Topic() string { func (n *noopMessage) Topic() string {
return n.topic return n.topic
} }

View File

@ -349,6 +349,7 @@ func (w *microWorkflow) Execute(ctx context.Context, req *Message, opts ...Execu
return eid, err return eid, err
} }
// NewFlow create new flow
func NewFlow(opts ...Option) Flow { func NewFlow(opts ...Option) Flow {
options := NewOptions(opts...) options := NewOptions(opts...)
return &microFlow{opts: options} return &microFlow{opts: options}
@ -574,11 +575,13 @@ func (s *microPublishStep) Execute(ctx context.Context, req *Message, opts ...Ex
return nil, nil return nil, nil
} }
// NewCallStep create new step with client.Call
func NewCallStep(service string, name string, method string, opts ...StepOption) Step { func NewCallStep(service string, name string, method string, opts ...StepOption) Step {
options := NewStepOptions(opts...) options := NewStepOptions(opts...)
return &microCallStep{service: service, method: name + "." + method, opts: options} return &microCallStep{service: service, method: name + "." + method, opts: options}
} }
// NewPublishStep create new step with client.Publish
func NewPublishStep(topic string, opts ...StepOption) Step { func NewPublishStep(topic string, opts ...StepOption) Step {
options := NewStepOptions(opts...) options := NewStepOptions(opts...)
return &microPublishStep{topic: topic, opts: options} return &microPublishStep{topic: topic, opts: options}

View File

@ -70,7 +70,7 @@ func Client(c client.Client) Option {
// Context specifies a context for the service. // Context specifies a context for the service.
// Can be used to signal shutdown of the flow // Can be used to signal shutdown of the flow
// Can be used for extra option values. // or can be used for extra option values.
func Context(ctx context.Context) Option { func Context(ctx context.Context) Option {
return func(o *Options) { return func(o *Options) {
o.Context = ctx o.Context = ctx
@ -91,7 +91,7 @@ func Store(s store.Store) Option {
} }
} }
// WorflowOption signature // WorflowOption func signature
type WorkflowOption func(*WorkflowOptions) type WorkflowOption func(*WorkflowOptions)
// WorkflowOptions holds workflow options // WorkflowOptions holds workflow options
@ -107,6 +107,7 @@ func WorkflowID(id string) WorkflowOption {
} }
} }
// ExecuteOptions holds execute options
type ExecuteOptions struct { type ExecuteOptions struct {
// Client holds the client.Client // Client holds the client.Client
Client client.Client Client client.Client
@ -128,56 +129,66 @@ type ExecuteOptions struct {
Async bool Async bool
} }
// ExecuteOption func signature
type ExecuteOption func(*ExecuteOptions) type ExecuteOption func(*ExecuteOptions)
// ExecuteClient pass client.Client to ExecuteOption
func ExecuteClient(c client.Client) ExecuteOption { func ExecuteClient(c client.Client) ExecuteOption {
return func(o *ExecuteOptions) { return func(o *ExecuteOptions) {
o.Client = c o.Client = c
} }
} }
// ExecuteTracer pass tracer.Tracer to ExecuteOption
func ExecuteTracer(t tracer.Tracer) ExecuteOption { func ExecuteTracer(t tracer.Tracer) ExecuteOption {
return func(o *ExecuteOptions) { return func(o *ExecuteOptions) {
o.Tracer = t o.Tracer = t
} }
} }
// ExecuteLogger pass logger.Logger to ExecuteOption
func ExecuteLogger(l logger.Logger) ExecuteOption { func ExecuteLogger(l logger.Logger) ExecuteOption {
return func(o *ExecuteOptions) { return func(o *ExecuteOptions) {
o.Logger = l o.Logger = l
} }
} }
// ExecuteMeter pass meter.Meter to ExecuteOption
func ExecuteMeter(m meter.Meter) ExecuteOption { func ExecuteMeter(m meter.Meter) ExecuteOption {
return func(o *ExecuteOptions) { return func(o *ExecuteOptions) {
o.Meter = m o.Meter = m
} }
} }
// ExecuteContext pass context.Context ot ExecuteOption
func ExecuteContext(ctx context.Context) ExecuteOption { func ExecuteContext(ctx context.Context) ExecuteOption {
return func(o *ExecuteOptions) { return func(o *ExecuteOptions) {
o.Context = ctx o.Context = ctx
} }
} }
// ExecuteReverse says that dag must be run in reverse order
func ExecuteReverse(b bool) ExecuteOption { func ExecuteReverse(b bool) ExecuteOption {
return func(o *ExecuteOptions) { return func(o *ExecuteOptions) {
o.Reverse = b o.Reverse = b
} }
} }
// ExecuteTimeout pass timeout time.Duration for execution
func ExecuteTimeout(td time.Duration) ExecuteOption { func ExecuteTimeout(td time.Duration) ExecuteOption {
return func(o *ExecuteOptions) { return func(o *ExecuteOptions) {
o.Timeout = td o.Timeout = td
} }
} }
// ExecuteAsync says that caller does not wait for execution complete
func ExecuteAsync(b bool) ExecuteOption { func ExecuteAsync(b bool) ExecuteOption {
return func(o *ExecuteOptions) { return func(o *ExecuteOptions) {
o.Async = b o.Async = b
} }
} }
// NewExecuteOptions create new ExecuteOptions struct
func NewExecuteOptions(opts ...ExecuteOption) ExecuteOptions { func NewExecuteOptions(opts ...ExecuteOption) ExecuteOptions {
options := ExecuteOptions{ options := ExecuteOptions{
Client: client.DefaultClient, Client: client.DefaultClient,
@ -192,6 +203,7 @@ func NewExecuteOptions(opts ...ExecuteOption) ExecuteOptions {
return options return options
} }
// StepOptions holds step options
type StepOptions struct { type StepOptions struct {
Context context.Context Context context.Context
Fallback string Fallback string
@ -199,8 +211,10 @@ type StepOptions struct {
Requires []string Requires []string
} }
// StepOption func signature
type StepOption func(*StepOptions) type StepOption func(*StepOptions)
// NewStepOptions create new StepOptions struct
func NewStepOptions(opts ...StepOption) StepOptions { func NewStepOptions(opts ...StepOption) StepOptions {
options := StepOptions{ options := StepOptions{
Context: context.Background(), Context: context.Background(),
@ -211,18 +225,21 @@ func NewStepOptions(opts ...StepOption) StepOptions {
return options return options
} }
// StepID sets the step id for dag
func StepID(id string) StepOption { func StepID(id string) StepOption {
return func(o *StepOptions) { return func(o *StepOptions) {
o.ID = id o.ID = id
} }
} }
// StepRequires specifies required steps
func StepRequires(steps ...string) StepOption { func StepRequires(steps ...string) StepOption {
return func(o *StepOptions) { return func(o *StepOptions) {
o.Requires = steps o.Requires = steps
} }
} }
// StepFallback set the step to run on error
func StepFallback(step string) StepOption { func StepFallback(step string) StepOption {
return func(o *StepOptions) { return func(o *StepOptions) {
o.Fallback = step o.Fallback = step

View File

@ -1,3 +1,4 @@
//go:build ignore
// +build ignore // +build ignore
package micro package micro

View File

@ -1,3 +1,4 @@
//go:build ignore
// +build ignore // +build ignore
package micro package micro

View File

@ -10,6 +10,7 @@ type stdLogger struct {
level Level level Level
} }
// NewStdLogger returns new *log.Logger baked by logger.Logger implementation
func NewStdLogger(l Logger, level Level) *log.Logger { func NewStdLogger(l Logger, level Level) *log.Logger {
return log.New(&stdLogger{l: l, level: level}, "" /* prefix */, 0 /* flags */) return log.New(&stdLogger{l: l, level: level}, "" /* prefix */, 0 /* flags */)
} }
@ -20,6 +21,7 @@ func (sl *stdLogger) Write(p []byte) (int, error) {
return len(p), nil return len(p), nil
} }
// RedirectStdLogger replace *log.Logger with logger.Logger implementation
func RedirectStdLogger(l Logger, level Level) func() { func RedirectStdLogger(l Logger, level Level) func() {
flags := log.Flags() flags := log.Flags()
prefix := log.Prefix() prefix := log.Prefix()

View File

@ -20,104 +20,104 @@ type Wrapper interface {
Logf(LogfFunc) LogfFunc Logf(LogfFunc) LogfFunc
} }
var _ Logger = &OmitLogger{} var _ Logger = &omitLogger{}
type OmitLogger struct { type omitLogger struct {
l Logger l Logger
} }
func NewOmitLogger(l Logger) Logger { func NewOmitLogger(l Logger) Logger {
return &OmitLogger{l: l} return &omitLogger{l: l}
} }
func (w *OmitLogger) Init(opts ...Option) error { func (w *omitLogger) Init(opts ...Option) error {
return w.l.Init(append(opts, WrapLogger(NewOmitWrapper()))...) return w.l.Init(append(opts, WrapLogger(NewOmitWrapper()))...)
} }
func (w *OmitLogger) V(level Level) bool { func (w *omitLogger) V(level Level) bool {
return w.l.V(level) return w.l.V(level)
} }
func (w *OmitLogger) Level(level Level) { func (w *omitLogger) Level(level Level) {
w.l.Level(level) w.l.Level(level)
} }
func (w *OmitLogger) Clone(opts ...Option) Logger { func (w *omitLogger) Clone(opts ...Option) Logger {
return w.l.Clone(opts...) return w.l.Clone(opts...)
} }
func (w *OmitLogger) Options() Options { func (w *omitLogger) Options() Options {
return w.l.Options() return w.l.Options()
} }
func (w *OmitLogger) Fields(fields ...interface{}) Logger { func (w *omitLogger) Fields(fields ...interface{}) Logger {
return w.l.Fields(fields...) return w.l.Fields(fields...)
} }
func (w *OmitLogger) Info(ctx context.Context, args ...interface{}) { func (w *omitLogger) Info(ctx context.Context, args ...interface{}) {
w.l.Info(ctx, args...) w.l.Info(ctx, args...)
} }
func (w *OmitLogger) Trace(ctx context.Context, args ...interface{}) { func (w *omitLogger) Trace(ctx context.Context, args ...interface{}) {
w.l.Trace(ctx, args...) w.l.Trace(ctx, args...)
} }
func (w *OmitLogger) Debug(ctx context.Context, args ...interface{}) { func (w *omitLogger) Debug(ctx context.Context, args ...interface{}) {
w.l.Debug(ctx, args...) w.l.Debug(ctx, args...)
} }
func (w *OmitLogger) Warn(ctx context.Context, args ...interface{}) { func (w *omitLogger) Warn(ctx context.Context, args ...interface{}) {
w.l.Warn(ctx, args...) w.l.Warn(ctx, args...)
} }
func (w *OmitLogger) Error(ctx context.Context, args ...interface{}) { func (w *omitLogger) Error(ctx context.Context, args ...interface{}) {
w.l.Error(ctx, args...) w.l.Error(ctx, args...)
} }
func (w *OmitLogger) Fatal(ctx context.Context, args ...interface{}) { func (w *omitLogger) Fatal(ctx context.Context, args ...interface{}) {
w.l.Fatal(ctx, args...) w.l.Fatal(ctx, args...)
} }
func (w *OmitLogger) Infof(ctx context.Context, msg string, args ...interface{}) { func (w *omitLogger) Infof(ctx context.Context, msg string, args ...interface{}) {
w.l.Infof(ctx, msg, args...) w.l.Infof(ctx, msg, args...)
} }
func (w *OmitLogger) Tracef(ctx context.Context, msg string, args ...interface{}) { func (w *omitLogger) Tracef(ctx context.Context, msg string, args ...interface{}) {
w.l.Tracef(ctx, msg, args...) w.l.Tracef(ctx, msg, args...)
} }
func (w *OmitLogger) Debugf(ctx context.Context, msg string, args ...interface{}) { func (w *omitLogger) Debugf(ctx context.Context, msg string, args ...interface{}) {
w.l.Debugf(ctx, msg, args...) w.l.Debugf(ctx, msg, args...)
} }
func (w *OmitLogger) Warnf(ctx context.Context, msg string, args ...interface{}) { func (w *omitLogger) Warnf(ctx context.Context, msg string, args ...interface{}) {
w.l.Warnf(ctx, msg, args...) w.l.Warnf(ctx, msg, args...)
} }
func (w *OmitLogger) Errorf(ctx context.Context, msg string, args ...interface{}) { func (w *omitLogger) Errorf(ctx context.Context, msg string, args ...interface{}) {
w.l.Errorf(ctx, msg, args...) w.l.Errorf(ctx, msg, args...)
} }
func (w *OmitLogger) Fatalf(ctx context.Context, msg string, args ...interface{}) { func (w *omitLogger) Fatalf(ctx context.Context, msg string, args ...interface{}) {
w.l.Fatalf(ctx, msg, args...) w.l.Fatalf(ctx, msg, args...)
} }
func (w *OmitLogger) Log(ctx context.Context, level Level, args ...interface{}) { func (w *omitLogger) Log(ctx context.Context, level Level, args ...interface{}) {
w.l.Log(ctx, level, args...) w.l.Log(ctx, level, args...)
} }
func (w *OmitLogger) Logf(ctx context.Context, level Level, msg string, args ...interface{}) { func (w *omitLogger) Logf(ctx context.Context, level Level, msg string, args ...interface{}) {
w.l.Logf(ctx, level, msg, args...) w.l.Logf(ctx, level, msg, args...)
} }
func (w *OmitLogger) String() string { func (w *omitLogger) String() string {
return w.l.String() return w.l.String()
} }
type OmitWrapper struct{} type omitWrapper struct{}
func NewOmitWrapper() Wrapper { func NewOmitWrapper() Wrapper {
return &OmitWrapper{} return &omitWrapper{}
} }
func getArgs(args []interface{}) []interface{} { func getArgs(args []interface{}) []interface{} {
@ -153,13 +153,13 @@ func getArgs(args []interface{}) []interface{} {
return nargs return nargs
} }
func (w *OmitWrapper) Log(fn LogFunc) LogFunc { func (w *omitWrapper) Log(fn LogFunc) LogFunc {
return func(ctx context.Context, level Level, args ...interface{}) { return func(ctx context.Context, level Level, args ...interface{}) {
fn(ctx, level, getArgs(args)...) fn(ctx, level, getArgs(args)...)
} }
} }
func (w *OmitWrapper) Logf(fn LogfFunc) LogfFunc { func (w *omitWrapper) Logf(fn LogfFunc) LogfFunc {
return func(ctx context.Context, level Level, msg string, args ...interface{}) { return func(ctx context.Context, level Level, msg string, args ...interface{}) {
fn(ctx, level, msg, getArgs(args)...) fn(ctx, level, msg, getArgs(args)...)
} }

View File

@ -1,5 +1,5 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT. // Code generated by protoc-gen-go-micro. DO NOT EDIT.
// protoc-gen-go-micro version: v3.5.2 // protoc-gen-go-micro version: v3.5.3
// source: handler.proto // source: handler.proto
package handler package handler

View File

@ -1,5 +1,5 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT. // Code generated by protoc-gen-go-micro. DO NOT EDIT.
// protoc-gen-go-micro version: v3.5.2 // protoc-gen-go-micro version: v3.5.3
// source: handler.proto // source: handler.proto
package handler package handler

View File

@ -9,7 +9,7 @@ import (
// Option powers the configuration for metrics implementations: // Option powers the configuration for metrics implementations:
type Option func(*Options) type Option func(*Options)
// Options for metrics implementations: // Options for metrics implementations
type Options struct { type Options struct {
// Logger used for logging // Logger used for logging
Logger logger.Logger Logger logger.Logger
@ -102,6 +102,7 @@ func Logger(l logger.Logger) Option {
} }
} }
// Labels sets the meter labels
func Labels(ls ...string) Option { func Labels(ls ...string) Option {
return func(o *Options) { return func(o *Options) {
o.Labels = append(o.Labels, ls...) o.Labels = append(o.Labels, ls...)

View File

@ -11,25 +11,38 @@ import (
) )
var ( var (
ClientRequestDurationSeconds = "client_request_duration_seconds" // ClientRequestDurationSeconds specifies meter metric name
ClientRequestDurationSeconds = "client_request_duration_seconds"
// ClientRequestLatencyMicroseconds specifies meter metric name
ClientRequestLatencyMicroseconds = "client_request_latency_microseconds" ClientRequestLatencyMicroseconds = "client_request_latency_microseconds"
ClientRequestTotal = "client_request_total" // ClientRequestTotal specifies meter metric name
ClientRequestInflight = "client_request_inflight" ClientRequestTotal = "client_request_total"
// ClientRequestInflight specifies meter metric name
ServerRequestDurationSeconds = "server_request_duration_seconds" ClientRequestInflight = "client_request_inflight"
// ServerRequestDurationSeconds specifies meter metric name
ServerRequestDurationSeconds = "server_request_duration_seconds"
// ServerRequestLatencyMicroseconds specifies meter metric name
ServerRequestLatencyMicroseconds = "server_request_latency_microseconds" ServerRequestLatencyMicroseconds = "server_request_latency_microseconds"
ServerRequestTotal = "server_request_total" // ServerRequestTotal specifies meter metric name
ServerRequestInflight = "server_request_inflight" ServerRequestTotal = "server_request_total"
// ServerRequestInflight specifies meter metric name
PublishMessageDurationSeconds = "publish_message_duration_seconds" ServerRequestInflight = "server_request_inflight"
// PublishMessageDurationSeconds specifies meter metric name
PublishMessageDurationSeconds = "publish_message_duration_seconds"
// PublishMessageLatencyMicroseconds specifies meter metric name
PublishMessageLatencyMicroseconds = "publish_message_latency_microseconds" PublishMessageLatencyMicroseconds = "publish_message_latency_microseconds"
PublishMessageTotal = "publish_message_total" // PublishMessageTotal specifies meter metric name
PublishMessageInflight = "publish_message_inflight" PublishMessageTotal = "publish_message_total"
// PublishMessageInflight specifies meter metric name
SubscribeMessageDurationSeconds = "subscribe_message_duration_seconds" PublishMessageInflight = "publish_message_inflight"
// SubscribeMessageDurationSeconds specifies meter metric name
SubscribeMessageDurationSeconds = "subscribe_message_duration_seconds"
// SubscribeMessageLatencyMicroseconds specifies meter metric name
SubscribeMessageLatencyMicroseconds = "subscribe_message_latency_microseconds" SubscribeMessageLatencyMicroseconds = "subscribe_message_latency_microseconds"
SubscribeMessageTotal = "subscribe_message_total" // SubscribeMessageTotal specifies meter metric name
SubscribeMessageInflight = "subscribe_message_inflight" SubscribeMessageTotal = "subscribe_message_total"
// SubscribeMessageInflight specifies meter metric name
SubscribeMessageInflight = "subscribe_message_inflight"
labelSuccess = "success" labelSuccess = "success"
labelFailure = "failure" labelFailure = "failure"
@ -40,14 +53,17 @@ var (
DefaultSkipEndpoints = []string{"Meter.Metrics"} DefaultSkipEndpoints = []string{"Meter.Metrics"}
) )
// Options struct
type Options struct { type Options struct {
Meter meter.Meter Meter meter.Meter
lopts []meter.Option lopts []meter.Option
SkipEndpoints []string SkipEndpoints []string
} }
// Option func signature
type Option func(*Options) type Option func(*Options)
// NewOptions creates new Options struct
func NewOptions(opts ...Option) Options { func NewOptions(opts ...Option) Options {
options := Options{ options := Options{
Meter: meter.DefaultMeter, Meter: meter.DefaultMeter,
@ -60,30 +76,35 @@ func NewOptions(opts ...Option) Options {
return options return options
} }
// ServiceName passes service name to meter label
func ServiceName(name string) Option { func ServiceName(name string) Option {
return func(o *Options) { return func(o *Options) {
o.lopts = append(o.lopts, meter.Labels("name", name)) o.lopts = append(o.lopts, meter.Labels("name", name))
} }
} }
// ServiceVersion passes service version to meter label
func ServiceVersion(version string) Option { func ServiceVersion(version string) Option {
return func(o *Options) { return func(o *Options) {
o.lopts = append(o.lopts, meter.Labels("version", version)) o.lopts = append(o.lopts, meter.Labels("version", version))
} }
} }
// ServiceID passes service id to meter label
func ServiceID(id string) Option { func ServiceID(id string) Option {
return func(o *Options) { return func(o *Options) {
o.lopts = append(o.lopts, meter.Labels("id", id)) o.lopts = append(o.lopts, meter.Labels("id", id))
} }
} }
// Meter passes meter
func Meter(m meter.Meter) Option { func Meter(m meter.Meter) Option {
return func(o *Options) { return func(o *Options) {
o.Meter = m o.Meter = m
} }
} }
// SkipEndpoint add endpoint to skip
func SkipEndoints(eps ...string) Option { func SkipEndoints(eps ...string) Option {
return func(o *Options) { return func(o *Options) {
o.SkipEndpoints = append(o.SkipEndpoints, eps...) o.SkipEndpoints = append(o.SkipEndpoints, eps...)
@ -96,6 +117,7 @@ type wrapper struct {
opts Options opts Options
} }
// NewClientWrapper create new client wrapper
func NewClientWrapper(opts ...Option) client.Wrapper { func NewClientWrapper(opts ...Option) client.Wrapper {
return func(c client.Client) client.Client { return func(c client.Client) client.Client {
handler := &wrapper{ handler := &wrapper{
@ -106,6 +128,7 @@ func NewClientWrapper(opts ...Option) client.Wrapper {
} }
} }
// NewCallWrapper create new call wrapper
func NewCallWrapper(opts ...Option) client.CallWrapper { func NewCallWrapper(opts ...Option) client.CallWrapper {
return func(fn client.CallFunc) client.CallFunc { return func(fn client.CallFunc) client.CallFunc {
handler := &wrapper{ handler := &wrapper{
@ -231,6 +254,7 @@ func (w *wrapper) Publish(ctx context.Context, p client.Message, opts ...client.
return err return err
} }
// NewHandlerWrapper create new server handler wrapper
func NewHandlerWrapper(opts ...Option) server.HandlerWrapper { func NewHandlerWrapper(opts ...Option) server.HandlerWrapper {
handler := &wrapper{ handler := &wrapper{
opts: NewOptions(opts...), opts: NewOptions(opts...),
@ -240,7 +264,7 @@ func NewHandlerWrapper(opts ...Option) server.HandlerWrapper {
func (w *wrapper) HandlerFunc(fn server.HandlerFunc) server.HandlerFunc { func (w *wrapper) HandlerFunc(fn server.HandlerFunc) server.HandlerFunc {
return func(ctx context.Context, req server.Request, rsp interface{}) error { return func(ctx context.Context, req server.Request, rsp interface{}) error {
endpoint := req.Endpoint() endpoint := req.Service() + "." + req.Endpoint()
for _, ep := range w.opts.SkipEndpoints { for _, ep := range w.opts.SkipEndpoints {
if ep == endpoint { if ep == endpoint {
return fn(ctx, req, rsp) return fn(ctx, req, rsp)
@ -270,6 +294,7 @@ func (w *wrapper) HandlerFunc(fn server.HandlerFunc) server.HandlerFunc {
} }
} }
// NewSubscribeWrapper create server subscribe wrapper
func NewSubscriberWrapper(opts ...Option) server.SubscriberWrapper { func NewSubscriberWrapper(opts ...Option) server.SubscriberWrapper {
handler := &wrapper{ handler := &wrapper{
opts: NewOptions(opts...), opts: NewOptions(opts...),

View File

@ -1,5 +1,5 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT. // Code generated by protoc-gen-go-micro. DO NOT EDIT.
// protoc-gen-go-micro version: v3.5.2 // protoc-gen-go-micro version: v3.5.3
// source: health.proto // source: health.proto
package health package health

View File

@ -1,5 +1,5 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT. // Code generated by protoc-gen-go-micro. DO NOT EDIT.
// protoc-gen-go-micro version: v3.5.2 // protoc-gen-go-micro version: v3.5.3
// source: health.proto // source: health.proto
package health package health

View File

@ -123,11 +123,21 @@ type Response interface {
// The last error will be left in Error(). // The last error will be left in Error().
// EOF indicates end of the stream. // EOF indicates end of the stream.
type Stream interface { type Stream interface {
// Context for the stream
Context() context.Context Context() context.Context
// Request returns request
Request() Request Request() Request
// Send will encode and send a request
Send(msg interface{}) error Send(msg interface{}) error
// Recv will decode and read a response
Recv(msg interface{}) error Recv(msg interface{}) error
// SendMsg will encode and send a request
SendMsg(msg interface{}) error
// RecvMsg will decode and read a response
RecvMsg(msg interface{}) error
// Error returns stream error
Error() error Error() error
// Close closes the stream
Close() error Close() error
} }

View File

@ -2,8 +2,12 @@ package buf // import "go.unistack.org/micro/v3/util/buf"
import ( import (
"bytes" "bytes"
"io"
) )
var _ io.Closer = &Buffer{}
// Buffer bytes.Buffer wrapper to satisfie io.Closer interface
type Buffer struct { type Buffer struct {
*bytes.Buffer *bytes.Buffer
} }

View File

@ -1,3 +1,4 @@
//go:build ignore
// +build ignore // +build ignore
package http package http

View File

@ -45,8 +45,7 @@ var methodMap = map[string]methodTyp{
http.MethodTrace: mTRACE, http.MethodTrace: mTRACE,
} }
// RegisterMethod adds support for custom HTTP method handlers, available // RegisterMethod adds support for custom HTTP method handlers
// via Router#Method and Router#MethodFunc
func RegisterMethod(method string) error { func RegisterMethod(method string) error {
if method == "" { if method == "" {
return nil return nil
@ -75,13 +74,13 @@ const (
ntCatchAll // /api/v1/* ntCatchAll // /api/v1/*
) )
func NewTrie() *Node { // NewTrie create new tree
return &Node{} func NewTrie() *Trie {
return &Trie{}
} }
type Trie = Node // Trie holds nodes for path based tree search
type Trie struct {
type Node struct {
// regexp matcher for regexp nodes // regexp matcher for regexp nodes
rex *regexp.Regexp rex *regexp.Regexp
@ -128,7 +127,8 @@ func (s endpoints) Value(method methodTyp) *endpoint {
return mh return mh
} }
func (n *Node) Insert(methods []string, pattern string, handler interface{}) error { // Insert add elemenent to tree
func (n *Trie) Insert(methods []string, pattern string, handler interface{}) error {
var err error var err error
for _, method := range methods { for _, method := range methods {
if err = n.insert(methodMap[method], pattern, handler); err != nil { if err = n.insert(methodMap[method], pattern, handler); err != nil {
@ -138,8 +138,8 @@ func (n *Node) Insert(methods []string, pattern string, handler interface{}) err
return nil return nil
} }
func (n *Node) insert(method methodTyp, pattern string, handler interface{}) error { func (n *Trie) insert(method methodTyp, pattern string, handler interface{}) error {
var parent *Node var parent *Trie
search := pattern search := pattern
for { for {
@ -175,8 +175,8 @@ func (n *Node) insert(method methodTyp, pattern string, handler interface{}) err
// No edge, create one // No edge, create one
if n == nil { if n == nil {
child := &Node{typ: ntStatic, label: label, tail: segTail, prefix: search} child := &Trie{typ: ntStatic, label: label, tail: segTail, prefix: search}
var hn *Node var hn *Trie
hn, err = parent.addChild(child, search) hn, err = parent.addChild(child, search)
if err != nil { if err != nil {
return err return err
@ -205,7 +205,7 @@ func (n *Node) insert(method methodTyp, pattern string, handler interface{}) err
} }
// Split the node // Split the node
child := &Node{ child := &Trie{
typ: ntStatic, typ: ntStatic,
prefix: search[:commonPrefix], prefix: search[:commonPrefix],
} }
@ -227,12 +227,12 @@ func (n *Node) insert(method methodTyp, pattern string, handler interface{}) err
} }
// Create a new edge for the node // Create a new edge for the node
subchild := &Node{ subchild := &Trie{
typ: ntStatic, typ: ntStatic,
label: search[0], label: search[0],
prefix: search, prefix: search,
} }
var hn *Node var hn *Trie
hn, err = child.addChild(subchild, search) hn, err = child.addChild(subchild, search)
if err != nil { if err != nil {
return err return err
@ -245,7 +245,7 @@ func (n *Node) insert(method methodTyp, pattern string, handler interface{}) err
// For a URL router like chi's, we split the static, param, regexp and wildcard segments // For a URL router like chi's, we split the static, param, regexp and wildcard segments
// into different nodes. In addition, addChild will recursively call itself until every // into different nodes. In addition, addChild will recursively call itself until every
// pattern segment is added to the url pattern tree as individual nodes, depending on type. // pattern segment is added to the url pattern tree as individual nodes, depending on type.
func (n *Node) addChild(child *Node, prefix string) (*Node, error) { func (n *Trie) addChild(child *Trie, prefix string) (*Trie, error) {
search := prefix search := prefix
// handler leaf node added to the tree is the child. // handler leaf node added to the tree is the child.
@ -298,7 +298,7 @@ func (n *Node) addChild(child *Node, prefix string) (*Node, error) {
search = search[segStartIdx:] // advance search position search = search[segStartIdx:] // advance search position
nn := &Node{ nn := &Trie{
typ: ntStatic, typ: ntStatic,
label: search[0], label: search[0],
prefix: search, prefix: search,
@ -321,7 +321,7 @@ func (n *Node) addChild(child *Node, prefix string) (*Node, error) {
// add the param edge node // add the param edge node
search = search[segStartIdx:] search = search[segStartIdx:]
nn := &Node{ nn := &Trie{
typ: segTyp, typ: segTyp,
label: search[0], label: search[0],
tail: segTail, tail: segTail,
@ -339,7 +339,7 @@ func (n *Node) addChild(child *Node, prefix string) (*Node, error) {
return hn, nil return hn, nil
} }
func (n *Node) replaceChild(label, tail byte, child *Node) error { func (n *Trie) replaceChild(label, tail byte, child *Trie) error {
for i := 0; i < len(n.children[child.typ]); i++ { for i := 0; i < len(n.children[child.typ]); i++ {
if n.children[child.typ][i].label == label && n.children[child.typ][i].tail == tail { if n.children[child.typ][i].label == label && n.children[child.typ][i].tail == tail {
n.children[child.typ][i] = child n.children[child.typ][i] = child
@ -351,7 +351,7 @@ func (n *Node) replaceChild(label, tail byte, child *Node) error {
return fmt.Errorf("replacing missing child") return fmt.Errorf("replacing missing child")
} }
func (n *Node) getEdge(ntyp nodeTyp, label, tail byte, prefix string) *Node { func (n *Trie) getEdge(ntyp nodeTyp, label, tail byte, prefix string) *Trie {
nds := n.children[ntyp] nds := n.children[ntyp]
for i := 0; i < len(nds); i++ { for i := 0; i < len(nds); i++ {
if nds[i].label == label && nds[i].tail == tail { if nds[i].label == label && nds[i].tail == tail {
@ -364,7 +364,7 @@ func (n *Node) getEdge(ntyp nodeTyp, label, tail byte, prefix string) *Node {
return nil return nil
} }
func (n *Node) setEndpoint(method methodTyp, handler interface{}, pattern string) error { func (n *Trie) setEndpoint(method methodTyp, handler interface{}, pattern string) error {
// Set the handler for the method type on the node // Set the handler for the method type on the node
if n.endpoints == nil { if n.endpoints == nil {
n.endpoints = make(endpoints) n.endpoints = make(endpoints)
@ -398,7 +398,8 @@ func (n *Node) setEndpoint(method methodTyp, handler interface{}, pattern string
return nil return nil
} }
func (n *Node) Search(method string, path string) (interface{}, map[string]string, bool) { // Search try to find element in tree with path and method
func (n *Trie) Search(method string, path string) (interface{}, map[string]string, bool) {
params := &routeParams{} params := &routeParams{}
// Find the routing handlers for the path // Find the routing handlers for the path
rn := n.findRoute(params, methodMap[method], path) rn := n.findRoute(params, methodMap[method], path)
@ -425,7 +426,7 @@ type routeParams struct {
// Recursive edge traversal by checking all nodeTyp groups along the way. // Recursive edge traversal by checking all nodeTyp groups along the way.
// It's like searching through a multi-dimensional radix trie. // It's like searching through a multi-dimensional radix trie.
func (n *Node) findRoute(params *routeParams, method methodTyp, path string) *Node { func (n *Trie) findRoute(params *routeParams, method methodTyp, path string) *Trie {
nn := n nn := n
search := path search := path
@ -435,7 +436,7 @@ func (n *Node) findRoute(params *routeParams, method methodTyp, path string) *No
continue continue
} }
var xn *Node var xn *Trie
xsearch := search xsearch := search
var label byte var label byte
@ -550,7 +551,7 @@ func (n *Node) findRoute(params *routeParams, method methodTyp, path string) *No
return nil return nil
} }
func (n *Node) isLeaf() bool { func (n *Trie) isLeaf() bool {
return n.endpoints != nil return n.endpoints != nil
} }
@ -665,7 +666,7 @@ func longestPrefix(k1, k2 string) int {
return i return i
} }
type nodes []*Node type nodes []*Trie
// Sort the list of nodes by label // Sort the list of nodes by label
func (ns nodes) Sort() { sort.Sort(ns); ns.tailSort() } func (ns nodes) Sort() { sort.Sort(ns); ns.tailSort() }
@ -684,7 +685,7 @@ func (ns nodes) tailSort() {
} }
} }
func (ns nodes) findEdge(label byte) *Node { func (ns nodes) findEdge(label byte) *Trie {
num := len(ns) num := len(ns)
idx := 0 idx := 0
i, j := 0, num-1 i, j := 0, num-1

View File

@ -1,3 +1,4 @@
//go:build ignore
// +build ignore // +build ignore
package pool package pool

View File

@ -10,16 +10,19 @@ type Rand struct {
buf [8]byte buf [8]byte
} }
// Int31 function implementation
func (r *Rand) Int31() int32 { func (r *Rand) Int31() int32 {
_, _ = crand.Read(r.buf[:4]) _, _ = crand.Read(r.buf[:4])
return int32(binary.BigEndian.Uint32(r.buf[:4]) & ^uint32(1<<31)) return int32(binary.BigEndian.Uint32(r.buf[:4]) & ^uint32(1<<31))
} }
// Int function implementation
func (r *Rand) Int() int { func (r *Rand) Int() int {
u := uint(r.Int63()) u := uint(r.Int63())
return int(u << 1 >> 1) // clear sign bit if int == int32 return int(u << 1 >> 1) // clear sign bit if int == int32
} }
// Float64 function implementation
func (r *Rand) Float64() float64 { func (r *Rand) Float64() float64 {
again: again:
f := float64(r.Int63()) / (1 << 63) f := float64(r.Int63()) / (1 << 63)
@ -29,6 +32,7 @@ again:
return f return f
} }
// Float32 function implementation
func (r *Rand) Float32() float32 { func (r *Rand) Float32() float32 {
again: again:
f := float32(r.Float64()) f := float32(r.Float64())
@ -38,14 +42,17 @@ again:
return f return f
} }
// Uint32 function implementation
func (r *Rand) Uint32() uint32 { func (r *Rand) Uint32() uint32 {
return uint32(r.Int63() >> 31) return uint32(r.Int63() >> 31)
} }
// Uint64 function implementation
func (r *Rand) Uint64() uint64 { func (r *Rand) Uint64() uint64 {
return uint64(r.Int63())>>31 | uint64(r.Int63())<<32 return uint64(r.Int63())>>31 | uint64(r.Int63())<<32
} }
// Intn function implementation
func (r *Rand) Intn(n int) int { func (r *Rand) Intn(n int) int {
if n <= 1<<31-1 { if n <= 1<<31-1 {
return int(r.Int31n(int32(n))) return int(r.Int31n(int32(n)))
@ -53,12 +60,13 @@ func (r *Rand) Intn(n int) int {
return int(r.Int63n(int64(n))) return int(r.Int63n(int64(n)))
} }
// Int63 function implementation
func (r *Rand) Int63() int64 { func (r *Rand) Int63() int64 {
_, _ = crand.Read(r.buf[:]) _, _ = crand.Read(r.buf[:])
return int64(binary.BigEndian.Uint64(r.buf[:]) & ^uint64(1<<63)) return int64(binary.BigEndian.Uint64(r.buf[:]) & ^uint64(1<<63))
} }
// Int31n copied from the standard library math/rand implementation of Int31n // Int31n function implementation copied from the standard library math/rand implementation of Int31n
func (r *Rand) Int31n(n int32) int32 { func (r *Rand) Int31n(n int32) int32 {
if n&(n-1) == 0 { // n is power of two, can mask if n&(n-1) == 0 { // n is power of two, can mask
return r.Int31() & (n - 1) return r.Int31() & (n - 1)
@ -71,7 +79,7 @@ func (r *Rand) Int31n(n int32) int32 {
return v % n return v % n
} }
// Int63n copied from the standard library math/rand implementation of Int63n // Int63n function implementation copied from the standard library math/rand implementation of Int63n
func (r *Rand) Int63n(n int64) int64 { func (r *Rand) Int63n(n int64) int64 {
if n&(n-1) == 0 { // n is power of two, can mask if n&(n-1) == 0 { // n is power of two, can mask
return r.Int63() & (n - 1) return r.Int63() & (n - 1)
@ -84,7 +92,7 @@ func (r *Rand) Int63n(n int64) int64 {
return v % n return v % n
} }
// Shuffle copied from the standard library math/rand implementation of Shuffle // Shuffle function implementation copied from the standard library math/rand implementation of Shuffle
func (r *Rand) Shuffle(n int, swap func(i, j int)) { func (r *Rand) Shuffle(n int, swap func(i, j int)) {
if n < 0 { if n < 0 {
panic("invalid argument to Shuffle") panic("invalid argument to Shuffle")

View File

@ -10,30 +10,40 @@ import (
) )
var ( var (
// ErrInvalidStruct happens when passed not struct and not struct pointer
ErrInvalidStruct = errors.New("invalid struct specified") ErrInvalidStruct = errors.New("invalid struct specified")
ErrInvalidValue = errors.New("invalid value specified") // ErrInvalidValue happens when passed invalid value for field
ErrNotFound = errors.New("struct field not found") ErrInvalidValue = errors.New("invalid value specified")
// ErrNotFound happens when struct field not found
ErrNotFound = errors.New("struct field not found")
) )
// Option func signature
type Option func(*Options) type Option func(*Options)
// Options for merge
type Options struct { type Options struct {
Tags []string // Tags specifies tags to lookup
Tags []string
// SliceAppend controls slice appending
SliceAppend bool SliceAppend bool
} }
// Tags sets the merge tags for lookup
func Tags(t []string) Option { func Tags(t []string) Option {
return func(o *Options) { return func(o *Options) {
o.Tags = t o.Tags = t
} }
} }
// SliceAppend sets the option
func SliceAppend(b bool) Option { func SliceAppend(b bool) Option {
return func(o *Options) { return func(o *Options) {
o.SliceAppend = b o.SliceAppend = b
} }
} }
// Merge merges map[string]interface{} to destination struct
func Merge(dst interface{}, mp map[string]interface{}, opts ...Option) error { func Merge(dst interface{}, mp map[string]interface{}, opts ...Option) error {
var err error var err error
var sval reflect.Value var sval reflect.Value
@ -481,6 +491,7 @@ func IsEmpty(v reflect.Value) bool {
return true return true
} }
// FieldName returns map field name that can be looked up in struct field
func FieldName(name string) string { func FieldName(name string) string {
newstr := make([]rune, 0, len(name)) newstr := make([]rune, 0, len(name))
for idx, chr := range name { for idx, chr := range name {

View File

@ -1,3 +1,4 @@
//go:build ignore
// +build ignore // +build ignore
package basic package basic