forked from webrpc/gen-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go.tmpl
211 lines (182 loc) · 6 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
{{define "client"}}
{{- $typeMap := .TypeMap -}}
{{- if .Services -}}
//
// Client
//
{{range .Services -}}
const {{.Name}}PathPrefix = "/rpc/{{.Name}}/"
{{end}}
{{- range .Services -}}
{{ $serviceName := (printf "%sClient" (.Name | firstLetterToLower)) }}
type {{$serviceName}} struct {
client HTTPClient
urls [{{len .Methods}}]string
}
func New{{.Name | firstLetterToUpper }}Client(addr string, client HTTPClient) {{.Name}} {
prefix := urlBase(addr) + {{.Name}}PathPrefix
urls := [{{len .Methods}}]string{
{{- range .Methods}}
prefix + "{{.Name}}",
{{- end}}
}
return &{{$serviceName}}{
client: client,
urls: urls,
}
}
{{- range $i, $method := .Methods -}}
{{- $inputs := $method.Inputs -}}
{{- $outputs := $method.Outputs }}
func (c *{{$serviceName}}) {{.Name}}(ctx context.Context{{range $_, $input := $inputs}}, {{$input.Name}} {{template "type" dict "Type" $input.Type "Optional" $input.Optional "TypeMap" $typeMap}}{{end}}) {{if len .Outputs}}({{end}}{{range $i, $output := .Outputs}}{{template "type" dict "Type" $output.Type "Optional" $output.Optional "TypeMap" $typeMap}}{{if lt $i (len $method.Outputs)}}, {{end}}{{end}}error{{if len .Outputs}}){{end}} {
{{- $inputVar := "nil" -}}
{{- $outputVar := "nil" -}}
{{- if $inputs | len}}
{{- $inputVar = "in"}}
in := struct {
{{- range $i, $input := $inputs}}
Arg{{$i}} {{template "type" dict "Type" $input.Type "Optional" $input.Optional "TypeMap" $typeMap}} `json:"{{firstLetterToLower $input.Name}}"`
{{- end}}
}{ {{- range $i, $input := $inputs}}{{if gt $i 0}}, {{end}}{{$input.Name}}{{end}}}
{{- end}}
{{- if $outputs | len}}
{{- $outputVar = "&out"}}
out := struct {
{{- range $i, $output := .Outputs}}
Ret{{$i}} {{template "type" dict "Type" $output.Type "Optional" $output.Optional "TypeMap" $typeMap}} `json:"{{firstLetterToLower $output.Name}}"`
{{- end}}
}{}
{{- end}}
err := doJSONRequest(ctx, c.client, c.urls[{{$i}}], {{$inputVar}}, {{$outputVar}})
return {{range $i, $output := .Outputs}}out.Ret{{$i}}, {{end}}err
}
{{- end -}}
{{- 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.NewRequest("POST", url, reqBody)
if err != nil {
return nil, err
}
req.Header.Set("Accept", contentType)
req.Header.Set("Content-Type", contentType)
if headers, ok := HTTPRequestHeaders(ctx); ok {
for k := range headers {
for _, v := range headers[k] {
req.Header.Add(k, v)
}
}
}
return req, nil
}
// doJSONRequest is common code to make a request to the remote service.
func doJSONRequest(ctx context.Context, client HTTPClient, url string, in, out interface{}) error {
reqBody, err := json.Marshal(in)
if err != nil {
return clientError("failed to marshal json request", err)
}
if err = ctx.Err(); err != nil {
return clientError("aborted because context was done", err)
}
req, err := newRequest(ctx, url, bytes.NewBuffer(reqBody), "application/json")
if err != nil {
return clientError("could not build request", err)
}
resp, err := client.Do(req)
if err != nil {
return clientError("request failed", err)
}
defer func() {
cerr := resp.Body.Close()
if err == nil && cerr != nil {
err = clientError("failed to close response body", cerr)
}
}()
if err = ctx.Err(); err != nil {
return clientError("aborted because context was done", err)
}
if resp.StatusCode != 200 {
return errorFromResponse(resp)
}
if out != nil {
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return clientError("failed to read response body", err)
}
err = json.Unmarshal(respBody, &out)
if err != nil {
return clientError("failed to unmarshal json response body", err)
}
if err = ctx.Err(); err != nil {
return clientError("aborted because context was done", err)
}
}
return nil
}
// errorFromResponse builds a webrpc Error from a non-200 HTTP response.
func errorFromResponse(resp *http.Response) Error {
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return clientError("failed to read server error response body", err)
}
var respErr ErrorPayload
if err := json.Unmarshal(respBody, &respErr); err != nil {
return clientError("failed unmarshal error response", err)
}
errCode := ErrorCode(respErr.Code)
if HTTPStatusFromErrorCode(errCode) == 0 {
return ErrorInternal("invalid code returned from server error response: %s", respErr.Code)
}
return &rpcErr{
code: errCode,
msg: respErr.Msg,
cause: errors.New(respErr.Cause),
}
}
func clientError(desc string, err error) Error {
return WrapError(ErrInternal, err, desc)
}
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 }}