-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
74 lines (57 loc) · 1.55 KB
/
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
package logclient
import (
"fmt"
"io"
"net/http"
json "github.com/goccy/go-json"
)
type CtApiError struct {
Reason string
HttpStatusCode int
}
func (e *CtApiError) Error() string {
return e.Reason
}
var Logs = make(LogMap)
var httpClients []http.Client
func init() {
httpClients = make([]http.Client, 0)
}
func AddHttpClient(client http.Client) {
httpClients = append(httpClients, client)
}
var counter int = 0
func getRequest[T any](url string) (*T, error) {
if len(httpClients) == 0 {
httpClients = append(httpClients, http.Client{})
}
counter += 1
var httpClientId int = counter % len(httpClients)
httpClient := httpClients[httpClientId]
var httpRequest *http.Request
var err error
if httpRequest, err = http.NewRequest(http.MethodGet, url, nil); err != nil {
return nil, err
}
var httpResponse *http.Response
if httpResponse, err = httpClient.Do(httpRequest); err != nil {
return nil, err
}
defer httpResponse.Body.Close()
var body []byte
if body, err = io.ReadAll(httpResponse.Body); err != nil {
return nil, err
}
if httpResponse.StatusCode != http.StatusOK {
switch httpResponse.StatusCode {
case http.StatusTooManyRequests:
return nil, &CtApiError{Reason: fmt.Sprintf("Too Many Requests: %s", url), HttpStatusCode: httpResponse.StatusCode}
}
return nil, &CtApiError{Reason: fmt.Sprintf("Http Status {%d}Not OK: %s", httpResponse.StatusCode, url), HttpStatusCode: httpResponse.StatusCode}
}
var response T
if err = json.Unmarshal(body, &response); err != nil {
return nil, err
}
return &response, nil
}