-
Notifications
You must be signed in to change notification settings - Fork 98
/
service.go
82 lines (69 loc) · 1.51 KB
/
service.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
// Package gotest is a library that simulates the testing of cache, dao and handler.
package gotest
import (
"context"
"fmt"
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/zhufuyi/sponge/pkg/utils"
)
// Service info
type Service struct {
Ctx context.Context
TestData interface{}
MockDao *Dao
Server *grpc.Server
listen net.Listener
clientAddr string
clientConn *grpc.ClientConn
IServiceClient interface{}
}
// NewService instantiated service
func NewService(dao *Dao, testData interface{}) *Service {
port, _ := utils.GetAvailablePort()
clientAddr := fmt.Sprintf("127.0.0.1:%d", port)
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
panic(err)
}
server := grpc.NewServer()
return &Service{
Ctx: context.Background(),
TestData: testData,
MockDao: dao,
clientAddr: clientAddr,
Server: server,
listen: lis,
}
}
// GoGrpcServer run grpc server
func (s *Service) GoGrpcServer() {
go func() {
if err := s.Server.Serve(s.listen); err != nil {
panic(err)
}
}()
}
// GetClientConn dial rpc server
func (s *Service) GetClientConn() *grpc.ClientConn {
conn, err := grpc.Dial(s.clientAddr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
panic(err)
}
return conn
}
// Close service
func (s *Service) Close() {
if s.MockDao != nil {
s.MockDao.Close()
}
if s.clientConn != nil {
_ = s.clientConn.Close()
}
if s.Server != nil {
s.Server.GracefulStop()
}
}