-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
222 lines (183 loc) · 5.44 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
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
package allsrvc
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"runtime/debug"
"github.com/jsteenb2/errors"
)
const (
resourceTypeFoo = "foo"
)
var (
ErrIDRequired = errors.Kind("id is required")
version = func() string {
if info, ok := debug.ReadBuildInfo(); ok {
for _, m := range info.Deps {
if m.Path == "github.com/jsteenb2/allsrvc" {
return m.Version
}
}
}
return ""
}()
)
func WithBasicAuth(user, pass string) func(*ClientHTTP) {
return func(c *ClientHTTP) {
c.authFn = func(r *http.Request) error {
r.SetBasicAuth(user, pass)
return nil
}
}
}
type ClientHTTP struct {
addr string
origin string
c *http.Client
authFn func(r *http.Request) error
}
func NewClientHTTP(addr, origin string, c *http.Client, opts ...func(*ClientHTTP)) *ClientHTTP {
out := ClientHTTP{
addr: addr,
origin: origin,
c: c,
authFn: func(r *http.Request) error { return nil },
}
for _, o := range opts {
o(&out)
}
return &out
}
// Foo API types
type (
FooCreateAttrs struct {
Name string `json:"name"`
Note string `json:"note"`
}
// ResourceFooAttrs are the attributes of a foo resource.
ResourceFooAttrs struct {
Name string `json:"name"`
Note string `json:"note"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
)
func (c *ClientHTTP) CreateFoo(ctx context.Context, attrs FooCreateAttrs) (RespBody[ResourceFooAttrs], error) {
req, err := jsonReq(ctx, "POST", c.fooPath(""), c.origin, newFooData("", attrs))
if err != nil {
return RespBody[ResourceFooAttrs]{}, errors.Wrap(err, "create foo")
}
resp, err := c.doFooReq(req)
return resp, errors.Wrap(err)
}
func (c *ClientHTTP) ReadFoo(ctx context.Context, id string) (RespBody[ResourceFooAttrs], error) {
if id == "" {
return RespBody[ResourceFooAttrs]{}, errors.Wrap(ErrIDRequired)
}
req, err := newRequest(ctx, "GET", c.fooPath(id), c.origin, nil)
if err != nil {
return RespBody[ResourceFooAttrs]{}, errors.Wrap(err)
}
resp, err := c.doFooReq(req)
return resp, errors.Wrap(err)
}
type FooUpdAttrs struct {
Name *string `json:"name"`
Note *string `json:"note"`
}
func (c *ClientHTTP) UpdateFoo(ctx context.Context, id string, attrs FooUpdAttrs) (RespBody[ResourceFooAttrs], error) {
req, err := jsonReq(ctx, "PATCH", c.fooPath(id), c.origin, newFooData(id, attrs))
if err != nil {
return RespBody[ResourceFooAttrs]{}, errors.Wrap(err)
}
resp, err := c.doFooReq(req)
return resp, errors.Wrap(err)
}
func (c *ClientHTTP) DelFoo(ctx context.Context, id string) (RespBody[any], error) {
if id == "" {
return RespBody[any]{}, errors.Wrap(ErrIDRequired)
}
req, err := newRequest(ctx, "DELETE", c.fooPath(id), c.origin, nil)
if err != nil {
return RespBody[any]{}, errors.Wrap(err)
}
err = c.authFn(req)
if err != nil {
return RespBody[any]{}, errors.Wrap(err)
}
resp, err := doJSON[any](c.c, req)
return resp, errors.Wrap(err)
}
func (c *ClientHTTP) doFooReq(req *http.Request) (RespBody[ResourceFooAttrs], error) {
if err := c.authFn(req); err != nil {
return RespBody[ResourceFooAttrs]{}, errors.Wrap(err)
}
resp, err := doJSON[ResourceFooAttrs](c.c, req)
return resp, errors.Wrap(err)
}
func (c *ClientHTTP) fooPath(id string) string {
u := c.addr + "/v1/foos"
if id == "" {
return u
}
return u + "/" + id
}
func newFooData[Attr Attrs](id string, attrs Attr) Data[Attr] {
return Data[Attr]{
Type: resourceTypeFoo,
ID: id,
Attrs: attrs,
}
}
// jsonReq here uses generics to provide feedback to developers when they provide some other field.
// This improves the feedback loop working with these methods. If they copy pasta wrong and provide
// ReqBody[Attr] instead, this will reject that.
func jsonReq[Attr Attrs](ctx context.Context, method, path, origin string, v Data[Attr]) (*http.Request, error) {
reqBody := ReqBody[Attr]{Data: v}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(reqBody); err != nil {
return nil, errors.Wrap(err, "failed to json encode request body")
}
req, err := newRequest(ctx, method, path, origin, &buf)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return req, nil
}
func newRequest(ctx context.Context, method, path, origin string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, method, path, body)
if err != nil {
return nil, err
}
// add origin and user agent to track SDK usage. Incredibly helpful!
req.Header.Set("Origin", origin)
req.Header.Set("User-Agent", "allsrvc (github.com/jsteenb2/allsrvc) / "+version)
return req, nil
}
func doJSON[Attr Attrs](c *http.Client, req *http.Request) (RespBody[Attr], error) {
resp, err := c.Do(req)
if err != nil {
return *new(RespBody[Attr]), errors.Wrap(err)
}
defer func() {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}()
// put an upper limit on how much data we'll read off the wire. A little bit of protection
// from a resource exhaustion attack.
b, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) // 1MB limit
if err != nil {
return *new(RespBody[Attr]), errors.Wrap(err, "failed to read response body")
}
if resp.Header.Get("Content-Type") != "application/json" {
return *new(RespBody[Attr]), errors.Wrap(err, "invalid content type received", errors.KVs("content", string(b)))
}
var respBody RespBody[Attr]
if err := json.Unmarshal(b, &respBody); err != nil {
return *new(RespBody[Attr]), errors.Wrap(err)
}
return respBody, nil
}