-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrpc_server.go
53 lines (41 loc) · 1.07 KB
/
grpc_server.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
package main
import (
"context"
"math/rand"
"net"
"github.com/denslobodan/micro-price/proto"
"google.golang.org/grpc"
)
func makeGRPCServerAndRun(listenAddr string, svc PriceService) error {
grpcPriceFetcher := NewGRPCPriceFetcherServer(svc)
ln, err := net.Listen("tcp", listenAddr)
if err != nil {
return err
}
opts := []grpc.ServerOption{}
server := grpc.NewServer(opts...)
proto.RegisterPriceFetcherServer(server, grpcPriceFetcher)
return server.Serve(ln)
}
type GRPCPriceFetcherServer struct {
svc PriceService
proto.UnimplementedPriceFetcherServer
}
func NewGRPCPriceFetcherServer(svc PriceService) *GRPCPriceFetcherServer {
return &GRPCPriceFetcherServer{
svc: svc,
}
}
func (s *GRPCPriceFetcherServer) FetchPrice(ctx context.Context, req *proto.PriceRequest) (*proto.PriceResponse, error) {
reqid := rand.Intn(10000)
ctx = context.WithValue(ctx, "requestID", reqid)
price, err := s.svc.FetchPrice(ctx, req.Ticker)
if err != nil {
return nil, err
}
resp := &proto.PriceResponse{
Ticker: req.Ticker,
Price: float32(price),
}
return resp, err
}