-
Notifications
You must be signed in to change notification settings - Fork 8
/
client.go.tmpl
302 lines (257 loc) · 9.53 KB
/
client.go.tmpl
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
{{define "client"}}
{{- $typeMap := .TypeMap -}}
{{- $typePrefix := .TypePrefix -}}
{{- $services := .Services -}}
{{- $opts := .Opts }}
{{- if $services -}}
//
// Client
//
{{range $services -}}
const {{.Name}}PathPrefix = "/rpc/{{.Name}}/"
{{end}}
{{- range $_, $service := $services -}}
{{- $serviceNameClient := (printf "%sClient" ($service.Name | firstLetterToLower)) }}
{{- $ServiceNameClient := (printf "%sClient" ($service.Name | firstLetterToUpper)) }}
type {{$serviceNameClient}} struct {
client HTTPClient
urls [{{len $service.Methods}}]string
}
func New{{$ServiceNameClient}}(addr string, client HTTPClient) {{$ServiceNameClient}} {
prefix := urlBase(addr) + {{$service.Name}}PathPrefix
urls := [{{len $service.Methods}}]string{
{{- range $_, $method := $service.Methods}}
prefix + "{{$method.Name}}",
{{- end}}
}
return &{{$serviceNameClient}}{
client: client,
urls: urls,
}
}
{{- range $i, $method := $service.Methods -}}
{{ if eq $method.StreamOutput false }}
func (c *{{$serviceNameClient}}) {{$method.Name}}(ctx context.Context{{range $_, $input := $method.Inputs}}, {{$input.Name}} {{template "field" dict "Name" $input.Name "Type" $input.Type "Optional" $input.Optional "TypeMap" $typeMap "TypePrefix" $typePrefix "TypeMeta" $input.Meta}}{{end}}) {{if len $method.Outputs}}({{end}}{{range $i, $output := $method.Outputs}}{{template "field" dict "Name" $output.Name "Type" $output.Type "Optional" $output.Optional "TypeMap" $typeMap "TypePrefix" $typePrefix "TypeMeta" $output.Meta}}{{if lt $i (len $method.Outputs)}}, {{end}}{{end}}error{{if len $method.Outputs}}){{end}} {
{{- $inputVar := "nil" -}}
{{- $outputVar := "nil" -}}
{{- if $method.Inputs | len}}
{{- $inputVar = "in"}}
in := struct {
{{- range $i, $input := $method.Inputs}}
Arg{{$i}} {{template "field" dict "Name" $input.Name "Type" $input.Type "Optional" $input.Optional "TypeMap" $typeMap "TypePrefix" $typePrefix "TypeMeta" $input.Meta "JsonTags" true}}
{{- end}}
}{ {{- range $i, $input := $method.Inputs}}{{if gt $i 0}}, {{end}}{{$input.Name}}{{end}}}
{{- end}}
{{- if $method.Outputs | len}}
{{- $outputVar = "&out"}}
out := struct {
{{- range $i, $output := $method.Outputs}}
Ret{{$i}} {{template "field" dict "Name" $output.Name "Type" $output.Type "Optional" $output.Optional "TypeMap" $typeMap "TypePrefix" $typePrefix "TypeMeta" $output.Meta "JsonTags" true}}
{{- end}}
}{}
{{- end }}
resp, err := doHTTPRequest(ctx, c.client, c.urls[{{$i}}], {{$inputVar}}, {{$outputVar}})
if resp != nil {
cerr := resp.Body.Close()
if err == nil && cerr != nil {
err = ErrWebrpcRequestFailed.WithCausef("failed to close response body: %w", cerr)
}
}
return {{range $i, $output := $method.Outputs}}out.Ret{{$i}}, {{end}}err
}
{{- else }}
func (c *{{$serviceNameClient}}) {{$method.Name}}(ctx context.Context{{range $_, $input := $method.Inputs}}, {{$input.Name}} {{template "field" dict "Name" $input.Name "Type" $input.Type "Optional" $input.Optional "TypeMap" $typeMap "TypePrefix" $typePrefix "TypeMeta" $input.Meta}}{{end}}) ({{$method.Name}}StreamReader, error) {
{{- $inputVar := "nil" -}}
{{- if $method.Inputs | len}}
{{- $inputVar = "in"}}
in := struct {
{{- range $i, $input := $method.Inputs}}
Arg{{$i}} {{template "field" dict "Name" $input.Name "Type" $input.Type "Optional" $input.Optional "TypeMap" $typeMap "TypePrefix" $typePrefix "TypeMeta" $input.Meta "JsonTags" true}}
{{- end}}
}{ {{- range $i, $input := $method.Inputs}}{{if gt $i 0}}, {{end}}{{$input.Name}}{{end}}}
{{- end}}
resp, err := doHTTPRequest(ctx, c.client, c.urls[{{$i}}], {{$inputVar}}, nil)
if err != nil {
if resp != nil {
resp.Body.Close()
}
return nil, err
}
buf := bufio.NewReader(resp.Body)
return &{{$method.Name | firstLetterToLower}}StreamReader{streamReader{ctx: ctx, c: resp.Body, r: buf}}, nil
}
type {{firstLetterToLower $method.Name}}StreamReader struct {
streamReader
}
func (r *{{firstLetterToLower $method.Name}}StreamReader) Read() ({{range $i, $output := $method.Outputs}}{{template "field" dict "Name" $output.Name "Type" $output.Type "Optional" $output.Optional "TypeMap" $typeMap "TypePrefix" $typePrefix "TypeMeta" $output.Meta}}{{if lt $i (len $method.Outputs)}}{{end}}, {{end}}error) {
{{- $outputVar := "nil" -}}
{{- if $method.Outputs | len}}
{{- $outputVar = "&out"}}
out := struct {
{{- range $i, $output := $method.Outputs}}
Ret{{$i}} {{template "field" dict "Name" $output.Name "Type" $output.Type "Optional" $output.Optional "TypeMap" $typeMap "TypePrefix" $typePrefix "TypeMeta" $output.Meta "JsonTags" true}}
{{- end}}
WebRPCError *WebRPCError `json:"webrpcError"`
}{}
err := r.streamReader.read(&out)
if err != nil {
return {{range $i, $output := $method.Outputs}}out.Ret{{$i}}, {{end}}err
}
if out.WebRPCError != nil {
return {{range $i, $output := $method.Outputs}}out.Ret{{$i}}, {{end}}out.WebRPCError
}
return {{range $i, $output := $method.Outputs}}out.Ret{{$i}}, {{end}}nil
}
{{- end -}}
{{- end -}}
{{- end }}
{{- end }}
{{- if $opts.streaming }}
type streamReader struct {
ctx context.Context
c io.Closer
r *bufio.Reader
}
func (r *streamReader) read(v interface {}) error {
for {
select {
case <-r.ctx.Done():
r.c.Close()
return ErrWebrpcClientDisconnected.WithCause(r.ctx.Err())
default:
}
line, err := r.r.ReadBytes('\n')
if err != nil {
return r.handleReadError(err)
}
// Eat newlines (keep-alive pings).
if len(line) == 1 && line[0] == '\n' {
continue
}
if err := json.Unmarshal(line, &v); err != nil {
return r.handleReadError(err)
}
return nil
}
}
func (r *streamReader) handleReadError(err error) error {
defer r.c.Close()
if errors.Is(err, io.EOF) {
return ErrWebrpcStreamFinished.WithCause(err)
}
if errors.Is(err, io.ErrUnexpectedEOF) {
return ErrWebrpcStreamLost.WithCause(err)
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded){
return ErrWebrpcClientDisconnected.WithCause(err)
}
return ErrWebrpcBadResponse.WithCausef("reading stream: %w", err)
}
{{- end }}
// HTTPClient is the interface used by generated clients to send HTTP requests.
// It is fulfilled by *(net/http).Client, which is sufficient for most users.
// Users can provide their own implementation for special retry policies.
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
// urlBase helps ensure that addr specifies a scheme. If it is unparsable
// as a URL, it returns addr unchanged.
func urlBase(addr string) string {
// If the addr specifies a scheme, use it. If not, default to
// http. If url.Parse fails on it, return it unchanged.
url, err := url.Parse(addr)
if err != nil {
return addr
}
if url.Scheme == "" {
url.Scheme = "http"
}
return url.String()
}
// newRequest makes an http.Request from a client, adding common headers.
func newRequest(ctx context.Context, url string, reqBody io.Reader, contentType string) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, "POST", url, reqBody)
if err != nil {
return nil, err
}
req.Header.Set("Accept", contentType)
req.Header.Set("Content-Type", contentType)
{{- if eq $opts.webrpcHeader true }}
req.Header.Set(WebrpcHeader, WebrpcHeaderValue)
{{- end }}
if headers, ok := HTTPRequestHeaders(ctx); ok {
for k := range headers {
for _, v := range headers[k] {
req.Header.Add(k, v)
}
}
}
return req, nil
}
// doHTTPRequest is common code to make a request to the remote service.
func doHTTPRequest(ctx context.Context, client HTTPClient, url string, in, out interface{}) (*http.Response, error) {
reqBody, err := json.Marshal(in)
if err != nil {
return nil, ErrWebrpcRequestFailed.WithCausef("failed to marshal JSON body: %w", err)
}
if err = ctx.Err(); err != nil {
return nil, ErrWebrpcRequestFailed.WithCausef("aborted because context was done: %w", err)
}
req, err := newRequest(ctx, url, bytes.NewBuffer(reqBody), "application/json")
if err != nil {
return nil, ErrWebrpcRequestFailed.WithCausef("could not build request: %w", err)
}
resp, err := client.Do(req)
if err != nil {
return nil, ErrWebrpcRequestFailed.WithCause(err)
}
if resp.StatusCode != 200 {
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, ErrWebrpcBadResponse.WithCausef("failed to read server error response body: %w", err)
}
var rpcErr WebRPCError
if err := json.Unmarshal(respBody, &rpcErr); err != nil {
return nil, ErrWebrpcBadResponse.WithCausef("failed to unmarshal server error: %w", err)
}
if rpcErr.Cause != "" {
rpcErr.cause = errors.New(rpcErr.Cause)
}
return nil, rpcErr
}
if out != nil {
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, ErrWebrpcBadResponse.WithCausef("failed to read response body: %w", err)
}
err = json.Unmarshal(respBody, &out)
if err != nil {
return nil, ErrWebrpcBadResponse.WithCausef("failed to unmarshal JSON response body: %w", err)
}
}
return resp, nil
}
func WithHTTPRequestHeaders(ctx context.Context, h http.Header) (context.Context, error) {
if _, ok := h["Accept"]; ok {
return nil, errors.New("provided header cannot set Accept")
}
if _, ok := h["Content-Type"]; ok {
return nil, errors.New("provided header cannot set Content-Type")
}
copied := make(http.Header, len(h))
for k, vv := range h {
if vv == nil {
copied[k] = nil
continue
}
copied[k] = make([]string, len(vv))
copy(copied[k], vv)
}
return context.WithValue(ctx, HTTPClientRequestHeadersCtxKey, copied), nil
}
func HTTPRequestHeaders(ctx context.Context) (http.Header, bool) {
h, ok := ctx.Value(HTTPClientRequestHeadersCtxKey).(http.Header)
return h, ok
}
{{- end -}}
{{- end -}}