-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
128 lines (100 loc) · 2.35 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
118
119
120
121
122
123
124
125
126
127
128
package adacore
import (
"context"
"io"
"io/ioutil"
adacorebase "github.com/zhs007/adacore/base"
adacorepb "github.com/zhs007/adacore/adacorepb"
"google.golang.org/grpc"
)
// Client - AdaRenderServClient
type Client struct {
servAddr string
token string
conn *grpc.ClientConn
client adacorepb.AdaCoreServiceClient
}
// NewClient - new AdaRenderClient
func NewClient(servAddr string, token string) *Client {
return &Client{
servAddr: servAddr,
token: token,
}
}
// isValid - check myself
func (client *Client) isValid() error {
if client.servAddr == "" {
return adacorebase.ErrAdaCoreClientNoServAddr
}
if client.token == "" {
return adacorebase.ErrAdaCoreClientNoToken
}
return nil
}
// reset - reset
func (client *Client) reset() {
if client.conn != nil {
client.conn.Close()
}
client.conn = nil
client.client = nil
}
// BuildWithMarkdown - MarkdownData => ReplyMarkdown
func (client *Client) BuildWithMarkdown(ctx context.Context, mddata *adacorepb.MarkdownData) (
*adacorepb.ReplyMarkdown, error) {
err := client.isValid()
if err != nil {
return nil, err
}
if client.conn == nil || client.client == nil {
conn, err := grpc.Dial(client.servAddr, grpc.WithInsecure())
if err != nil {
return nil, err
}
client.conn = conn
client.client = adacorepb.NewAdaCoreServiceClient(conn)
}
stream, err := client.client.BuildWithMarkdown(ctx)
if err != nil {
// if error, reset
client.reset()
return nil, err
}
lst, err := BuildMarkdownStream(mddata, client.token)
if err != nil {
// if error, close
stream.CloseSend()
// if error, reset
client.reset()
return nil, err
}
for _, cn := range lst {
curerr := stream.Send(cn)
if curerr != nil {
// if error, close
stream.CloseSend()
// if error, reset
client.reset()
return nil, curerr
}
}
reply, err := stream.CloseAndRecv()
if err != nil && err != io.EOF {
// if error, reset
client.reset()
return nil, err
}
return reply, nil
}
// BuildWithMarkdownFile - markdown file => ReplyMarkdown
func (client *Client) BuildWithMarkdownFile(ctx context.Context, fn string, tempname string) (*adacorepb.ReplyMarkdown, error) {
fd, err := ioutil.ReadFile(fn)
if err != nil {
return nil, err
}
md := &adacorepb.MarkdownData{
StrData: string(fd),
TemplateName: tempname,
}
return client.BuildWithMarkdown(ctx, md)
}