Repository navigation
Expand file tree
/
Copy pathrender.go
More file actions
41 lines (36 loc) · 1.48 KB
/
Copy pathrender.go
File metadata and controls
41 lines (36 loc) · 1.48 KB
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
package main
import "regexp"
// validTrackingID keeps the measurement id to characters that are safe to
// splice into a script tag and a JS string literal.
var validTrackingID = regexp.MustCompile(`^[A-Za-z0-9-]+$`)
// setting mirrors goblog's settings JSON shape.
type setting struct {
Key string `json:"key"`
Type string `json:"type"`
Default string `json:"default"`
Label string `json:"label"`
Description string `json:"description"`
}
// settingDefs keeps the keys of the compiled-in plugin this one replaces,
// so an upgraded site's saved settings carry over.
func settingDefs() []setting {
return []setting{
{Key: "tracking_id", Type: "text", Default: "", Label: "Measurement ID", Description: "Google Analytics measurement ID (e.g. G-XXXXXXXXXX)"},
{Key: "enabled", Type: "text", Default: "false", Label: "Enabled", Description: "Set to 'true' to enable tracking"},
}
}
// headHTML returns the gtag.js snippet for the <head>, or "" when tracking
// is off, unconfigured, or the id is not something we would put in a script.
func headHTML(settings map[string]string) string {
id := settings["tracking_id"]
if settings["enabled"] != "true" || id == "" || !validTrackingID.MatchString(id) {
return ""
}
return `<script async src="https://www.googletagmanager.com/gtag/js?id=` + id + `"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '` + id + `');
</script>`
}