-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
78 lines (65 loc) · 1.59 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
package nodeless
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
// New creates a new Nodeless client.
func New(config Config) (*Client, error) {
if err := config.Validate(); err != nil {
return nil, err
}
return &Client{
config: config,
}, nil
}
// Client implements the Nodeless API.
// Use 'New' to instantiate.
type Client struct {
config Config
}
func (c *Client) authHeader() string {
return fmt.Sprintf("Bearer %s", c.config.APIKey)
}
func (c *Client) do(ctx context.Context, method, endpoint string, body, resp any) error {
var payload io.Reader
if body != nil {
jsonb, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("json marshal: %w", err)
}
payload = bytes.NewBuffer(jsonb)
}
req, err := http.NewRequestWithContext(ctx, method, endpoint, payload)
if err != nil {
return fmt.Errorf("http NewRequest: %w", err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", c.authHeader())
req.Header.Set("Content-Type", "application/json")
result, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer result.Body.Close()
if result.StatusCode > 300 {
var resp struct {
Message string `json:"message"`
}
if err := json.NewDecoder(result.Body).Decode(&resp); err != nil {
return fmt.Errorf("json decode: %w", err)
}
return parseError(resp.Message)
}
// NOTE: delete requests return 200 with no body
if method == http.MethodDelete {
return nil
}
if err := json.NewDecoder(result.Body).Decode(resp); err != nil {
return fmt.Errorf("json decode: %w", err)
}
return nil
}