This repository has been archived by the owner on Nov 24, 2023. It is now read-only.
forked from dukex/mixpanel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mixpanel.go
329 lines (260 loc) · 8.33 KB
/
mixpanel.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package mixpanel
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
)
var IgnoreTime *time.Time = &time.Time{}
type MixpanelError struct {
URL string
Err error
}
func (err *MixpanelError) Cause() error {
return err.Err
}
func (err *MixpanelError) Error() string {
return "mixpanel: " + err.Err.Error()
}
type ErrTrackFailed struct {
Message string
}
func (err *ErrTrackFailed) Error() string {
return fmt.Sprintf("mixpanel did not return 1 when tracking: %s", err.Message)
}
// Mixapanel struct store the mixpanel endpoint and the project token
type Mixpanel interface {
// Create a mixpanel event using the track api
Track(ctx context.Context, distinctId, eventName string, e *Event) error
// Create a mixpanel event using the import api
Import(ctx context.Context, distinctId, eventName string, e *Event) error
// Set properties for a mixpanel user.
// Deprecated: Use UpdateUser instead
Update(ctx context.Context, distinctId string, u *Update) error
// Set properties for a mixpanel user.
UpdateUser(ctx context.Context, distinctId string, u *Update) error
// Set properties for a mixpanel group.
UpdateGroup(ctx context.Context, groupKey, groupId string, u *Update) error
// Create an alias for an existing distinct id
Alias(ctx context.Context, distinctId, newId string) error
// Unions a profile property in mixpanel
UnionUser(ctx context.Context, distinctId string, u *Update) error
// Unions a group property in mixpanel
UnionGroup(ctx context.Context, groupId, groupKey string, u *Update) error
}
// The Mixapanel struct store the mixpanel endpoint and the project token
type mixpanel struct {
Client *http.Client
Token string
Secret string
ApiURL string
}
// A mixpanel event
type Event struct {
// IP-address of the user. Leave empty to use autodetect, or set to "0" to
// not specify an ip-address.
IP string
// Timestamp. Set to nil to use the current time.
Timestamp *time.Time
// Custom properties. At least one must be specified.
Properties map[string]interface{}
}
// An update of a user in mixpanel
type Update struct {
// IP-address of the user. Leave empty to use autodetect, or set to "0" to
// not specify an ip-address at all.
IP string
// Timestamp. Set to nil to use the current time, or IgnoreTime to not use a
// timestamp.
Timestamp *time.Time
// Update operation such as "$set", "$update" etc.
Operation string
// Custom properties. At least one must be specified.
Properties map[string]interface{}
}
// Alias create an alias for an existing distinct id
func (m *mixpanel) Alias(ctx context.Context, distinctId, newId string) error {
props := map[string]interface{}{
"token": m.Token,
"distinct_id": distinctId,
"alias": newId,
}
params := map[string]interface{}{
"event": "$create_alias",
"properties": props,
}
return m.send(ctx, "track", params, false)
}
// Track create an event for an existing distinct id
func (m *mixpanel) Track(ctx context.Context, distinctId, eventName string, e *Event) error {
props := map[string]interface{}{
"token": m.Token,
"distinct_id": distinctId,
}
if e.IP != "" {
props["ip"] = e.IP
}
if e.Timestamp != nil {
props["time"] = e.Timestamp.Unix()
}
for key, value := range e.Properties {
props[key] = value
}
params := map[string]interface{}{
"event": eventName,
"properties": props,
}
autoGeolocate := e.IP == ""
return m.send(ctx, "track", params, autoGeolocate)
}
// Import create an event for an existing distinct id
// See https://developer.mixpanel.com/docs/importing-old-events
func (m *mixpanel) Import(ctx context.Context, distinctId, eventName string, e *Event) error {
props := map[string]interface{}{
"token": m.Token,
"distinct_id": distinctId,
}
if e.IP != "" {
props["ip"] = e.IP
}
if e.Timestamp != nil {
props["time"] = e.Timestamp.Unix()
}
for key, value := range e.Properties {
props[key] = value
}
params := map[string]interface{}{
"event": eventName,
"properties": props,
}
autoGeolocate := e.IP == ""
return m.send(ctx, "import", params, autoGeolocate)
}
// Update updates a user in mixpanel. See
// https://mixpanel.com/help/reference/http#people-analytics-updates
// Deprecated: Use UpdateUser instead
func (m *mixpanel) Update(ctx context.Context, distinctId string, u *Update) error {
return m.UpdateUser(ctx, distinctId, u)
}
// UpdateUser: Updates a user in mixpanel. See
// https://mixpanel.com/help/reference/http#people-analytics-updates
func (m *mixpanel) UpdateUser(ctx context.Context, distinctId string, u *Update) error {
params := map[string]interface{}{
"$token": m.Token,
"$distinct_id": distinctId,
}
if u.IP != "" {
params["$ip"] = u.IP
}
if u.Timestamp == IgnoreTime {
params["$ignore_time"] = true
} else if u.Timestamp != nil {
params["$time"] = u.Timestamp.Unix()
}
params[u.Operation] = u.Properties
autoGeolocate := u.IP == ""
return m.send(ctx, "engage#profile-set", params, autoGeolocate)
}
// UpdateGroup: Updates a group in mixpanel. See
// https://api.mixpanel.com/groups#group-set
func (m *mixpanel) UpdateGroup(ctx context.Context, groupKey, groupId string, u *Update) error {
params := map[string]interface{}{
"$token": m.Token,
"$group_id": groupId,
"$group_key": groupKey,
}
params[u.Operation] = u.Properties
return m.send(ctx, "groups#group-set", params, false)
}
// UnionUser: Unions a profile property in mixpanel. See
// https://api.mixpanel.com/engage#profile-union
func (m *mixpanel) UnionUser(ctx context.Context, userID string, u *Update) error {
params := map[string]interface{}{
"$token": m.Token,
"$distinct_id": userID,
}
params[u.Operation] = u.Properties
return m.send(ctx, "engage#profile-union", params, false)
}
// UnionGroup: Unions a group property in mixpanel. See
// https://api.mixpanel.com/groups#group-union
func (m *mixpanel) UnionGroup(ctx context.Context, groupId, groupKey string, u *Update) error {
params := map[string]interface{}{
"$token": m.Token,
"$group_id": groupId,
"$group_key": groupKey,
}
params[u.Operation] = u.Properties
return m.send(ctx, "groups#group-union", params, false)
}
func (m *mixpanel) to64(data []byte) string {
return base64.StdEncoding.EncodeToString(data)
}
func (m *mixpanel) send(ctx context.Context, eventType string, params interface{}, autoGeolocate bool) error {
data, err := json.Marshal(params)
if err != nil {
return err
}
url := m.ApiURL + "/" + eventType + "?verbose=1"
wrapErr := func(err error) error {
return &MixpanelError{URL: url, Err: err}
}
request, err := http.NewRequestWithContext(ctx, "POST", url, strings.NewReader("data="+m.to64(data)))
if err != nil {
return wrapErr(err)
}
if m.Secret != "" {
request.SetBasicAuth(m.Secret, "")
}
resp, err := m.Client.Do(request)
if err != nil {
return wrapErr(err)
}
defer resp.Body.Close()
body, bodyErr := ioutil.ReadAll(resp.Body)
if bodyErr != nil {
return wrapErr(bodyErr)
}
type verboseResponse struct {
Error string `json:"error"`
Status int `json:"status"`
}
var jsonBody verboseResponse
json.Unmarshal(body, &jsonBody)
if jsonBody.Status != 1 {
errMsg := fmt.Sprintf("error=%s; status=%d; httpCode=%d", jsonBody.Error, jsonBody.Status, resp.StatusCode)
return wrapErr(&ErrTrackFailed{Message: errMsg})
}
return nil
}
// New returns the client instance. If apiURL is blank, the default will be used
// ("https://api.mixpanel.com").
func New(token, apiURL string) Mixpanel {
return NewFromClient(http.DefaultClient, token, apiURL)
}
// NewWithSecret returns the client instance using a secret.If apiURL is blank,
// the default will be used ("https://api.mixpanel.com").
func NewWithSecret(token, secret, apiURL string) Mixpanel {
return NewFromClientWithSecret(http.DefaultClient, token, secret, apiURL)
}
// NewFromClient creates a client instance using the specified client instance. This is useful
// when using a proxy.
func NewFromClient(c *http.Client, token, apiURL string) Mixpanel {
return NewFromClientWithSecret(c, token, "", apiURL)
}
// NewFromClientWithSecret creates a client instance using the specified client instance and secret.
func NewFromClientWithSecret(c *http.Client, token, secret, apiURL string) Mixpanel {
if apiURL == "" {
apiURL = "https://api.mixpanel.com"
}
return &mixpanel{
Client: c,
Token: token,
Secret: secret,
ApiURL: apiURL,
}
}