-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
117 lines (93 loc) · 2.39 KB
/
client.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package mathtoolset2
import (
"context"
"log/slog"
"os"
"github.com/zhs007/goutils"
sgc7pb "github.com/zhs007/slotsgamecore7/sgc7pb"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// Client - MathToolsetClient
type Client struct {
servAddr string
conn *grpc.ClientConn
client sgc7pb.MathToolsetClient
}
// NewClient - new MathToolsetClient
func NewClient(servAddr string) (*Client, error) {
client := &Client{
servAddr: servAddr,
}
return client, nil
}
// reset - reset
func (client *Client) reset() {
if client.conn != nil {
client.conn.Close()
}
client.conn = nil
client.client = nil
}
func (client *Client) onRequest(_ context.Context) error {
if client.conn == nil || client.client == nil {
conn, err := grpc.Dial(client.servAddr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor()),
grpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor()))
if err != nil {
goutils.Error("Client.onRequest:grpc.Dial",
slog.String("server address", client.servAddr),
goutils.Err(err))
return err
}
client.conn = conn
client.client = sgc7pb.NewMathToolsetClient(conn)
}
return nil
}
// RunScript - run script
func (client *Client) RunScript(ctx context.Context, script string, mapFiles map[string]string) (*sgc7pb.ReplyRunScript, error) {
err := client.onRequest(ctx)
if err != nil {
goutils.Error("Client.RunScript:onRequest",
goutils.Err(err))
return nil, err
}
mapfd, err := NewFileDataMap("")
if err != nil {
goutils.Error("Client.RunScript:NewFileDataMap",
goutils.Err(err))
return nil, err
}
for k, v := range mapFiles {
file, err := os.Open(v)
if err != nil {
goutils.Error("Client.RunScript:Open",
slog.String("fn", v),
goutils.Err(err))
return nil, err
}
mapfd.AddReader(k, file)
}
jsondata, err := mapfd.ToJson()
if err != nil {
goutils.Error("Client.RunScript:ToJson",
goutils.Err(err))
return nil, err
}
res, err := client.client.RunScript(ctx, &sgc7pb.RunScript{
Script: script,
MapFiles: jsondata,
})
if err != nil {
goutils.Error("Client.InitGame:InitGame",
slog.String("server address", client.servAddr),
slog.String("script", script),
goutils.Err(err))
client.reset()
return nil, err
}
return res, nil
}