@@ -3,18 +3,35 @@ package mixpanel
33import (
44 "encoding/base64"
55 "encoding/json"
6- "errors"
76 "fmt"
87 "io/ioutil"
98 "net/http"
109 "time"
1110)
1211
13- var (
14- ErrTrackFailed = errors .New ("Mixpanel did not return 1 when tracking" )
12+ var IgnoreTime * time.Time = & time.Time {}
1513
16- IgnoreTime * time.Time = & time.Time {}
17- )
14+ type MixpanelError struct {
15+ URL string
16+ Err error
17+ }
18+
19+ func (err * MixpanelError ) Cause () error {
20+ return err .Err
21+ }
22+
23+ func (err * MixpanelError ) Error () string {
24+ return "mixpanel: " + err .Err .Error ()
25+ }
26+
27+ type ErrTrackFailed struct {
28+ Body string
29+ Resp * http.Response
30+ }
31+
32+ func (err * ErrTrackFailed ) Error () string {
33+ return fmt .Sprintf ("Mixpanel did not return 1 when tracking: %s" , err .Body )
34+ }
1835
1936// The Mixapanel struct store the mixpanel endpoint and the project token
2037type Mixpanel interface {
@@ -131,32 +148,43 @@ func (m *mixpanel) Update(distinctId string, u *Update) error {
131148 return m .send ("engage" , params , autoGeolocate )
132149}
133150
134- func (m * mixpanel ) to64 (data string ) string {
135- bytes := []byte (data )
136- return base64 .StdEncoding .EncodeToString (bytes )
151+ func (m * mixpanel ) to64 (data []byte ) string {
152+ return base64 .StdEncoding .EncodeToString (data )
137153}
138154
139155func (m * mixpanel ) send (eventType string , params interface {}, autoGeolocate bool ) error {
140- dataJSON , _ := json .Marshal (params )
141- data := string (dataJSON )
156+ data , err := json .Marshal (params )
157+
158+ if err != nil {
159+ return err
160+ }
142161
143162 url := m .ApiURL + "/" + eventType + "?data=" + m .to64 (data )
144163
145164 if autoGeolocate {
146165 url += "&ip=1"
147166 }
148167
149- if resp , err := m .Client .Get (url ); err != nil {
150- return fmt .Errorf ("mixpanel: %s" , err .Error ())
151- } else {
152- defer resp .Body .Close ()
153- body , bodyErr := ioutil .ReadAll (resp .Body )
154- if bodyErr != nil {
155- return fmt .Errorf ("mixpanel: %s" , bodyErr .Error ())
156- }
157- if string (body ) != "1" && string (body ) != "1\n " {
158- return ErrTrackFailed
159- }
168+ wrapErr := func (err error ) error {
169+ return & MixpanelError {URL : url , Err : err }
170+ }
171+
172+ resp , err := m .Client .Get (url )
173+
174+ if err != nil {
175+ return wrapErr (err )
176+ }
177+
178+ defer resp .Body .Close ()
179+
180+ body , bodyErr := ioutil .ReadAll (resp .Body )
181+
182+ if bodyErr != nil {
183+ return wrapErr (bodyErr )
184+ }
185+
186+ if strBody := string (body ); strBody != "1" && strBody != "1\n " {
187+ return wrapErr (& ErrTrackFailed {Body : strBody , Resp : resp })
160188 }
161189
162190 return nil
0 commit comments