Repository navigation
Expand file tree
/
Copy pathclient.go
More file actions
144 lines (135 loc) · 3.38 KB
/
Copy pathclient.go
File metadata and controls
144 lines (135 loc) · 3.38 KB
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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// Client is a minimal management API client (`.json` paths, Bearer pat_…).
type Client struct {
Endpoint string
Token string
HTTP *http.Client
}
// APIError is a non-2xx response, decoded from {error:{code,message,details}}.
type APIError struct {
Status int
Code string `json:"code"`
Message string `json:"message"`
Details map[string]any `json:"details"`
}
func (e *APIError) Error() string {
msg := e.Message
if msg == "" {
msg = http.StatusText(e.Status)
}
s := fmt.Sprintf("API error %d", e.Status)
if e.Code != "" {
s += " (" + e.Code + ")"
}
s += ": " + msg
if len(e.Details) > 0 {
if b, err := json.Marshal(e.Details); err == nil {
s += " " + string(b)
}
}
return s
}
func newClient(endpoint, token string) *Client {
return &Client{Endpoint: strings.TrimRight(endpoint, "/"), Token: token, HTTP: &http.Client{Timeout: 60 * time.Second}}
}
// jsonPath appends ".json" to an app path unless it already has an
// extension, keeping any query string.
func jsonPath(p string) string {
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
path, query, hasQuery := strings.Cut(p, "?")
last := path[strings.LastIndex(path, "/")+1:]
if path != "/" && !strings.Contains(last, ".") {
path += ".json"
}
if hasQuery {
return path + "?" + query
}
return path
}
// Raw performs a request and returns status and body without decoding.
func (c *Client) Raw(ctx context.Context, method, path string, body []byte) (int, []byte, error) {
var reader io.Reader
if body != nil {
reader = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, c.Endpoint+jsonPath(path), reader)
if err != nil {
return 0, nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "privatus-cli/"+version)
if c.Token != "" {
req.Header.Set("Authorization", "Bearer "+c.Token)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.HTTP.Do(req)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(io.LimitReader(resp.Body, 64<<20))
return resp.StatusCode, b, err
}
// Do sends body (JSON-encoded if non-nil) and decodes `data` into out and
// `meta` into meta (both optional).
func (c *Client) Do(ctx context.Context, method, path string, query url.Values, body, out any, meta *map[string]any) error {
if len(query) > 0 {
path += "?" + query.Encode()
}
var raw []byte
if body != nil {
var err error
if raw, err = json.Marshal(body); err != nil {
return err
}
}
status, b, err := c.Raw(ctx, method, path, raw)
if err != nil {
return err
}
var env struct {
Data json.RawMessage `json:"data"`
Meta map[string]any `json:"meta"`
Error *APIError `json:"error"`
}
decodeErr := json.Unmarshal(b, &env)
if status >= 300 {
apiErr := env.Error
if apiErr == nil {
apiErr = &APIError{Message: strings.TrimSpace(truncate(string(b), 200))}
}
apiErr.Status = status
return apiErr
}
if decodeErr != nil && len(bytes.TrimSpace(b)) > 0 {
return fmt.Errorf("decoding response: %w", decodeErr)
}
if meta != nil {
*meta = env.Meta
}
if out != nil && len(env.Data) > 0 {
return json.Unmarshal(env.Data, out)
}
return nil
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "…"
}