-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
85 lines (68 loc) · 2.11 KB
/
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
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
package grpctools
import (
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
)
// Server embeds a standard grpc Server with a healthcheck
type Server struct {
*grpc.Server
name string
addr string
health *health.Server
}
// NewServer returns a new Server instance.
func NewServer(name string, addr string, opts *Options, extra ...grpc.ServerOption) *Server {
if opts == nil {
opts = new(Options)
}
full := append(opts.grpcServerOpts(), extra...)
srv := &Server{
Server: grpc.NewServer(full...),
name: name,
addr: addr,
health: health.NewServer(),
}
healthpb.RegisterHealthServer(srv.Server, srv.health)
return srv
}
// ListenAndServe starts the server (blocking).
func (s *Server) ListenAndServe() error {
lis, err := net.Listen("tcp", s.addr)
if err != nil {
return err
}
defer lis.Close()
s.health.SetServingStatus(s.name, healthpb.HealthCheckResponse_SERVING)
err = s.Serve(lis)
s.health.SetServingStatus(s.name, healthpb.HealthCheckResponse_NOT_SERVING)
return err
}
// --------------------------------------------------------------------
// Options represent server options
type Options struct {
MaxConcurrentStreams uint32
SkipInstrumentation bool
UnaryInterceptors []grpc.UnaryServerInterceptor
StreamInterceptors []grpc.StreamServerInterceptor
}
func (o *Options) grpcServerOpts() []grpc.ServerOption {
opts := make([]grpc.ServerOption, 0)
uchain := append([]grpc.UnaryServerInterceptor{}, o.UnaryInterceptors...)
schain := append([]grpc.StreamServerInterceptor{}, o.StreamInterceptors...)
if o.MaxConcurrentStreams > 0 {
opts = append(opts, grpc.MaxConcurrentStreams(o.MaxConcurrentStreams))
}
if !o.SkipInstrumentation {
uchain = append(uchain, DefaultInstrumenter.UnaryServerInterceptor)
schain = append(schain, DefaultInstrumenter.StreamServerInterceptor)
}
if len(uchain) != 0 {
opts = append(opts, grpc.UnaryInterceptor(unaryServerInterceptorChain(uchain...)))
}
if len(schain) != 0 {
opts = append(opts, grpc.StreamInterceptor(streamServerInterceptorChain(schain...)))
}
return opts
}