-
Notifications
You must be signed in to change notification settings - Fork 2
/
server_rpc.go
87 lines (64 loc) · 1.62 KB
/
server_rpc.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package geoipfix
import (
"context"
"fmt"
"net"
"strconv"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
"github.com/grpc-ecosystem/go-grpc-middleware/tags"
"go.uber.org/zap"
"google.golang.org/grpc"
"github.com/ulule/geoipfix/proto"
)
// rpcServer is an RPC server.
type rpcServer struct {
srv *grpc.Server
opt options
cfg serverRPCConfig
}
func newRPCServer(cfg serverRPCConfig, opts ...option) *rpcServer {
opt := newOptions(opts...)
srv := &rpcServer{
cfg: cfg,
}
opt.Logger = opt.Logger.With(zap.String("server", srv.Name()))
srv.opt = opt
return srv
}
func (h *rpcServer) Name() string {
return "rpc"
}
// Init initializes rpc server instance.
func (h *rpcServer) Init() error {
grpc_zap.ReplaceGrpcLogger(h.opt.Logger)
s := grpc.NewServer(
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_zap.UnaryServerInterceptor(h.opt.Logger),
),
)
proto.RegisterGeoipfixServer(s, &rpcHandler{h.opt})
h.srv = s
return nil
}
// Serve serves rpc requests.
func (h *rpcServer) Serve(ctx context.Context) error {
addr := fmt.Sprintf(":%s", strconv.Itoa(h.cfg.Port))
lis, err := net.Listen("tcp", addr)
if err != nil {
return err
}
h.opt.Logger.Info("Launch server", zap.String("addr", addr))
err = h.srv.Serve(lis)
if err != nil {
return err
}
return nil
}
// Shutdown stops the rpc server.
func (h *rpcServer) Shutdown() error {
h.srv.GracefulStop()
h.opt.Logger.Info("Server shutdown")
return nil
}