I used the official documentation https://grpc.io/docs/languages/go/basics/, but after implementation, questions arose. When I create a TCP server I have to specify host and port (in my case mcrsrv-book:7561). But what if I want to implement another API for GRPC? Do I need to start another server on a new port (e.g. mcrsrv-book:7562)? How is routing and api implemented in grpc?
My server code is:
type routeGuideServer struct {
pb.UnimplementedRouteGuideServer
savedFeatures []*pb.Response // read-only after initialized
}
// GetFeature returns the feature at the given point.
func (s *routeGuideServer) GetFeature(ctx context.Context, request *pb.Request) (*pb.Response, error) {
context := localContext.LocalContext{}
book := bookRepository.FindOrFailBook(context, int(request.BookId))
return &pb.Response{
Name: book.Name,
BookId: int32(book.BookId),
AuthorId: int32(book.AuthorId),
Category: book.Category,
Description: "Описание",
}, nil
}
func newServer() *routeGuideServer {
s := &routeGuideServer{}
return s
}
func SomeAction() {
lis, err := net.Listen("tcp", fmt.Sprintf("mcrsrv-book:7561"))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
var opts []grpc.ServerOption
grpcServer := grpc.NewServer(opts...)
pb.RegisterRouteGuideServer(grpcServer, newServer())
grpcServer.Serve(lis)
}
I think there should be options other than opening a separate port for each grpc service.
How is the api implemented in grpc?
If you want to use the same address for a different service, you can just re-register the other service before initiating the grpc server.
grpcServer := grpc.NewServer(opts...)
pb.RegisterRouteGuideServer(grpcServer, newServer())
#register other server here with the same 'grpcServer'
grpcServer.Serve(lis)
This stackoverflow thread would probably help as an example of what you want to achieve. The question provided a sample code that I believe align with what you asked.