micro/options.go
2016-01-26 23:32:27 +00:00

151 lines
2.7 KiB
Go

package micro
import (
"time"
"github.com/micro/cli"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/cmd"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/server"
"github.com/micro/go-micro/transport"
"golang.org/x/net/context"
)
type Options struct {
Broker broker.Broker
Cmd cmd.Cmd
Client client.Client
Server server.Server
Registry registry.Registry
Transport transport.Transport
// Registration options
RegisterTTL time.Duration
RegisterInterval time.Duration
// Before and After funcs
BeforeStart []func() error
AfterStop []func() error
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
}
func newOptions(opts ...Option) Options {
opt := Options{
Broker: broker.DefaultBroker,
Cmd: cmd.DefaultCmd,
Client: client.DefaultClient,
Server: server.DefaultServer,
Registry: registry.DefaultRegistry,
Transport: transport.DefaultTransport,
}
for _, o := range opts {
o(&opt)
}
return opt
}
func Broker(b broker.Broker) Option {
return func(o *Options) {
o.Broker = b
}
}
func Cmd(c cmd.Cmd) Option {
return func(o *Options) {
o.Cmd = c
}
}
func Client(c client.Client) Option {
return func(o *Options) {
o.Client = c
}
}
func Server(s server.Server) Option {
return func(o *Options) {
o.Server = s
}
}
func Registry(r registry.Registry) Option {
return func(o *Options) {
o.Registry = r
}
}
func Transport(t transport.Transport) Option {
return func(o *Options) {
o.Transport = t
}
}
// Convenience options
// Name of the service
func Name(n string) Option {
return func(o *Options) {
o.Server.Init(server.Name(n))
}
}
// Version of the service
func Version(v string) Option {
return func(o *Options) {
o.Server.Init(server.Version(v))
}
}
// Metadata associated with the service
func Metadata(md map[string]string) Option {
return func(o *Options) {
o.Server.Init(server.Metadata(md))
}
}
func Flags(flags ...cli.Flag) Option {
return func(o *Options) {
o.Cmd.App().Flags = append(o.Cmd.App().Flags, flags...)
}
}
func Action(a func(*cli.Context)) Option {
return func(o *Options) {
o.Cmd.App().Action = a
}
}
func RegisterTTL(t time.Duration) Option {
return func(o *Options) {
o.RegisterTTL = t
}
}
func RegisterInterval(t time.Duration) Option {
return func(o *Options) {
o.RegisterInterval = t
}
}
// Before and Afters
func BeforeStart(fn func() error) Option {
return func(o *Options) {
o.BeforeStart = append(o.BeforeStart, fn)
}
}
func AfterStop(fn func() error) Option {
return func(o *Options) {
o.AfterStop = append(o.AfterStop, fn)
}
}