-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
91 lines (73 loc) · 1.73 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package api
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"strings"
"time"
"github.com/hashicorp/go-retryablehttp"
)
// HostURL - Default Warpstream URL.
const HostURL string = "https://api.prod.us-east-1.warpstream.com/api/v1"
// Client.
type Client struct {
HostURL string
HTTPClient *retryablehttp.Client
Token string
}
// NewClient.
func NewClient(host string, token *string) (*Client, error) {
retryClient := retryablehttp.NewClient()
retryClient.RetryMax = 5
retryClient.StandardClient().Timeout = 10 * time.Second
c := Client{
HTTPClient: retryClient,
// Default Warpstream URL
HostURL: HostURL,
}
if host != "" {
c.HostURL = host
}
// If token not provided, return empty client
if token == nil {
return &c, nil
}
c.Token = *token
return &c, nil
}
func (c *Client) doRequest(req *http.Request, authToken *string) ([]byte, error) {
d, err := httputil.DumpRequest(req, true)
if err != nil {
return nil, fmt.Errorf("internal client error: %s", err)
}
log.Printf("%q\n", d)
token := c.Token
if authToken != nil {
token = *authToken
}
req.Header.Set("warpstream-api-key", token)
req.Header.Set("Content-Type", "application/json")
retryReq, err := retryablehttp.FromRequest(req)
if err != nil {
return nil, err
}
res, err := c.HTTPClient.Do(retryReq)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
log.Printf("%q\n", body)
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status: %d, body: %s", res.StatusCode, body)
}
if strings.Contains(string(body), "internal server error") {
return nil, fmt.Errorf("status: 500, body: internal server error")
}
return body, err
}