-
Notifications
You must be signed in to change notification settings - Fork 0
/
metric_fetcher.go
105 lines (90 loc) · 2.57 KB
/
metric_fetcher.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package google_analytics
import (
"context"
"fmt"
"log"
"strconv"
ga "google.golang.org/api/analyticsreporting/v4"
"google.golang.org/api/option"
)
type (
// MetricFetcher retrieves metrics from Google Analytics.
MetricFetcher interface {
PageViewsByPath(startDate, endDate string) ([]PageViewCount, error)
}
// PageViewCount represents the number of pageviews for a given URL path.
PageViewCount struct {
Path string
Views uint64
}
// defaultMetricFetcher implements MetricFetcher using a real Google Analytics
// backend.
defaultMetricFetcher struct {
svc *ga.Service
viewID string
}
)
// New creates a new MetricFetcher instance.
func New(keyFilePath string, viewID string) (mf MetricFetcher, err error) {
svc, err := ga.NewService(context.Background(), option.WithCredentialsFile(keyFilePath))
if err != nil {
return defaultMetricFetcher{nil, ""}, err
}
return defaultMetricFetcher{svc, viewID}, nil
}
// PageViewsByPath retrieves the total pageviews for each URL path over a given
// date range.
func (r defaultMetricFetcher) PageViewsByPath(startDate, endDate string) ([]PageViewCount, error) {
res, err := getReport(r.svc, r.viewID, startDate, endDate)
if err != nil {
return []PageViewCount{}, err
}
return extractPageViews(res)
}
func getReport(svc *ga.Service, viewID string, startDate string, endDate string) (*ga.GetReportsResponse, error) {
req := &ga.GetReportsRequest{
ReportRequests: []*ga.ReportRequest{
{
ViewId: viewID,
DateRanges: []*ga.DateRange{
{StartDate: startDate, EndDate: endDate},
},
Metrics: []*ga.Metric{
{Expression: "ga:pageviews"},
},
Dimensions: []*ga.Dimension{
{Name: "ga:pagePath"},
},
},
},
}
res, err := svc.Reports.BatchGet(req).Do()
if err != nil {
return nil, err
}
if res.HTTPStatusCode != 200 {
return nil, fmt.Errorf("request to Google Analytics failed with %d", res.HTTPStatusCode)
}
return res, nil
}
func extractPageViews(res *ga.GetReportsResponse) ([]PageViewCount, error) {
if len(res.Reports) != 1 {
return []PageViewCount{}, fmt.Errorf("unexpected report count. wanted %d, got %d", 1, len(res.Reports))
}
report := res.Reports[0]
rows := report.Data.Rows
if rows == nil {
log.Println("no data found in report")
return []PageViewCount{}, nil
}
viewCounts := []PageViewCount{}
for _, row := range rows {
pagePath := row.Dimensions[0]
pageViews, err := strconv.ParseUint(row.Metrics[0].Values[0], 0, 64)
if err != nil {
panic(err)
}
viewCounts = append(viewCounts, PageViewCount{pagePath, pageViews})
}
return viewCounts, nil
}