github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/courier/transport_grpc/serve.go (about)

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