go-micro.dev/v5@v5.12.0/micro.go (about) 1 // Package micro is a pluggable framework for microservices 2 package micro 3 4 import ( 5 "context" 6 7 "go-micro.dev/v5/client" 8 "go-micro.dev/v5/server" 9 "go-micro.dev/v5/service" 10 ) 11 12 type serviceKey struct{} 13 14 // Service is an interface that wraps the lower level libraries 15 // within go-micro. Its a convenience method for building 16 // and initializing services. 17 type Service interface { 18 // The service name 19 Name() string 20 // Init initializes options 21 Init(...Option) 22 // Options returns the current options 23 Options() Options 24 // Register the handler 25 Handle(v interface{}) error 26 // Client is used to call services 27 Client() client.Client 28 // Server is for handling requests and events 29 Server() server.Server 30 // Run the service 31 Run() error 32 // The service implementation 33 String() string 34 } 35 36 type Option = service.Option 37 38 type Options = service.Options 39 40 // Event is used to publish messages to a topic. 41 type Event interface { 42 // Publish publishes a message to the event topic 43 Publish(ctx context.Context, msg interface{}, opts ...client.PublishOption) error 44 } 45 46 // Type alias to satisfy the deprecation. 47 type Publisher = Event 48 49 // New represents the new service 50 func New(name string) Service { 51 return NewService( 52 service.Name(name), 53 ) 54 } 55 56 // NewService creates and returns a new Service based on the packages within. 57 func NewService(opts ...Option) Service { 58 return service.New(opts...) 59 } 60 61 // FromContext retrieves a Service from the Context. 62 func FromContext(ctx context.Context) (Service, bool) { 63 s, ok := ctx.Value(serviceKey{}).(Service) 64 return s, ok 65 } 66 67 // NewContext returns a new Context with the Service embedded within it. 68 func NewContext(ctx context.Context, s Service) context.Context { 69 return context.WithValue(ctx, serviceKey{}, s) 70 } 71 72 // NewEvent creates a new event publisher. 73 func NewEvent(topic string, c client.Client) Event { 74 if c == nil { 75 c = client.NewClient() 76 } 77 78 return &event{c, topic} 79 } 80 81 // RegisterHandler is syntactic sugar for registering a handler. 82 func RegisterHandler(s server.Server, h interface{}, opts ...server.HandlerOption) error { 83 return s.Handle(s.NewHandler(h, opts...)) 84 } 85 86 // RegisterSubscriber is syntactic sugar for registering a subscriber. 87 func RegisterSubscriber(topic string, s server.Server, h interface{}, opts ...server.SubscriberOption) error { 88 return s.Subscribe(s.NewSubscriber(topic, h, opts...)) 89 }