/
track_handler.go
55 lines (46 loc) · 1.24 KB
/
track_handler.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
package server
import (
"net/http"
"time"
"github.com/skybox/skybox/db"
)
type trackHandler struct {
handler
}
func (h *trackHandler) install() {
h.server.Handle("/skybox.js", http.HandlerFunc(h.track)).Methods("GET")
h.server.Handle("/track.png", h.transact(http.HandlerFunc(h.track))).Methods("GET")
}
func (h *trackHandler) track(w http.ResponseWriter, r *http.Request) {
tx := h.transaction(r)
// Find account by API key.
a, err := tx.AccountByAPIKey(r.FormValue("apiKey"))
if err != nil {
http.Error(w, "invalid api key", http.StatusBadRequest)
return
}
// Extract event from URL parameters.
e := &db.Event{
UserID: r.FormValue("user.id"),
DeviceID: r.FormValue("device.id"),
Timestamp: time.Now().UTC(),
Channel: r.FormValue("channel"),
Resource: r.FormValue("resource"),
Action: r.FormValue("action"),
Data: make(map[string]interface{}),
}
if domain := r.FormValue("domain"); len(domain) > 0 {
e.Data["domain"] = domain
}
if path := r.FormValue("path"); len(path) > 0 {
e.Data["path"] = path
}
// Send event to Sky.
if err := a.Track(e); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write png to response.
b, _ := Asset("pixel.png")
w.Write(b)
}