Skip to content

Instantly share code, notes, and snippets.

@AryanGodara
Created July 17, 2023 18:22
Show Gist options
  • Save AryanGodara/59913aa6954b1edb7734091757fa2766 to your computer and use it in GitHub Desktop.
Save AryanGodara/59913aa6954b1edb7734091757fa2766 to your computer and use it in GitHub Desktop.
transports/grpcTransport.go
package transports
import (
"context"
"errors"
"github.com/aryangodara/go-kit-grpc-example1/api/endpoints"
"github.com/aryangodara/go-kit-grpc-example1/pb"
gt "github.com/go-kit/kit/transport/grpc"
"github.com/go-kit/log"
)
type gRPCServer struct {
add gt.Handler
subtract gt.Handler
mutiply gt.Handler
divide gt.Handler
pb.UnimplementedMathServiceServer
}
// NewGRPCServer initializes a new gRPC server
func NewGRPCServer(endpointds endpoints.Endpoints, logger log.Logger) pb.MathServiceServer {
return &gRPCServer{
add: gt.NewServer(
endpointds.Add,
decodeMathRequest,
encodeMathResponse,
),
subtract: gt.NewServer(
endpointds.Subtract,
decodeMathRequest,
encodeMathResponse,
),
mutiply: gt.NewServer(
endpointds.Multiply,
decodeMathRequest,
encodeMathResponse,
),
divide: gt.NewServer(
endpointds.Divide,
decodeMathRequest,
encodeMathResponse,
),
}
}
func (s gRPCServer) Add(ctx context.Context, req *pb.MathRequest) (*pb.MathResponse, error) {
_, resp, err := s.add.ServeGRPC(ctx, req)
if err != nil {
return nil, err
}
return resp.(*pb.MathResponse), nil
}
func (s gRPCServer) Subtract(ctx context.Context, req *pb.MathRequest) (*pb.MathResponse, error) {
_, resp, err := s.subtract.ServeGRPC(ctx, req)
if err != nil {
return nil, err
}
return resp.(*pb.MathResponse), nil
}
func (s gRPCServer) Multiply(ctx context.Context, req *pb.MathRequest) (*pb.MathResponse, error) {
_, resp, err := s.mutiply.ServeGRPC(ctx, req)
if err != nil {
return nil, err
}
return resp.(*pb.MathResponse), nil
}
func (s gRPCServer) Divide(ctx context.Context, req *pb.MathRequest) (*pb.MathResponse, error) {
_, resp, err := s.divide.ServeGRPC(ctx, req)
if err != nil {
return nil, err
}
return resp.(*pb.MathResponse), nil
}
func decodeMathRequest(_ context.Context, request interface{}) (interface{}, error) {
req, ok := request.(*pb.MathRequest)
if !ok {
return nil, errors.New("invalid request body")
}
return endpoints.MathReq{NumA: req.NumA, NumB: req.NumB}, nil
}
func encodeMathResponse(_ context.Context, response interface{}) (interface{}, error) {
resp, ok := response.(endpoints.MathResp)
if !ok {
return nil, errors.New("invalid response body")
}
return &pb.MathResponse{Result: resp.Result}, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment