github.com/annwntech/go-micro/v2@v2.9.5/service/grpc/grpc.go (about) 1 package grpc 2 3 import ( 4 "github.com/annwntech/go-micro/v2/client" 5 gclient "github.com/annwntech/go-micro/v2/client/grpc" 6 "github.com/annwntech/go-micro/v2/server" 7 gserver "github.com/annwntech/go-micro/v2/server/grpc" 8 "github.com/annwntech/go-micro/v2/service" 9 ) 10 11 type grpcService struct { 12 opts service.Options 13 } 14 15 func newService(opts ...service.Option) service.Service { 16 options := service.NewOptions(opts...) 17 18 return &grpcService{ 19 opts: options, 20 } 21 } 22 23 func (s *grpcService) Name() string { 24 return s.opts.Server.Options().Name 25 } 26 27 // Init initialises options. Additionally it calls cmd.Init 28 // which parses command line flags. cmd.Init is only called 29 // on first Init. 30 func (s *grpcService) Init(opts ...service.Option) { 31 // process options 32 for _, o := range opts { 33 o(&s.opts) 34 } 35 } 36 37 func (s *grpcService) Options() service.Options { 38 return s.opts 39 } 40 41 func (s *grpcService) Client() client.Client { 42 return s.opts.Client 43 } 44 45 func (s *grpcService) Server() server.Server { 46 return s.opts.Server 47 } 48 49 func (s *grpcService) String() string { 50 return "grpc" 51 } 52 53 func (s *grpcService) Start() error { 54 for _, fn := range s.opts.BeforeStart { 55 if err := fn(); err != nil { 56 return err 57 } 58 } 59 60 if err := s.opts.Server.Start(); err != nil { 61 return err 62 } 63 64 for _, fn := range s.opts.AfterStart { 65 if err := fn(); err != nil { 66 return err 67 } 68 } 69 70 return nil 71 } 72 73 func (s *grpcService) Stop() error { 74 var gerr error 75 76 for _, fn := range s.opts.BeforeStop { 77 if err := fn(); err != nil { 78 gerr = err 79 } 80 } 81 82 if err := s.opts.Server.Stop(); err != nil { 83 return err 84 } 85 86 for _, fn := range s.opts.AfterStop { 87 if err := fn(); err != nil { 88 gerr = err 89 } 90 } 91 92 return gerr 93 } 94 95 func (s *grpcService) Run() error { 96 if err := s.Start(); err != nil { 97 return err 98 } 99 100 // wait on context cancel 101 <-s.opts.Context.Done() 102 103 return s.Stop() 104 } 105 106 // NewService returns a grpc service compatible with go-micro.Service 107 func NewService(opts ...service.Option) service.Service { 108 // our grpc client 109 c := gclient.NewClient() 110 // our grpc server 111 s := gserver.NewServer() 112 113 // create options with priority for our opts 114 options := []service.Option{ 115 service.Client(c), 116 service.Server(s), 117 } 118 119 // append passed in opts 120 options = append(options, opts...) 121 122 // generate and return a service 123 return newService(options...) 124 }