2016-11-24 13:18:40 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2016-12-08 08:16:43 +00:00
|
|
|
"github.com/dannyvankooten/ana/db"
|
2016-11-24 13:18:40 +00:00
|
|
|
"encoding/json"
|
|
|
|
)
|
|
|
|
|
|
|
|
// URL: /api/screen-resolutions
|
|
|
|
var GetScreenResolutionsHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2016-11-26 16:19:15 +00:00
|
|
|
before, after := getRequestedPeriods(r)
|
2016-11-24 13:18:40 +00:00
|
|
|
|
|
|
|
// get total
|
2016-12-08 08:16:43 +00:00
|
|
|
stmt, err := db.Conn.Prepare(`
|
2016-11-24 13:18:40 +00:00
|
|
|
SELECT
|
2016-12-10 13:16:05 +00:00
|
|
|
COUNT(DISTINCT(pv.visitor_id))
|
|
|
|
FROM pageviews pv
|
|
|
|
WHERE UNIX_TIMESTAMP(pv.timestamp) <= ? AND UNIX_TIMESTAMP(pv.timestamp) >= ?`)
|
2016-11-24 13:18:40 +00:00
|
|
|
checkError(err)
|
|
|
|
defer stmt.Close()
|
|
|
|
var total float32
|
2016-11-26 16:19:15 +00:00
|
|
|
stmt.QueryRow(before, after).Scan(&total)
|
2016-11-24 13:18:40 +00:00
|
|
|
|
|
|
|
// get rows
|
2016-12-08 08:16:43 +00:00
|
|
|
stmt, err = db.Conn.Prepare(`
|
2016-11-24 13:18:40 +00:00
|
|
|
SELECT
|
2016-12-10 13:16:05 +00:00
|
|
|
v.screen_resolution,
|
|
|
|
COUNT(DISTINCT(pv.visitor_id)) AS count
|
|
|
|
FROM pageviews pv
|
|
|
|
LEFT JOIN visitors v ON v.id = pv.visitor_id
|
|
|
|
WHERE UNIX_TIMESTAMP(pv.timestamp) <= ? AND UNIX_TIMESTAMP(pv.timestamp) >= ?
|
|
|
|
GROUP BY v.screen_resolution
|
2016-11-25 12:38:20 +00:00
|
|
|
ORDER BY count DESC
|
|
|
|
LIMIT ?`)
|
2016-11-24 13:18:40 +00:00
|
|
|
checkError(err)
|
|
|
|
defer stmt.Close()
|
2016-11-26 16:19:15 +00:00
|
|
|
rows, err := stmt.Query(before, after, defaultLimit)
|
2016-11-24 13:18:40 +00:00
|
|
|
checkError(err)
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
results := make([]Datapoint, 0)
|
|
|
|
for rows.Next() {
|
|
|
|
var d Datapoint
|
|
|
|
err = rows.Scan(&d.Label, &d.Count);
|
|
|
|
checkError(err)
|
|
|
|
|
|
|
|
d.Percentage = float32(d.Count) / total * 100
|
|
|
|
results = append(results, d)
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
json.NewEncoder(w).Encode(results)
|
|
|
|
})
|