-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmixpanel.go
78 lines (61 loc) · 1.45 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
package mixpanel
import (
"encoding/json"
"fmt"
"net/http"
"strings"
)
// Mixpanel client config
type Config struct {
Verbose int
Token string
}
const (
TrackEndpoint = "https://api.mixpanel.com/track#live-event"
)
// NewClient initializes new config
func NewClient(token string, verbose int) *Config {
return &Config{
Verbose: verbose,
Token: token,
}
}
// Track is mixpanel tracking event
type Track struct {
Event string `json:"event"`
Properties TrackProperties `json:"properties"`
}
type TrackProperties struct {
// Unique user ID
DistinctID string `json:"distinct_id"`
// Event data.
EventData string `json:"event_data"`
// Project token
Token string `json:"token"`
// User remote IP address
IP string `json:"ip"`
// Event time
Time int64 `json:"time"`
// Unique event ID
InsertID string `json:"$insert_id"`
}
// Track sends mixpanel trackevent - https://developer.mixpanel.com/reference/events#track-event
func (con Config) Track(track Track) error {
track.Properties.Token = con.Token
data, err := json.Marshal(track)
if err != nil {
return err
}
reqBody := fmt.Sprintf("data=%s", string(data))
req, err := http.NewRequest("POST", TrackEndpoint, strings.NewReader(reqBody))
if err != nil {
return err
}
req.Header.Set("Accept", "text/plain")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
return resp.Body.Close()
}