-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathservice_grpc.go
49 lines (44 loc) · 1.22 KB
/
service_grpc.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
package lifetime
import (
"fmt"
"google.golang.org/grpc"
"net"
)
// NewGRPCService returns a service that will run listen and serve the given
// GRPC server.
func NewGRPCService(server *grpc.Server, listenAddress string) Service {
return &grpcService{
server: server,
listenAddress: listenAddress,
}
}
// grpcService is an implementation of Service that will listen and serve the given
// HTTP server.
type grpcService struct {
server *grpc.Server
listenAddress string
}
// Start will start the service.
// This is a blocking call and should block for the lifetime of the service.
// Returns an error which is treated as fatal.
func (service *grpcService) Start() error {
lis, err := net.Listen("tcp", service.listenAddress)
if err != nil {
return fmt.Errorf("could not listen on tcp address: %w", err)
}
err = service.server.Serve(lis)
if err == nil {
return nil
}
// ErrServerStopped is returned when we call server.Close() from Service.Stop
// so we shouldn't treat it as a breaking error.
if err == grpc.ErrServerStopped {
return nil
}
return err
}
// Stop will stop the service.
// Stop is not called if Start returned an error.
func (service *grpcService) Stop() {
service.server.GracefulStop()
}