-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
79 lines (70 loc) · 2.28 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
package jape
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
// A Client provides methods for interacting with an API server.
type Client struct {
BaseURL string
Password string
}
func (c *Client) req(ctx context.Context, method string, route string, data, resp interface{}) error {
var body io.Reader
if data != nil {
js, _ := json.Marshal(data)
body = bytes.NewReader(js)
}
req, err := http.NewRequestWithContext(ctx, method, fmt.Sprintf("%v%v", c.BaseURL, route), body)
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
if c.Password != "" {
req.SetBasicAuth("", c.Password)
}
r, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer io.Copy(io.Discard, r.Body)
defer r.Body.Close()
if !(200 <= r.StatusCode && r.StatusCode < 300) {
err, _ := io.ReadAll(r.Body)
return errors.New(string(err))
}
if resp == nil {
return nil
}
return json.NewDecoder(r.Body).Decode(resp)
}
// GET performs a GET request, decoding the response into r.
func (c *Client) GET(ctx context.Context, route string, r interface{}) error {
return c.req(ctx, http.MethodGet, route, nil, r)
}
// POST performs a POST request. If d is non-nil, it is encoded as the request
// body. If r is non-nil, the response is decoded into it.
func (c *Client) POST(ctx context.Context, route string, d, r interface{}) error {
return c.req(ctx, http.MethodPost, route, d, r)
}
// PUT performs a PUT request, encoding d as the request body.
func (c *Client) PUT(ctx context.Context, route string, d interface{}) error {
return c.req(ctx, http.MethodPut, route, d, nil)
}
// DELETE performs a DELETE request.
func (c *Client) DELETE(ctx context.Context, route string) error {
return c.req(ctx, http.MethodDelete, route, nil, nil)
}
// PATCH performs a PATCH request. If d is non-nil, it is encoded as the request
// body. If r is non-nil, the response is decoded into it.
func (c *Client) PATCH(ctx context.Context, route string, d, r interface{}) error {
return c.req(ctx, http.MethodPatch, route, d, r)
}
// Custom is a no-op that simply declares the request and response types used by
// a client method. This allows japecheck to be used on endpoints that do not
// speak JSON.
func (c *Client) Custom(method, route string, d, r interface{}) {}