fathom/api/pageviews.go

76 lines
2.1 KiB
Go
Raw Normal View History

2016-11-21 16:36:25 +00:00
package api
import (
2016-12-11 13:50:01 +00:00
"encoding/json"
"github.com/dannyvankooten/ana/count"
"github.com/dannyvankooten/ana/db"
"github.com/dannyvankooten/ana/models"
"net/http"
2016-11-21 16:36:25 +00:00
)
// URL: /api/pageviews
2016-11-22 21:33:50 +00:00
var GetPageviewsHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2016-12-11 13:50:01 +00:00
before, after := getRequestedPeriods(r)
2016-12-11 15:23:13 +00:00
stmt, err := db.Conn.Prepare(`
SELECT
p.hostname,
p.path,
SUM(a.count) AS count,
"0" AS count_unique
FROM archive a
LEFT JOIN pages p ON p.id = a.value
WHERE metric = 'pageviews.page' AND UNIX_TIMESTAMP(a.date) <= ? AND UNIX_TIMESTAMP(a.date) >= ?
GROUP BY p.path, p.hostname
ORDER BY count DESC
LIMIT ?`)
// stmt, err := db.Conn.Prepare(`SELECT
// p.hostname,
// p.path,
// COUNT(*) AS pageviews,
// COUNT(DISTINCT(pv.visitor_id)) AS pageviews_unique
// FROM pageviews pv
// LEFT JOIN pages p ON pv.page_id = p.id
// WHERE UNIX_TIMESTAMP(pv.timestamp) <= ? AND UNIX_TIMESTAMP(pv.timestamp) >= ?
// GROUP BY p.path, p.hostname
// ORDER BY pageviews DESC
// LIMIT ?`)
2016-12-11 13:50:01 +00:00
checkError(err)
defer stmt.Close()
rows, err := stmt.Query(before, after, defaultLimit)
checkError(err)
defer rows.Close()
results := make([]models.Pageviews, 0)
for rows.Next() {
var p models.Pageviews
err = rows.Scan(&p.Hostname, &p.Path, &p.Count, &p.CountUnique)
checkError(err)
results = append(results, p)
}
err = rows.Err()
checkError(err)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(results)
2016-11-22 21:33:50 +00:00
})
2016-11-23 19:30:09 +00:00
// URL: /api/pageviews/count
var GetPageviewsCountHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2016-12-11 13:50:01 +00:00
before, after := getRequestedPeriods(r)
result := count.Pageviews(before, after)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(result)
})
// URL: /api/pageviews/group/day
var GetPageviewsPeriodCountHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2016-12-11 13:50:01 +00:00
before, after := getRequestedPeriods(r)
results := count.PageviewsPerDay(before, after)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(results)
2016-11-23 19:30:09 +00:00
})