-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
97 lines (77 loc) · 2.08 KB
/
client.go
File metadata and controls
97 lines (77 loc) · 2.08 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
package mcsmapi
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
type Client struct {
baseURL string
token string
Dashboard *dashboardClient
Daemon *daemonClient
Instance *instanceClient
File *fileClient
User *userClient
Image *imageClient
httpClient *http.Client
}
const HTTPTimeout = 10
func NewClient(token string, baseURL string, httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = &http.Client{
Timeout: HTTPTimeout * time.Second,
}
}
client := &Client{
token: token,
baseURL: baseURL,
httpClient: httpClient,
}
client.Daemon = newDaemonClient(client)
client.Dashboard = newDashboardClient(client)
client.File = newFileClient(client)
client.Instance = newInstanceClient(client)
client.User = newUserClient(client)
client.Image = newImageClient(client)
return client
}
func (c *Client) createRequest(endpoint string, body any, method string) (*http.Request, error) {
bodyBytes, err := json.Marshal(body)
if err != nil {
return nil, err
}
sep := "?"
if strings.Contains(endpoint, "?") {
sep = "&"
}
apiQuery := sep + "apikey=" + c.token
fmt.Println(c.baseURL + "/api/" + endpoint + apiQuery)
req, err := http.NewRequest(method, c.baseURL+"/api/"+endpoint+apiQuery, bytes.NewBuffer(bodyBytes))
return req, err
}
func (c *Client) doRequest(req *http.Request) (*http.Response, error) {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Requested-With", "XMLHttpRequest")
return c.httpClient.Do(req)
}
func (c *Client) sendRequest(method, endpoint string, body any) (*http.Response, error) {
req, err := c.createRequest(endpoint, body, method)
if err != nil {
return nil, err
}
return c.doRequest(req)
}
func (c *Client) doRequestAndDecode(method, endpoint string, body, out any) error {
resp, err := c.sendRequest(method, endpoint, body)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
return fmt.Errorf("decode response failed: %w", err)
}
return nil
}