-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_client.go
83 lines (67 loc) · 1.54 KB
/
api_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
79
80
81
82
83
package client
import (
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"
"github.com/draganm/kartusche/common/auth"
)
func CallAPI(
baseURL, method, pth string,
q url.Values,
bodyEncoder func() (io.Reader, error),
responseCallback func(io.Reader) error,
expectedStatus int,
) error {
var tkn string
if !(strings.HasPrefix(pth, "/auth/") || strings.HasPrefix(pth, "auth/")) {
var err error
tkn, err = auth.GetTokenForServer(baseURL)
if err != nil {
return err
}
}
bu, err := url.Parse(baseURL)
if err != nil {
return fmt.Errorf("while parsing server base url: %w", err)
}
bu.Path = path.Join(bu.Path, pth)
if q != nil {
bu.RawQuery = q.Encode()
}
var body io.Reader
if bodyEncoder != nil {
body, err = bodyEncoder()
if err != nil {
return fmt.Errorf("while encoding body: %w", err)
}
}
req, err := http.NewRequest(method, bu.String(), body)
if err != nil {
return fmt.Errorf("while creating request: %w", err)
}
if tkn != "" {
req.Header.Set("Authorization", fmt.Sprintf("bearer %s", tkn))
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("while performing %s %s request: %w", method, pth, err)
}
defer res.Body.Close()
if res.StatusCode != expectedStatus {
bod, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("while reading response body: %w", err)
}
return fmt.Errorf("unexpected status %s: %s", res.Status, string(bod))
}
if responseCallback != nil {
err = responseCallback(res.Body)
if err != nil {
return err
}
}
return nil
}