-
Notifications
You must be signed in to change notification settings - Fork 1
/
grpcserver.go
93 lines (75 loc) · 1.55 KB
/
grpcserver.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
88
89
90
91
92
93
package grpcserver
import (
"context"
"net"
"github.com/boxgo/box/pkg/config"
"github.com/boxgo/box/pkg/dummybox"
"google.golang.org/grpc"
)
type (
Server struct {
dummybox.DummyBox
name string
cfg *Config
server *grpc.Server
}
Options struct {
name string
cfg config.SubConfigurator
serverOptions []grpc.ServerOption
}
OptionFunc func(*Options)
)
func WithName(name string) OptionFunc {
return func(opts *Options) {
opts.name = name
}
}
func WithConfigurator(cfg config.SubConfigurator) OptionFunc {
return func(opts *Options) {
opts.cfg = cfg
}
}
func WithServerOption(serverOptions ...grpc.ServerOption) OptionFunc {
return func(opts *Options) {
opts.serverOptions = append(opts.serverOptions, serverOptions...)
}
}
func New(optFunc ...OptionFunc) *Server {
opts := &Options{}
for _, fn := range optFunc {
fn(opts)
}
if opts.name == "" {
opts.name = "grpc.server"
}
if opts.cfg == nil {
opts.cfg = config.Default
}
return &Server{
name: opts.name,
cfg: newConfig(opts.name, opts.cfg),
server: grpc.NewServer(opts.serverOptions...),
}
}
func (s *Server) Name() string {
return s.name
}
func (s *Server) Serve(ctx context.Context) error {
lis, err := net.Listen(s.cfg.Network(), s.cfg.Address())
if err != nil {
return err
}
err = s.server.Serve(lis)
if err != grpc.ErrServerStopped {
return nil
}
return err
}
func (s *Server) Shutdown(ctx context.Context) error {
s.server.GracefulStop()
return nil
}
func (s *Server) RawServer() *grpc.Server {
return s.server
}