-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
211 lines (181 loc) · 5.07 KB
/
client.go
File metadata and controls
211 lines (181 loc) · 5.07 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
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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
// Client handles API requests
type Client struct {
baseURL string
accessToken string
httpClient *http.Client
}
// NewClient creates a new API client
func NewClient(baseURL, accessToken string) *Client {
return &Client{
baseURL: strings.TrimSuffix(baseURL, "/"),
accessToken: accessToken,
httpClient: &http.Client{Timeout: 30 * time.Second},
}
}
// request makes an HTTP request to the API
func (c *Client) request(method, path string, params map[string]interface{}, body interface{}) (map[string]interface{}, error) {
urlStr := c.baseURL + path
// Add query parameters
if len(params) > 0 && (method == "GET" || method == "DELETE") {
u, _ := url.Parse(urlStr)
q := u.Query()
for k, v := range params {
if v == nil {
continue
}
switch val := v.(type) {
case string:
if val != "" {
q.Set(k, val)
}
case []string:
for _, s := range val {
q.Add(k, s)
}
case int:
q.Set(k, strconv.Itoa(val))
case bool:
q.Set(k, strconv.FormatBool(val))
default:
q.Set(k, fmt.Sprintf("%v", val))
}
}
u.RawQuery = q.Encode()
urlStr = u.String()
}
var reqBody io.Reader
if body != nil {
jsonData, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("failed to marshal request body: %w", err)
}
reqBody = bytes.NewBuffer(jsonData)
}
req, err := http.NewRequest(method, urlStr, reqBody)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.accessToken)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode >= 400 {
var errResp map[string]interface{}
if json.Unmarshal(respBody, &errResp) == nil {
if errMsg, ok := errResp["error"].(string); ok {
return nil, fmt.Errorf("API error (%d): %s", resp.StatusCode, errMsg)
}
}
return nil, fmt.Errorf("API error (%d): %s", resp.StatusCode, string(respBody))
}
if len(respBody) == 0 || resp.StatusCode == 204 {
return map[string]interface{}{"success": true}, nil
}
// Try parsing as object first, then as array
var result map[string]interface{}
if err := json.Unmarshal(respBody, &result); err != nil {
// Try parsing as array
var arrayResult []interface{}
if err := json.Unmarshal(respBody, &arrayResult); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
// Wrap array in a map for consistent handling
return map[string]interface{}{"items": arrayResult}, nil
}
return result, nil
}
// uploadFile uploads a file using multipart form with correct mime type
func (c *Client) uploadFile(path, filePath string) (map[string]interface{}, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
// Detect mime type from extension
filename := filepath.Base(filePath)
ext := filepath.Ext(filePath)
mimeType := mime.TypeByExtension(ext)
if mimeType == "" {
mimeType = "application/octet-stream"
}
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// Create form file with correct Content-Type
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, filename))
h.Set("Content-Type", mimeType)
part, err := writer.CreatePart(h)
if err != nil {
return nil, fmt.Errorf("failed to create form file: %w", err)
}
if _, err := io.Copy(part, file); err != nil {
return nil, fmt.Errorf("failed to copy file: %w", err)
}
writer.Close()
req, err := http.NewRequest("POST", c.baseURL+path, body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.accessToken)
req.Header.Set("Content-Type", writer.FormDataContentType())
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("API error (%d): %s", resp.StatusCode, string(respBody))
}
var result map[string]interface{}
if err := json.Unmarshal(respBody, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
return result, nil
}
func getClient() (*Client, error) {
token := accessToken
if token == "" {
token = os.Getenv("BEEPER_ACCESS_TOKEN")
}
if token == "" {
return nil, fmt.Errorf("access token required. Set BEEPER_ACCESS_TOKEN or use --token")
}
url := baseURL
if url == "" {
url = os.Getenv("BEEPER_DESKTOP_BASE_URL")
}
if url == "" {
url = defaultBaseURL
}
return NewClient(url, token), nil
}