fix linting #4

Merged
vtolstov merged 1 commits from lint into master 2020-11-03 01:08:23 +03:00
36 changed files with 218 additions and 188 deletions

View File

@ -9,10 +9,12 @@ import (
"github.com/unistack-org/micro/v3/api/resolver" "github.com/unistack-org/micro/v3/api/resolver"
) )
// Resolver struct
type Resolver struct { type Resolver struct {
opts resolver.Options opts resolver.Options
} }
// Resolve func to resolve enndpoint
func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) { func (r *Resolver) Resolve(req *http.Request, opts ...resolver.ResolveOption) (*resolver.Endpoint, error) {
// parse options // parse options
options := resolver.NewResolveOptions(opts...) options := resolver.NewResolveOptions(opts...)
@ -39,6 +41,7 @@ func (r *Resolver) String() string {
return "grpc" return "grpc"
} }
// NewResolver is used to create new Resolver
func NewResolver(opts ...resolver.Option) resolver.Resolver { func NewResolver(opts ...resolver.Option) resolver.Resolver {
return &Resolver{opts: resolver.NewOptions(opts...)} return &Resolver{opts: resolver.NewOptions(opts...)}
} }

View File

@ -4,11 +4,13 @@ import (
"github.com/unistack-org/micro/v3/registry" "github.com/unistack-org/micro/v3/registry"
) )
// Options struct
type Options struct { type Options struct {
Handler string Handler string
ServicePrefix string ServicePrefix string
} }
// Option func
type Option func(o *Options) type Option func(o *Options)
// WithHandler sets the handler being used // WithHandler sets the handler being used
@ -27,7 +29,7 @@ func WithServicePrefix(p string) Option {
// NewOptions returns new initialised options // NewOptions returns new initialised options
func NewOptions(opts ...Option) Options { func NewOptions(opts ...Option) Options {
var options Options options := Options{}
for _, o := range opts { for _, o := range opts {
o(&options) o(&options)
} }
@ -51,13 +53,10 @@ func Domain(n string) ResolveOption {
// NewResolveOptions returns new initialised resolve options // NewResolveOptions returns new initialised resolve options
func NewResolveOptions(opts ...ResolveOption) ResolveOptions { func NewResolveOptions(opts ...ResolveOption) ResolveOptions {
var options ResolveOptions options := ResolveOptions{Domain: registry.DefaultDomain}
for _, o := range opts { for _, o := range opts {
o(&options) o(&options)
} }
if len(options.Domain) == 0 {
options.Domain = registry.DefaultDomain
}
return options return options
} }

View File

@ -7,7 +7,9 @@ import (
) )
var ( var (
ErrNotFound = errors.New("not found") // ErrNotFound returned when endpoint is not found
ErrNotFound = errors.New("not found")
// ErrInvalidPath returned on invalid path
ErrInvalidPath = errors.New("invalid path") ErrInvalidPath = errors.New("invalid path")
) )
@ -19,7 +21,7 @@ type Resolver interface {
// Endpoint is the endpoint for a http request // Endpoint is the endpoint for a http request
type Endpoint struct { type Endpoint struct {
// e.g greeter // Endpoint name e.g greeter
Name string Name string
// HTTP Host e.g example.com // HTTP Host e.g example.com
Host string Host string

View File

@ -23,6 +23,7 @@ type Options struct {
Wrappers []Wrapper Wrappers []Wrapper
} }
// NewOptions returns new Options
func NewOptions(opts ...Option) Options { func NewOptions(opts ...Option) Options {
options := Options{} options := Options{}
for _, o := range opts { for _, o := range opts {

View File

@ -4,7 +4,7 @@ package broker
import "context" import "context"
var ( var (
DefaultBroker Broker = &NoopBroker{opts: NewOptions()} DefaultBroker Broker = NewBroker()
) )
// Broker is an interface used for asynchronous messaging. // Broker is an interface used for asynchronous messaging.

View File

@ -2,7 +2,7 @@ package broker
import "context" import "context"
type NoopBroker struct { type noopBroker struct {
opts Options opts Options
} }
@ -11,7 +11,13 @@ type noopSubscriber struct {
opts SubscribeOptions opts SubscribeOptions
} }
func (n *NoopBroker) Init(opts ...Option) error { // NewBroker returns new noop broker
func NewBroker(opts ...Option) Broker {
return &noopBroker{opts: NewOptions(opts...)}
}
// Init initialize broker
func (n *noopBroker) Init(opts ...Option) error {
for _, o := range opts { for _, o := range opts {
o(&n.opts) o(&n.opts)
} }
@ -19,48 +25,53 @@ func (n *NoopBroker) Init(opts ...Option) error {
return nil return nil
} }
func (n *NoopBroker) Options() Options { // Options returns broker Options
func (n *noopBroker) Options() Options {
return n.opts return n.opts
} }
func (n *NoopBroker) Address() string { // Address returns broker address
func (n *noopBroker) Address() string {
return "" return ""
} }
func (n *NoopBroker) Connect(ctx context.Context) error { // Connect connects to broker
func (n *noopBroker) Connect(ctx context.Context) error {
return nil return nil
} }
func (n *NoopBroker) Disconnect(ctx context.Context) error { // Disconnect disconnects from broker
func (n *noopBroker) Disconnect(ctx context.Context) error {
return nil return nil
} }
func (n *NoopBroker) Publish(ctx context.Context, topic string, m *Message, opts ...PublishOption) error { // Publish publishes message to broker
func (n *noopBroker) Publish(ctx context.Context, topic string, m *Message, opts ...PublishOption) error {
return nil return nil
} }
func (n *NoopBroker) Subscribe(ctx context.Context, topic string, h Handler, opts ...SubscribeOption) (Subscriber, error) { // Subscribe subscribes to broker topic
options := NewSubscribeOptions() func (n *noopBroker) Subscribe(ctx context.Context, topic string, h Handler, opts ...SubscribeOption) (Subscriber, error) {
options := NewSubscribeOptions(opts...)
for _, o := range opts {
o(&options)
}
return &noopSubscriber{topic: topic, opts: options}, nil return &noopSubscriber{topic: topic, opts: options}, nil
} }
func (n *NoopBroker) String() string { // String return broker string representation
func (n *noopBroker) String() string {
return "noop" return "noop"
} }
// Options returns subscriber options
func (n *noopSubscriber) Options() SubscribeOptions { func (n *noopSubscriber) Options() SubscribeOptions {
return n.opts return n.opts
} }
// TOpic returns subscriber topic
func (n *noopSubscriber) Topic() string { func (n *noopSubscriber) Topic() string {
return n.topic return n.topic
} }
// Unsubscribe unsbscribes from broker topic
func (n *noopSubscriber) Unsubscribe(ctx context.Context) error { func (n *noopSubscriber) Unsubscribe(ctx context.Context) error {
return nil return nil
} }

View File

@ -9,6 +9,7 @@ import (
"github.com/unistack-org/micro/v3/registry" "github.com/unistack-org/micro/v3/registry"
) )
// Options struct
type Options struct { type Options struct {
Addrs []string Addrs []string
Secure bool Secure bool
@ -27,6 +28,7 @@ type Options struct {
Context context.Context Context context.Context
} }
// NewOptions create new Options
func NewOptions(opts ...Option) Options { func NewOptions(opts ...Option) Options {
options := Options{ options := Options{
Registry: registry.DefaultRegistry, Registry: registry.DefaultRegistry,
@ -39,30 +41,34 @@ func NewOptions(opts ...Option) Options {
return options return options
} }
// Context sets the context option
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
} }
} }
// PublishOptions struct
type PublishOptions struct { type PublishOptions struct {
// Other options for implementations of the interface // Other options for implementations of the interface
// can be stored in a context // can be stored in a context
Context context.Context Context context.Context
} }
// NewPublishOptions creates PublishOptions struct
func NewPublishOptions(opts ...PublishOption) PublishOptions { func NewPublishOptions(opts ...PublishOption) PublishOptions {
opt := PublishOptions{ options := PublishOptions{
Context: context.Background(), Context: context.Background(),
} }
for _, o := range opts { for _, o := range opts {
o(&opt) o(&options)
} }
return opt return options
} }
// SubscribeOptions struct
type SubscribeOptions struct { type SubscribeOptions struct {
// AutoAck ack messages if handler returns nil err // AutoAck ack messages if handler returns nil err
AutoAck bool AutoAck bool
@ -80,30 +86,34 @@ type SubscribeOptions struct {
Context context.Context Context context.Context
} }
// Option func
type Option func(*Options) type Option func(*Options)
// PublishOption func
type PublishOption func(*PublishOptions) type PublishOption func(*PublishOptions)
// PublishContext set context // PublishContext sets the context
func PublishContext(ctx context.Context) PublishOption { func PublishContext(ctx context.Context) PublishOption {
return func(o *PublishOptions) { return func(o *PublishOptions) {
o.Context = ctx o.Context = ctx
} }
} }
// SubscribeOption func
type SubscribeOption func(*SubscribeOptions) type SubscribeOption func(*SubscribeOptions)
// NewSubscribeOptions creates new SubscribeOptions
func NewSubscribeOptions(opts ...SubscribeOption) SubscribeOptions { func NewSubscribeOptions(opts ...SubscribeOption) SubscribeOptions {
opt := SubscribeOptions{ options := SubscribeOptions{
AutoAck: true, AutoAck: true,
Context: context.Background(), Context: context.Background(),
} }
for _, o := range opts { for _, o := range opts {
o(&opt) o(&options)
} }
return opt return options
} }
// Addrs sets the host addresses to be used by the broker // Addrs sets the host addresses to be used by the broker
@ -121,6 +131,7 @@ func Codec(c codec.Marshaler) Option {
} }
} }
// DisableAutoAck disables auto ack
func DisableAutoAck() SubscribeOption { func DisableAutoAck() SubscribeOption {
return func(o *SubscribeOptions) { return func(o *SubscribeOptions) {
o.AutoAck = false o.AutoAck = false
@ -151,6 +162,7 @@ func SubscribeErrorHandler(h Handler) SubscribeOption {
} }
} }
// Queue sets the subscribers sueue
func Queue(name string) SubscribeOption { func Queue(name string) SubscribeOption {
return func(o *SubscribeOptions) { return func(o *SubscribeOptions) {
o.Group = name o.Group = name
@ -164,6 +176,7 @@ func SubscribeGroup(name string) SubscribeOption {
} }
} }
// Registry sets registry option
func Registry(r registry.Registry) Option { func Registry(r registry.Registry) Option {
return func(o *Options) { return func(o *Options) {
o.Registry = r o.Registry = r

View File

@ -1,13 +1,15 @@
package build package build
// Options struct
type Options struct { type Options struct {
// local path to download source // local path to download source
Path string Path string
} }
// Option func
type Option func(o *Options) type Option func(o *Options)
// Local path for repository // Path is the Local path for repository
func Path(p string) Option { func Path(p string) Option {
return func(o *Options) { return func(o *Options) {
o.Path = p o.Path = p

View File

@ -7,6 +7,7 @@ import (
"github.com/unistack-org/micro/v3/util/backoff" "github.com/unistack-org/micro/v3/util/backoff"
) )
// BackoffFunc is the backoff call func
type BackoffFunc func(ctx context.Context, req Request, attempts int) (time.Duration, error) type BackoffFunc func(ctx context.Context, req Request, attempts int) (time.Duration, error)
func exponentialBackoff(ctx context.Context, req Request, attempts int) (time.Duration, error) { func exponentialBackoff(ctx context.Context, req Request, attempts int) (time.Duration, error) {

View File

@ -9,7 +9,7 @@ import (
) )
var ( var (
DefaultClient Client = &NoopClient{opts: NewOptions()} DefaultClient Client = NewClient()
) )
// Client is the interface used to make requests to services. // Client is the interface used to make requests to services.

View File

@ -11,7 +11,7 @@ import (
"github.com/unistack-org/micro/v3/metadata" "github.com/unistack-org/micro/v3/metadata"
) )
type NoopClient struct { type noopClient struct {
opts Options opts Options
} }
@ -31,6 +31,11 @@ type noopRequest struct {
stream bool stream bool
} }
// NewClient returns new noop client
func NewClient(opts ...Option) Client {
return &noopClient{opts: NewOptions(opts...)}
}
func (n *noopRequest) Service() string { func (n *noopRequest) Service() string {
return n.service return n.service
} }
@ -118,49 +123,41 @@ func (n *noopMessage) ContentType() string {
return n.opts.ContentType return n.opts.ContentType
} }
func (n *NoopClient) Init(opts ...Option) error { func (n *noopClient) Init(opts ...Option) error {
for _, o := range opts { for _, o := range opts {
o(&n.opts) o(&n.opts)
} }
return nil return nil
} }
func (n *NoopClient) Options() Options { func (n *noopClient) Options() Options {
return n.opts return n.opts
} }
func (n *NoopClient) String() string { func (n *noopClient) String() string {
return "noop" return "noop"
} }
func (n *NoopClient) Call(ctx context.Context, req Request, rsp interface{}, opts ...CallOption) error { func (n *noopClient) Call(ctx context.Context, req Request, rsp interface{}, opts ...CallOption) error {
return nil return nil
} }
func (n *NoopClient) NewRequest(service, endpoint string, req interface{}, opts ...RequestOption) Request { func (n *noopClient) NewRequest(service, endpoint string, req interface{}, opts ...RequestOption) Request {
return &noopRequest{} return &noopRequest{}
} }
func (n *NoopClient) NewMessage(topic string, msg interface{}, opts ...MessageOption) Message { func (n *noopClient) NewMessage(topic string, msg interface{}, opts ...MessageOption) Message {
options := MessageOptions{} options := NewMessageOptions(opts...)
for _, o := range opts {
o(&options)
}
return &noopMessage{topic: topic, payload: msg, opts: options} return &noopMessage{topic: topic, payload: msg, opts: options}
} }
func (n *NoopClient) Stream(ctx context.Context, req Request, opts ...CallOption) (Stream, error) { func (n *noopClient) Stream(ctx context.Context, req Request, opts ...CallOption) (Stream, error) {
return &noopStream{}, nil return &noopStream{}, nil
} }
func (n *NoopClient) Publish(ctx context.Context, p Message, opts ...PublishOption) error { func (n *noopClient) Publish(ctx context.Context, p Message, opts ...PublishOption) error {
var body []byte var body []byte
if err := n.opts.Broker.Connect(ctx); err != nil {
return errors.InternalServerError("go.micro.client", err.Error())
}
options := NewPublishOptions(opts...) options := NewPublishOptions(opts...)
md, ok := metadata.FromContext(ctx) md, ok := metadata.FromContext(ctx)
@ -208,11 +205,3 @@ func (n *NoopClient) Publish(ctx context.Context, p Message, opts ...PublishOpti
return nil return nil
} }
func newClient(opts ...Option) Client {
options := NewOptions()
for _, o := range opts {
o(&options)
}
return &NoopClient{opts: options}
}

View File

@ -8,14 +8,13 @@ import (
"testing" "testing"
rmemory "github.com/unistack-org/micro-registry-memory" rmemory "github.com/unistack-org/micro-registry-memory"
"github.com/unistack-org/micro/v3/util/test"
) )
func TestFunction(t *testing.T) { func TestFunction(t *testing.T) {
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(1) wg.Add(1)
r := rmemory.NewRegistry(rmemory.Services(test.Data)) r := rmemory.NewRegistry()
// create service // create service
fn := NewFunction( fn := NewFunction(

View File

@ -14,9 +14,11 @@ type metadataKey struct{}
type Metadata map[string]string type Metadata map[string]string
var ( var (
// DefaultMetadataSize used when need to init new Metadata
DefaultMetadataSize = 6 DefaultMetadataSize = 6
) )
// Get returns value from metadata by key
func (md Metadata) Get(key string) (string, bool) { func (md Metadata) Get(key string) (string, bool) {
// fast path // fast path
val, ok := md[key] val, ok := md[key]
@ -27,10 +29,12 @@ func (md Metadata) Get(key string) (string, bool) {
return val, ok return val, ok
} }
// Set is used to store value in metadata
func (md Metadata) Set(key, val string) { func (md Metadata) Set(key, val string) {
md[textproto.CanonicalMIMEHeaderKey(key)] = val md[textproto.CanonicalMIMEHeaderKey(key)] = val
} }
// Del is used to remove value from metadata
func (md Metadata) Del(key string) { func (md Metadata) Del(key string) {
// fast path // fast path
if _, ok := md[key]; ok { if _, ok := md[key]; ok {

View File

@ -8,6 +8,7 @@ import (
"github.com/unistack-org/micro/v3/router" "github.com/unistack-org/micro/v3/router"
) )
// Option func
type Option func(*Options) type Option func(*Options)
// Options configure network // Options configure network

View File

@ -1,31 +1,35 @@
package transport package transport
type NoopTransport struct { type noopTransport struct {
opts Options opts Options
} }
func (t *NoopTransport) Init(opts ...Option) error { func NewTransport(opts ...Option) Transport {
return &noopTransport{opts: NewOptions(opts...)}
}
func (t *noopTransport) Init(opts ...Option) error {
for _, o := range opts { for _, o := range opts {
o(&t.opts) o(&t.opts)
} }
return nil return nil
} }
func (t *NoopTransport) Options() Options { func (t *noopTransport) Options() Options {
return t.opts return t.opts
} }
func (t *NoopTransport) Dial(addr string, opts ...DialOption) (Client, error) { func (t *noopTransport) Dial(addr string, opts ...DialOption) (Client, error) {
options := NewDialOptions(opts...) options := NewDialOptions(opts...)
return &noopClient{opts: options}, nil return &noopClient{opts: options}, nil
} }
func (t *NoopTransport) Listen(addr string, opts ...ListenOption) (Listener, error) { func (t *noopTransport) Listen(addr string, opts ...ListenOption) (Listener, error) {
options := NewListenOptions(opts...) options := NewListenOptions(opts...)
return &noopListener{opts: options}, nil return &noopListener{opts: options}, nil
} }
func (t *NoopTransport) String() string { func (t *noopTransport) String() string {
return "noop" return "noop"
} }

View File

@ -6,7 +6,8 @@ import (
) )
var ( var (
DefaultTransport Transport = &NoopTransport{opts: NewOptions()} // DefaultTransport is the global default transport
DefaultTransport Transport = NewTransport()
) )
// Transport is an interface which is used for communication between // Transport is an interface which is used for communication between

View File

@ -15,6 +15,7 @@ var (
DefaultToken = "go.micro.tunnel" DefaultToken = "go.micro.tunnel"
) )
// Option func
type Option func(*Options) type Option func(*Options)
// Options provides network configuration options // Options provides network configuration options
@ -33,8 +34,10 @@ type Options struct {
Logger logger.Logger Logger logger.Logger
} }
// DialOption func
type DialOption func(*DialOptions) type DialOption func(*DialOptions)
// DialOptions provides dial options
type DialOptions struct { type DialOptions struct {
// Link specifies the link to use // Link specifies the link to use
Link string Link string
@ -46,8 +49,10 @@ type DialOptions struct {
Timeout time.Duration Timeout time.Duration
} }
// ListenOption func
type ListenOption func(*ListenOptions) type ListenOption func(*ListenOptions)
// ListenOptions provides listen options
type ListenOptions struct { type ListenOptions struct {
// specify mode of the session // specify mode of the session
Mode Mode Mode Mode
@ -55,7 +60,7 @@ type ListenOptions struct {
Timeout time.Duration Timeout time.Duration
} }
// The tunnel id // Id sets the tunnel id
func Id(id string) Option { func Id(id string) Option {
return func(o *Options) { return func(o *Options) {
o.Id = id o.Id = id
@ -69,7 +74,7 @@ func Logger(l logger.Logger) Option {
} }
} }
// The tunnel address // Address sets the tunnel address
func Address(a string) Option { func Address(a string) Option {
return func(o *Options) { return func(o *Options) {
o.Address = a o.Address = a
@ -97,23 +102,21 @@ func Transport(t transport.Transport) Option {
} }
} }
// Listen options // ListenMode option
func ListenMode(m Mode) ListenOption { func ListenMode(m Mode) ListenOption {
return func(o *ListenOptions) { return func(o *ListenOptions) {
o.Mode = m o.Mode = m
} }
} }
// Timeout for reads and writes on the listener session // ListenTimeout for reads and writes on the listener session
func ListenTimeout(t time.Duration) ListenOption { func ListenTimeout(t time.Duration) ListenOption {
return func(o *ListenOptions) { return func(o *ListenOptions) {
o.Timeout = t o.Timeout = t
} }
} }
// Dial options // DialMode multicast sets the multicast option to send only to those mapped
// Dial multicast sets the multicast option to send only to those mapped
func DialMode(m Mode) DialOption { func DialMode(m Mode) DialOption {
return func(o *DialOptions) { return func(o *DialOptions) {
o.Mode = m o.Mode = m
@ -144,10 +147,14 @@ func DialWait(b bool) DialOption {
} }
// DefaultOptions returns router default options // DefaultOptions returns router default options
func DefaultOptions() Options { func NewOptions(opts ...Option) Options {
return Options{ options := Options{
Id: uuid.New().String(), Id: uuid.New().String(),
Address: DefaultAddress, Address: DefaultAddress,
Token: DefaultToken, Token: DefaultToken,
} }
for _, o := range opts {
o(&options)
}
return options
} }

View File

@ -93,7 +93,7 @@ func NewTransport(opts ...transport.Option) transport.Transport {
return t return t
} }
// WithTransport sets the internal tunnel // WithTunnel sets the internal tunnel
func WithTunnel(t tunnel.Tunnel) transport.Option { func WithTunnel(t tunnel.Tunnel) transport.Option {
return func(o *transport.Options) { return func(o *transport.Options) {
if o.Context == nil { if o.Context == nil {

View File

@ -49,6 +49,7 @@ type Options struct {
Context context.Context Context context.Context
} }
// NewOptions returns new Options filled with defaults and overrided by provided opts
func NewOptions(opts ...Option) Options { func NewOptions(opts ...Option) Options {
options := Options{ options := Options{
Context: context.Background(), Context: context.Background(),
@ -73,6 +74,7 @@ func NewOptions(opts ...Option) Options {
return options return options
} }
// Option func
type Option func(*Options) type Option func(*Options)
// Broker to be used for service // Broker to be used for service

View File

@ -6,6 +6,7 @@ import (
"strings" "strings"
) )
// Extract *Value from reflect.Type
func ExtractValue(v reflect.Type, d int) *Value { func ExtractValue(v reflect.Type, d int) *Value {
if d == 3 { if d == 3 {
return nil return nil
@ -59,6 +60,7 @@ func ExtractValue(v reflect.Type, d int) *Value {
return arg return arg
} }
// ExtractEndpoint extract *Endpoint from reflect.Method
func ExtractEndpoint(method reflect.Method) *Endpoint { func ExtractEndpoint(method reflect.Method) *Endpoint {
if method.PkgPath != "" { if method.PkgPath != "" {
return nil return nil
@ -104,6 +106,7 @@ func ExtractEndpoint(method reflect.Method) *Endpoint {
return ep return ep
} }
// ExtractSubValue exctact *Value from reflect.Type
func ExtractSubValue(typ reflect.Type) *Value { func ExtractSubValue(typ reflect.Type) *Value {
var reqType reflect.Type var reqType reflect.Type
switch typ.NumIn() { switch typ.NumIn() {

View File

@ -5,55 +5,64 @@ import (
"fmt" "fmt"
) )
type NoopRegistry struct { type noopRegistry struct {
opts Options opts Options
} }
func (n *NoopRegistry) Init(opts ...Option) error { // Init initialize registry
func (n *noopRegistry) Init(opts ...Option) error {
for _, o := range opts { for _, o := range opts {
o(&n.opts) o(&n.opts)
} }
return nil return nil
} }
func (n *NoopRegistry) Options() Options { // Options returns options struct
func (n *noopRegistry) Options() Options {
return n.opts return n.opts
} }
func (n *NoopRegistry) Connect(ctx context.Context) error { // Connect opens connection to registry
func (n *noopRegistry) Connect(ctx context.Context) error {
return nil return nil
} }
func (n *NoopRegistry) Disconnect(ctx context.Context) error { // Disconnect close connection to registry
func (n *noopRegistry) Disconnect(ctx context.Context) error {
return nil return nil
} }
func (n *NoopRegistry) Register(*Service, ...RegisterOption) error { // Register registers service
func (n *noopRegistry) Register(*Service, ...RegisterOption) error {
return nil return nil
} }
func (n *NoopRegistry) Deregister(*Service, ...DeregisterOption) error { // Deregister deregisters service
func (n *noopRegistry) Deregister(*Service, ...DeregisterOption) error {
return nil return nil
} }
func (n *NoopRegistry) GetService(string, ...GetOption) ([]*Service, error) { // GetService returns servive info
func (n *noopRegistry) GetService(string, ...GetOption) ([]*Service, error) {
return []*Service{}, nil return []*Service{}, nil
} }
func (n *NoopRegistry) ListServices(...ListOption) ([]*Service, error) { // ListServices listing services
func (n *noopRegistry) ListServices(...ListOption) ([]*Service, error) {
return []*Service{}, nil return []*Service{}, nil
} }
func (n *NoopRegistry) Watch(...WatchOption) (Watcher, error) { // Watch is used to watch for service changes
func (n *noopRegistry) Watch(...WatchOption) (Watcher, error) {
return nil, fmt.Errorf("not implemented") return nil, fmt.Errorf("not implemented")
} }
func (n *NoopRegistry) String() string { // String returns registry string representation
func (n *noopRegistry) String() string {
return "noop" return "noop"
} }
// NewRegistry returns a new noop registry // NewRegistry returns a new noop registry
func NewRegistry(opts ...Option) Registry { func NewRegistry(opts ...Option) Registry {
options := NewOptions(opts...) return &noopRegistry{opts: NewOptions(opts...)}
return &NoopRegistry{opts: options}
} }

View File

@ -14,6 +14,7 @@ const (
) )
var ( var (
// DefaultRegistry is the global default registry
DefaultRegistry Registry = NewRegistry() DefaultRegistry Registry = NewRegistry()
// ErrNotFound returned when GetService is called and no services found // ErrNotFound returned when GetService is called and no services found
ErrNotFound = errors.New("service not found") ErrNotFound = errors.New("service not found")

View File

@ -6,6 +6,7 @@ import (
) )
var ( var (
// DefaultRouter is the global default router
DefaultRouter Router DefaultRouter Router
// DefaultNetwork is default micro network // DefaultNetwork is default micro network
DefaultNetwork = "micro" DefaultNetwork = "micro"

View File

@ -7,6 +7,7 @@ import (
) )
var ( var (
// ErrAlreadyExists error
ErrAlreadyExists = errors.New("already exists") ErrAlreadyExists = errors.New("already exists")
) )

View File

@ -6,11 +6,13 @@ import (
type serverKey struct{} type serverKey struct{}
// FromContext returns Server from context
func FromContext(ctx context.Context) (Server, bool) { func FromContext(ctx context.Context) (Server, bool) {
c, ok := ctx.Value(serverKey{}).(Server) c, ok := ctx.Value(serverKey{}).(Server)
return c, ok return c, ok
} }
// NewContext stores Server to context
func NewContext(ctx context.Context, s Server) context.Context { func NewContext(ctx context.Context, s Server) context.Context {
return context.WithValue(ctx, serverKey{}, s) return context.WithValue(ctx, serverKey{}, s)
} }

View File

@ -32,7 +32,7 @@ const (
defaultContentType = "application/json" defaultContentType = "application/json"
) )
type NoopServer struct { type noopServer struct {
h Handler h Handler
opts Options opts Options
rsvc *registry.Service rsvc *registry.Service
@ -45,7 +45,12 @@ type NoopServer struct {
sync.RWMutex sync.RWMutex
} }
func (n *NoopServer) newCodec(contentType string) (codec.NewCodec, error) { // NewServer returns new noop server
func NewServer(opts ...Option) Server {
return &noopServer{opts: NewOptions(opts...)}
}
func (n *noopServer) newCodec(contentType string) (codec.NewCodec, error) {
if cf, ok := n.opts.Codecs[contentType]; ok { if cf, ok := n.opts.Codecs[contentType]; ok {
return cf, nil return cf, nil
} }
@ -55,12 +60,12 @@ func (n *NoopServer) newCodec(contentType string) (codec.NewCodec, error) {
return nil, fmt.Errorf("Unsupported Content-Type: %s", contentType) return nil, fmt.Errorf("Unsupported Content-Type: %s", contentType)
} }
func (n *NoopServer) Handle(handler Handler) error { func (n *noopServer) Handle(handler Handler) error {
n.h = handler n.h = handler
return nil return nil
} }
func (n *NoopServer) Subscribe(sb Subscriber) error { func (n *noopServer) Subscribe(sb Subscriber) error {
sub, ok := sb.(*subscriber) sub, ok := sb.(*subscriber)
if !ok { if !ok {
return fmt.Errorf("invalid subscriber: expected *subscriber") return fmt.Errorf("invalid subscriber: expected *subscriber")
@ -84,15 +89,15 @@ func (n *NoopServer) Subscribe(sb Subscriber) error {
return nil return nil
} }
func (n *NoopServer) NewHandler(h interface{}, opts ...HandlerOption) Handler { func (n *noopServer) NewHandler(h interface{}, opts ...HandlerOption) Handler {
return newRpcHandler(h, opts...) return newRpcHandler(h, opts...)
} }
func (n *NoopServer) NewSubscriber(topic string, sb interface{}, opts ...SubscriberOption) Subscriber { func (n *noopServer) NewSubscriber(topic string, sb interface{}, opts ...SubscriberOption) Subscriber {
return newSubscriber(topic, sb, opts...) return newSubscriber(topic, sb, opts...)
} }
func (n *NoopServer) Init(opts ...Option) error { func (n *noopServer) Init(opts ...Option) error {
for _, o := range opts { for _, o := range opts {
o(&n.opts) o(&n.opts)
} }
@ -110,15 +115,15 @@ func (n *NoopServer) Init(opts ...Option) error {
return nil return nil
} }
func (n *NoopServer) Options() Options { func (n *noopServer) Options() Options {
return n.opts return n.opts
} }
func (n *NoopServer) String() string { func (n *noopServer) String() string {
return "noop" return "noop"
} }
func (n *NoopServer) Register() error { func (n *noopServer) Register() error {
n.RLock() n.RLock()
rsvc := n.rsvc rsvc := n.rsvc
config := n.opts config := n.opts
@ -233,7 +238,7 @@ func (n *NoopServer) Register() error {
return nil return nil
} }
func (n *NoopServer) Deregister() error { func (n *noopServer) Deregister() error {
var err error var err error
n.RLock() n.RLock()
@ -293,7 +298,7 @@ func (n *NoopServer) Deregister() error {
return nil return nil
} }
func (n *NoopServer) Start() error { func (n *noopServer) Start() error {
n.RLock() n.RLock()
if n.started { if n.started {
n.RUnlock() n.RUnlock()
@ -433,7 +438,7 @@ func (n *NoopServer) Start() error {
return nil return nil
} }
func (n *NoopServer) Stop() error { func (n *noopServer) Stop() error {
n.RLock() n.RLock()
if !n.started { if !n.started {
n.RUnlock() n.RUnlock()

View File

@ -85,7 +85,7 @@ func NewOptions(opts ...Option) Options {
return options return options
} }
// Server name // Name sets the server name option
func Name(n string) Option { func Name(n string) Option {
return func(o *Options) { return func(o *Options) {
o.Name = n o.Name = n
@ -99,7 +99,7 @@ func Namespace(n string) Option {
} }
} }
// Logger // Logger sets the logger option
func Logger(l logger.Logger) Option { func Logger(l logger.Logger) Option {
return func(o *Options) { return func(o *Options) {
o.Logger = l o.Logger = l
@ -127,7 +127,7 @@ func Address(a string) Option {
} }
} }
// The address to advertise for discovery - host:port // Advertise the address to advertise for discovery - host:port
func Advertise(a string) Option { func Advertise(a string) Option {
return func(o *Options) { return func(o *Options) {
o.Advertise = a o.Advertise = a
@ -199,14 +199,14 @@ func RegisterCheck(fn func(context.Context) error) Option {
} }
} }
// Register the service with a TTL // RegisterTTL registers service with a TTL
func RegisterTTL(t time.Duration) Option { func RegisterTTL(t time.Duration) Option {
return func(o *Options) { return func(o *Options) {
o.RegisterTTL = t o.RegisterTTL = t
} }
} }
// Register the service with at interval // RegisterInterval registers service with at interval
func RegisterInterval(t time.Duration) Option { func RegisterInterval(t time.Duration) Option {
return func(o *Options) { return func(o *Options) {
o.RegisterInterval = t o.RegisterInterval = t
@ -250,28 +250,31 @@ func Wait(wg *sync.WaitGroup) Option {
} }
} }
// Adds a handler Wrapper to a list of options passed into the server // WrapHandler adds a handler Wrapper to a list of options passed into the server
func WrapHandler(w HandlerWrapper) Option { func WrapHandler(w HandlerWrapper) Option {
return func(o *Options) { return func(o *Options) {
o.HdlrWrappers = append(o.HdlrWrappers, w) o.HdlrWrappers = append(o.HdlrWrappers, w)
} }
} }
// Adds a subscriber Wrapper to a list of options passed into the server // WrapSubscriber adds a subscriber Wrapper to a list of options passed into the server
func WrapSubscriber(w SubscriberWrapper) Option { func WrapSubscriber(w SubscriberWrapper) Option {
return func(o *Options) { return func(o *Options) {
o.SubWrappers = append(o.SubWrappers, w) o.SubWrappers = append(o.SubWrappers, w)
} }
} }
// HandlerOption func
type HandlerOption func(*HandlerOptions) type HandlerOption func(*HandlerOptions)
// HandlerOptions struct
type HandlerOptions struct { type HandlerOptions struct {
Internal bool Internal bool
Metadata map[string]map[string]string Metadata map[string]map[string]string
Context context.Context Context context.Context
} }
// NewHandlerOptions creates new HandlerOptions
func NewHandlerOptions(opts ...HandlerOption) HandlerOptions { func NewHandlerOptions(opts ...HandlerOption) HandlerOptions {
options := HandlerOptions{ options := HandlerOptions{
Context: context.Background(), Context: context.Background(),
@ -284,8 +287,10 @@ func NewHandlerOptions(opts ...HandlerOption) HandlerOptions {
return options return options
} }
// SubscriberOption func
type SubscriberOption func(*SubscriberOptions) type SubscriberOption func(*SubscriberOptions)
// SubscriberOptions struct
type SubscriberOptions struct { type SubscriberOptions struct {
// AutoAck defaults to true. When a handler returns // AutoAck defaults to true. When a handler returns
// with a nil error the message is acked. // with a nil error the message is acked.
@ -295,6 +300,7 @@ type SubscriberOptions struct {
Context context.Context Context context.Context
} }
// NewSubscriberOptions create new SubscriberOptions
func NewSubscriberOptions(opts ...SubscriberOption) SubscriberOptions { func NewSubscriberOptions(opts ...SubscriberOption) SubscriberOptions {
options := SubscriberOptions{ options := SubscriberOptions{
AutoAck: true, AutoAck: true,
@ -316,7 +322,7 @@ func EndpointMetadata(name string, md map[string]string) HandlerOption {
} }
} }
// Internal Handler options specifies that a handler is not advertised // InternalHandler options specifies that a handler is not advertised
// to the discovery system. In the future this may also limit request // to the discovery system. In the future this may also limit request
// to the internal network or authorised user. // to the internal network or authorised user.
func InternalHandler(b bool) HandlerOption { func InternalHandler(b bool) HandlerOption {
@ -325,7 +331,7 @@ func InternalHandler(b bool) HandlerOption {
} }
} }
// Internal Subscriber options specifies that a subscriber is not advertised // InternalSubscriber options specifies that a subscriber is not advertised
// to the discovery system. // to the discovery system.
func InternalSubscriber(b bool) SubscriberOption { func InternalSubscriber(b bool) SubscriberOption {
return func(o *SubscriberOptions) { return func(o *SubscriberOptions) {
@ -341,7 +347,7 @@ func DisableAutoAck() SubscriberOption {
} }
} }
// Shared queue name distributed messages across subscribers // SubscriberQueue sets the shared queue name distributed messages across subscribers
func SubscriberQueue(n string) SubscriberOption { func SubscriberQueue(n string) SubscriberOption {
return func(o *SubscriberOptions) { return func(o *SubscriberOptions) {
o.Queue = n o.Queue = n

View File

@ -52,6 +52,7 @@ var (
} }
) )
// NewRegistryService returns *registry.Service from Server
func NewRegistryService(s Server) (*registry.Service, error) { func NewRegistryService(s Server) (*registry.Service, error) {
opts := s.Options() opts := s.Options()

View File

@ -11,7 +11,7 @@ import (
) )
var ( var (
DefaultServer Server = &NoopServer{opts: NewOptions()} DefaultServer Server = NewServer()
) )
// Server is a simple micro server abstraction // Server is a simple micro server abstraction

View File

@ -59,6 +59,7 @@ func isExportedOrBuiltinType(t reflect.Type) bool {
return isExported(t.Name()) || t.PkgPath() == "" return isExported(t.Name()) || t.PkgPath() == ""
} }
// ValidateSubscriber func
func ValidateSubscriber(sub Subscriber) error { func ValidateSubscriber(sub Subscriber) error {
typ := reflect.TypeOf(sub.Subscriber()) typ := reflect.TypeOf(sub.Subscriber())
var argType reflect.Type var argType reflect.Type
@ -184,7 +185,7 @@ func newSubscriber(topic string, sub interface{}, opts ...SubscriberOption) Subs
} }
} }
func (n *NoopServer) createSubHandler(sb *subscriber, opts Options) broker.Handler { func (n *noopServer) createSubHandler(sb *subscriber, opts Options) broker.Handler {
return func(p broker.Event) (err error) { return func(p broker.Event) (err error) {
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {

View File

@ -2,45 +2,58 @@ package store
import "context" import "context"
type NoopStore struct { type noopStore struct {
opts Options opts Options
} }
func (n *NoopStore) Init(opts ...Option) error { func NewStore(opts ...Option) Store {
return &noopStore{opts: NewOptions(opts...)}
}
// Init initialize store
func (n *noopStore) Init(opts ...Option) error {
for _, o := range opts { for _, o := range opts {
o(&n.opts) o(&n.opts)
} }
return nil return nil
} }
func (n *NoopStore) Options() Options { // Options returns Options struct
func (n *noopStore) Options() Options {
return n.opts return n.opts
} }
func (n *NoopStore) String() string { // String returns string representation
func (n *noopStore) String() string {
return "noop" return "noop"
} }
func (n *NoopStore) Read(ctx context.Context, key string, opts ...ReadOption) ([]*Record, error) { // Read reads store value by key
func (n *noopStore) Read(ctx context.Context, key string, opts ...ReadOption) ([]*Record, error) {
return []*Record{}, nil return []*Record{}, nil
} }
func (n *NoopStore) Write(ctx context.Context, r *Record, opts ...WriteOption) error { // Write writes store record
func (n *noopStore) Write(ctx context.Context, r *Record, opts ...WriteOption) error {
return nil return nil
} }
func (n *NoopStore) Delete(ctx context.Context, key string, opts ...DeleteOption) error { // Delete removes store value by key
func (n *noopStore) Delete(ctx context.Context, key string, opts ...DeleteOption) error {
return nil return nil
} }
func (n *NoopStore) List(ctx context.Context, opts ...ListOption) ([]string, error) { // List lists store
func (n *noopStore) List(ctx context.Context, opts ...ListOption) ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (n *NoopStore) Connect(ctx context.Context) error { // Connect connects to store
func (n *noopStore) Connect(ctx context.Context) error {
return nil return nil
} }
func (n *NoopStore) Disconnect(ctx context.Context) error { // Disconnect disconnects from store
func (n *noopStore) Disconnect(ctx context.Context) error {
return nil return nil
} }

View File

@ -10,14 +10,16 @@ import (
var ( var (
// ErrNotFound is returned when a key doesn't exist // ErrNotFound is returned when a key doesn't exist
ErrNotFound = errors.New("not found") ErrNotFound = errors.New("not found")
DefaultStore Store = &NoopStore{opts: NewOptions()} // DefaultStore is the global default store
DefaultStore Store = NewStore()
) )
// Store is a data storage interface // Store is a data storage interface
type Store interface { type Store interface {
// Init initialises the store. It must perform any required setup on the backing storage implementation and check that it is ready for use, returning any errors. // Init initialises the store. It must perform any required setup on the backing storage implementation and check that it is ready for use, returning any errors.
Init(opts ...Option) error Init(opts ...Option) error
// Connect is used when store needs to be connected
Connect(ctx context.Context) error Connect(ctx context.Context) error
// Options allows you to view the current options. // Options allows you to view the current options.
Options() Options Options() Options

View File

@ -1,10 +1,12 @@
package tracer package tracer
// Options struct
type Options struct { type Options struct {
// Size is the size of ring buffer // Size is the size of ring buffer
Size int Size int
} }
// Option func
type Option func(o *Options) type Option func(o *Options)
type ReadOptions struct { type ReadOptions struct {
@ -12,9 +14,10 @@ type ReadOptions struct {
Trace string Trace string
} }
// ReadOption func
type ReadOption func(o *ReadOptions) type ReadOption func(o *ReadOptions)
// Read the given trace // ReadTracer read the given trace
func ReadTrace(t string) ReadOption { func ReadTrace(t string) ReadOption {
return func(o *ReadOptions) { return func(o *ReadOptions) {
o.Trace = t o.Trace = t

View File

@ -2,12 +2,15 @@ package http
import "github.com/unistack-org/micro/v3/router" import "github.com/unistack-org/micro/v3/router"
// Options struct
type Options struct { type Options struct {
Router router.Router Router router.Router
} }
// Option func
type Option func(*Options) type Option func(*Options)
// WithRouter sets the router.Router option
func WithRouter(r router.Router) Option { func WithRouter(r router.Router) Option {
return func(o *Options) { return func(o *Options) {
o.Router = r o.Router = r

View File

@ -1,13 +0,0 @@
package signal
import (
"os"
"syscall"
)
// ShutDownSignals returns all the signals that are being watched for to shut down services.
func Shutdown() []os.Signal {
return []os.Signal{
syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL,
}
}

View File

@ -1,47 +0,0 @@
package test
import (
"github.com/unistack-org/micro/v3/registry"
)
var (
// mock registry data
Data = map[string][]*registry.Service{
"foo": {
{
Name: "foo",
Version: "1.0.0",
Nodes: []*registry.Node{
{
Id: "foo-1.0.0-123",
Address: "localhost:9999",
},
{
Id: "foo-1.0.0-321",
Address: "localhost:9999",
},
},
},
{
Name: "foo",
Version: "1.0.1",
Nodes: []*registry.Node{
{
Id: "foo-1.0.1-321",
Address: "localhost:6666",
},
},
},
{
Name: "foo",
Version: "1.0.3",
Nodes: []*registry.Node{
{
Id: "foo-1.0.3-345",
Address: "localhost:8888",
},
},
},
},
}
)