github.com/profzone/eden-framework@v1.0.10/pkg/courier/transport_grpc/serve.go (about) 1 package transport_grpc 2 3 import ( 4 "fmt" 5 "github.com/profzone/envconfig" 6 "net" 7 "os" 8 "time" 9 10 "google.golang.org/grpc" 11 12 "github.com/profzone/eden-framework/pkg/courier" 13 ) 14 15 type ServeGRPC struct { 16 IP string 17 Port int 18 WriteTimeout envconfig.Duration 19 ReadTimeout envconfig.Duration 20 Name string 21 } 22 23 func (s ServeGRPC) MarshalDefaults(v interface{}) { 24 if srv, ok := v.(*ServeGRPC); ok { 25 if srv.Name == "" { 26 srv.Name = os.Getenv("PROJECT_NAME") 27 } 28 29 if srv.Port == 0 { 30 srv.Port = 9000 31 } 32 33 if srv.ReadTimeout == 0 { 34 srv.ReadTimeout = envconfig.Duration(15 * time.Second) 35 } 36 37 if srv.WriteTimeout == 0 { 38 srv.WriteTimeout = envconfig.Duration(15 * time.Second) 39 } 40 } 41 } 42 43 func (s *ServeGRPC) Serve(router *courier.Router) error { 44 s.MarshalDefaults(s) 45 46 lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", s.IP, s.Port)) 47 if err != nil { 48 panic(err) 49 } 50 51 gs := grpc.NewServer(grpc.CustomCodec(&MsgPackCodec{})) 52 53 serviceDesc := s.convertRouterToServiceDesc(router) 54 serviceDesc.ServiceName = s.Name 55 56 gs.RegisterService(serviceDesc, &mockServer{}) 57 58 fmt.Printf("[Courier] listen on %s\n", lis.Addr().String()) 59 60 return gs.Serve(lis) 61 } 62 63 func (s *ServeGRPC) convertRouterToServiceDesc(router *courier.Router) *grpc.ServiceDesc { 64 routes := router.Routes() 65 66 if len(routes) == 0 { 67 panic(fmt.Sprintf("need to register operation before Listion")) 68 } 69 70 serviceDesc := grpc.ServiceDesc{ 71 HandlerType: (*MockServer)(nil), 72 Methods: []grpc.MethodDesc{}, 73 Streams: []grpc.StreamDesc{}, 74 } 75 76 for _, route := range routes { 77 operators, operatorTypeNames := route.EffectiveOperators() 78 79 streamDesc := grpc.StreamDesc{ 80 StreamName: operatorTypeNames[len(operatorTypeNames)-1], 81 Handler: CreateStreamHandler(s, operators...), 82 ServerStreams: true, 83 } 84 85 serviceDesc.Streams = append(serviceDesc.Streams, streamDesc) 86 } 87 88 return &serviceDesc 89 } 90 91 type MockServer interface { 92 } 93 94 type mockServer struct { 95 }