-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
73 lines (57 loc) · 1.56 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
package mixpanel
import (
"bufio"
"context"
"fmt"
"io"
"net/http"
"time"
"github.com/cuvva/cuvva-public-go/lib/cher"
)
type Client struct {
*http.Client
}
type BasicAuthTransport struct {
APISecret string
}
func (ba BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.SetBasicAuth(ba.APISecret, "")
return http.DefaultTransport.RoundTrip(req)
}
func NewClient(apiSecret string) *Client {
basicAuthTransport := BasicAuthTransport{APISecret: apiSecret}
httpClient := Client{&http.Client{
Transport: basicAuthTransport,
}}
return &httpClient
}
func (c Client) Export(ctx context.Context, fromDate, toDate time.Time) (ers *ExportResultScanner, err error) {
// https://developer.mixpanel.com/docs/exporting-raw-data
urlTemplate := `https://data.mixpanel.com/api/2.0/export/?from_date=%s&to_date=%s`
url := fmt.Sprintf(urlTemplate,
fromDate.Format("2006-01-02"),
toDate.Format("2006-01-02"),
)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
resp, err := c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusTooManyRequests {
return nil, cher.New(cher.TooManyRequests, nil)
}
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, cher.New(cher.Unknown, cher.M{"error": err})
}
return nil, cher.New(cher.Unknown, cher.M{"response_status": resp.Status,
"response_body": string(body)})
}
bns := bufio.NewScanner(resp.Body)
return NewExportResultScanner(*bns), nil
}