-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
100 lines (84 loc) · 2.27 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package grpcutils
import (
"context"
"fmt"
"net"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/hashicorp/go-multierror"
"go.uber.org/zap"
"google.golang.org/grpc"
)
type ServerOption func(s *Server)
type Server struct {
Server *grpc.Server
serviceName string
addr string
logger *zap.Logger
serverOpts []grpc.ServerOption
unaryInterceptors []grpc.UnaryServerInterceptor
streamInterceptors []grpc.StreamServerInterceptor
cleanFuncs []func(s *Server) error
}
func NewServer(name, addr string) *Server {
return &Server{serviceName: name, addr: addr}
}
func (s *Server) Init(opts ...interface{}) error {
for _, opt := range opts {
switch o := opt.(type) {
case ServerOption:
o(s)
case grpc.ServerOption:
s.serverOpts = append(s.serverOpts, o)
default:
return fmt.Errorf("invalid server option: %v", opt)
}
}
if s.logger == nil {
s.logger = zap.L()
}
s.logger = s.logger.With(zap.String("addr", s.addr))
s.serverOpts = append(s.serverOpts,
grpc.ChainUnaryInterceptor(s.unaryInterceptors...),
grpc.ChainStreamInterceptor(s.streamInterceptors...),
)
s.Server = grpc.NewServer(s.serverOpts...)
return nil
}
func (s *Server) CleanUp() error {
var err *multierror.Error
for _, clean := range s.cleanFuncs {
err = multierror.Append(err, clean(s))
}
return err.ErrorOrNil()
}
func (s *Server) Serve() error {
listener, err := net.Listen("tcp", s.addr)
if err != nil {
return err
}
s.cleanFuncs = append([]func(s *Server) error{
func(srv *Server) error {
if srv.Server != nil {
srv.Server.GracefulStop()
}
return nil
},
}, s.cleanFuncs...)
return s.Server.Serve(listener)
}
func (s *Server) GetHttpProxy(httpAddr string, opts []grpc.DialOption, register func(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error) (*http.Server, error) {
mux := runtime.NewServeMux()
conn := NewClientConnection(s.addr)
if err := conn.Dial(opts...); err != nil {
return nil, err
}
s.cleanFuncs = append(s.cleanFuncs, func(*Server) error {
return conn.CleanUp()
})
ctx := context.Background()
if err := register(ctx, mux, conn.Connection); err != nil {
return nil, err
}
return &http.Server{Addr: httpAddr, Handler: mux}, nil
}