-
Notifications
You must be signed in to change notification settings - Fork 17
/
grpc.go
64 lines (53 loc) · 1.66 KB
/
grpc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Code generated by kun; DO NOT EDIT.
// github.com/RussellLuo/kun
package helloworldgrpc
import (
"context"
"github.com/RussellLuo/kun/examples/helloworldgrpc/pb"
"github.com/RussellLuo/kun/pkg/grpccodec"
kitgrpc "github.com/go-kit/kit/transport/grpc"
)
type grpcServer struct {
pb.UnimplementedServiceServer
sayHello kitgrpc.Handler
}
func (s *grpcServer) SayHello(ctx context.Context, req *pb.SayHelloRequest) (*pb.SayHelloResponse, error) {
_, resp, err := s.sayHello.ServeGRPC(ctx, req)
if err != nil {
return nil, err
}
return resp.(*pb.SayHelloResponse), nil
}
func NewGRPCServer(svc Service, codecs grpccodec.Codecs) pb.ServiceServer {
var codec grpccodec.Codec
s := new(grpcServer)
codec = codecs.EncodeDecoder("SayHello")
s.sayHello = kitgrpc.NewServer(
MakeEndpointOfSayHello(svc),
decodeSayHelloRequest(codec),
encodeSayHelloResponse(codec),
)
return s
}
// decodeSayHelloRequest converts a gRPC request to an endpoint request.
func decodeSayHelloRequest(codec grpccodec.Codec) kitgrpc.DecodeRequestFunc {
return func(_ context.Context, grpcReq interface{}) (interface{}, error) {
var req SayHelloRequest
pb := grpcReq.(*pb.SayHelloRequest)
if err := codec.DecodeRequest(pb, &req); err != nil {
return nil, err
}
return &req, nil
}
}
// encodeSayHelloResponse converts an endpoint response to a gRPC response.
func encodeSayHelloResponse(codec grpccodec.Codec) kitgrpc.EncodeResponseFunc {
return func(_ context.Context, response interface{}) (interface{}, error) {
pb := new(pb.SayHelloResponse)
resp := response.(*SayHelloResponse)
if err := codec.EncodeResponse(resp, pb); err != nil {
return nil, err
}
return pb, nil
}
}