-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch.go
73 lines (60 loc) · 1.47 KB
/
fetch.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
package main
import (
"encoding/json"
"io"
"net/http"
"time"
)
// Request an endpoint without a response body.
func Request(method, path string, headers map[string]string) (*http.Response, error) {
cfg, err := loadConfig()
if err != nil {
return nil, err
}
url := cfg.ServerURL + "/api/" + path
headers["token"] = cfg.AdminToken
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
for k, v := range headers {
req.Header.Set(k, v)
}
c := &http.Client{Timeout: time.Second * 10}
res, err := c.Do(req)
if err != nil {
return res, err
}
return res, res.Body.Close()
}
// RequestJSON requests an endpoint and converts a JSON response.
// The response body will be closed.
func RequestJSON(method, path string, headers map[string]string, out interface{}) (*http.Response, error) {
cfg, err := loadConfig()
if err != nil {
return nil, err
}
url := cfg.ServerURL + "/api/" + path
headers["token"] = cfg.AdminToken
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
for k, v := range headers {
req.Header.Set(k, v)
}
c := &http.Client{Timeout: time.Second * 10}
res, err := c.Do(req)
if err != nil {
return res, err
}
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted && res.StatusCode != http.StatusCreated {
return res, nil
}
defer res.Body.Close()
buf, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
return res, json.Unmarshal(buf, out)
}