-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
190 lines (157 loc) · 4.4 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
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
package client
import (
"context"
"io"
"net/http"
"net/textproto"
"net/url"
"reflect"
"strings"
"github.com/julienschmidt/httprouter"
"github.com/octohelm/courier/pkg/courier"
"github.com/octohelm/courier/pkg/courierhttp/transport"
"github.com/octohelm/courier/pkg/statuserror"
transformer "github.com/octohelm/courier/pkg/transformer/core"
typesutil "github.com/octohelm/x/types"
"github.com/pkg/errors"
)
type RoundTrip = func(request *http.Request) (*http.Response, error)
func HttpTransportFunc(round func(request *http.Request, next RoundTrip) (*http.Response, error)) HttpTransport {
return func(rt http.RoundTripper) http.RoundTripper {
return &httpTransportFunc{
rt: rt,
round: round,
}
}
}
type httpTransportFunc struct {
rt http.RoundTripper
round func(request *http.Request, next RoundTrip) (*http.Response, error)
}
func (h *httpTransportFunc) RoundTrip(request *http.Request) (*http.Response, error) {
return h.round(request, h.rt.RoundTrip)
}
type HttpTransport func(rt http.RoundTripper) http.RoundTripper
type Client struct {
Endpoint string `flag:""`
HttpTransports []HttpTransport
}
func (c *Client) Do(ctx context.Context, req any, metas ...courier.Metadata) courier.Result {
httpReq, ok := req.(*http.Request)
if !ok {
r, err := c.newRequest(ctx, req, metas...)
if err != nil {
return &result{
err: statuserror.Wrap(err, http.StatusInternalServerError, "RequestFailed"),
}
}
httpReq = r
}
httpClient := HttpClientFromContext(ctx)
if httpClient == nil {
httpClient = GetShortConnClientContext(ctx, c.HttpTransports...)
}
resp, err := httpClient.Do(httpReq)
if err != nil {
if errors.Unwrap(err) == context.Canceled {
return &result{
err: statuserror.Wrap(err, 499, "ClientClosedRequest"),
}
}
return &result{
err: statuserror.Wrap(err, http.StatusInternalServerError, "RequestFailed"),
}
}
return &result{
Response: resp,
}
}
func (c *Client) newRequest(ctx context.Context, r any, metas ...courier.Metadata) (*http.Request, error) {
if ctx == nil {
ctx = context.Background()
}
req, err := transport.NewRequest(ctx, r)
if err != nil {
return nil, statuserror.Wrap(err, http.StatusBadRequest, "NewRequestFailed")
}
if u := req.URL.String(); !strings.HasPrefix(u, c.Endpoint) {
uu, _ := url.Parse(c.Endpoint)
req.URL.Scheme = uu.Scheme
req.URL.Host = uu.Host
req.URL.Path = httprouter.CleanPath(uu.Path + req.URL.Path)
}
for k, vs := range courier.FromMetas(metas...) {
for _, v := range vs {
req.Header.Add(k, v)
}
}
return req, nil
}
type result struct {
*http.Response
err error
}
func (r *result) StatusCode() int {
if r.Response != nil {
return r.Response.StatusCode
}
return 0
}
func (r *result) Meta() courier.Metadata {
if r.Response != nil {
return courier.Metadata(r.Response.Header)
}
return courier.Metadata{}
}
func (r *result) Into(body any) (courier.Metadata, error) {
defer func() {
if r.Response != nil && r.Response.Body != nil {
_ = r.Response.Body.Close()
}
}()
if r.err != nil {
return nil, r.err
}
meta := courier.Metadata(r.Response.Header)
if !isOk(r.Response.StatusCode) {
body = &statuserror.StatusErr{
Code: r.Response.StatusCode,
Msg: r.Response.Status,
Sources: []string{r.Response.Request.Host},
}
}
if body == nil {
return meta, nil
}
switch x := body.(type) {
case error:
// to unmarshal status error
if err := r.decode(x, meta); err != nil {
return meta, err
}
return meta, x
case io.Writer:
if _, err := io.Copy(x, r.Response.Body); err != nil {
return meta, statuserror.Wrap(err, http.StatusInternalServerError, "WriteFailed")
}
default:
if err := r.decode(body, meta); err != nil {
return meta, err
}
}
return meta, nil
}
func (r *result) decode(body any, meta courier.Metadata) error {
rv := reflect.ValueOf(body)
tf, err := transformer.NewTransformer(context.Background(), typesutil.FromRType(rv.Type()), transformer.Option{})
if err != nil {
return statuserror.Wrap(err, http.StatusInternalServerError, "TransformerCreateFailed")
}
if err := tf.DecodeFrom(context.Background(), r.Response.Body, rv, textproto.MIMEHeader(r.Response.Header)); err != nil {
return statuserror.Wrap(err, http.StatusInternalServerError, "DecodeFailed", errors.Wrapf(err, "decode failed to %v", body).Error())
}
return nil
}
func isOk(code int) bool {
return code >= http.StatusOK && code < http.StatusMultipleChoices
}