-
Notifications
You must be signed in to change notification settings - Fork 3
/
transport.go
80 lines (64 loc) · 1.39 KB
/
transport.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
package transport
import (
"context"
"errors"
"fmt"
"net"
"github.com/alexfalkowski/go-service/transport/grpc"
"github.com/alexfalkowski/go-service/transport/http"
"go.uber.org/fx"
)
// ErrInvalidPort for transport.
var ErrInvalidPort = errors.New("invalid port")
// RegisterParams for transport.
type RegisterParams struct {
fx.In
Lifecycle fx.Lifecycle
Config *Config
HTTP *http.Server
GRPC *grpc.Server
}
// Register all the transports.
func Register(params RegisterParams) {
s := &server{cfg: params.Config, http: params.HTTP, grpc: params.GRPC}
params.Lifecycle.Append(fx.Hook{
OnStart: func(context.Context) error {
return s.Start()
},
OnStop: func(ctx context.Context) error {
s.Stop(ctx)
return nil
},
})
}
// Server handles all the transports.
type server struct {
cfg *Config
http *http.Server
grpc *grpc.Server
}
// Start all the servers.
func (s *server) Start() error {
gl, err := s.listener(s.cfg.GRPC.Port)
if err != nil {
return err
}
hl, err := s.listener(s.cfg.HTTP.Port)
if err != nil {
return err
}
go s.grpc.Start(gl)
go s.http.Start(hl)
return nil
}
// Stop all the servers.
func (s *server) Stop(ctx context.Context) {
s.grpc.Stop(ctx)
s.http.Stop(ctx)
}
func (s *server) listener(port string) (net.Listener, error) {
if port == "" {
return nil, ErrInvalidPort
}
return net.Listen("tcp", fmt.Sprintf(":%s", port))
}