/
templates.go
106 lines (83 loc) · 2.39 KB
/
templates.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
106
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"path"
"regexp"
"text/template"
)
// Remove most of the useless spaces in HTML.
var spacesRegexp = regexp.MustCompile(`(>|\})\s+(<|\{)`)
// Replace a CSS tag with inline content.
var cssRegexp = regexp.MustCompile(`<!-- CSS([\s\S]+?)ENDCSS -->`)
// Remove protocol and trailing slash in homepages.
var simplifyURLRegexp = regexp.MustCompile(`(.*?://)(([^/]+)(/.+)?).*`)
// Templates is a map of all the parsed templates.
var Templates = make(map[string]*template.Template)
// preprocessTemplate does basic HTML minification before compiling templates.
func preprocessTemplate(s string) string {
// We are in production mode, inline the CSS!
if Config.Env == "prod" {
css, err := ioutil.ReadFile(path.Join(Config.PathFront, "build/static/css/index.css"))
if err != nil {
log.Fatal("built index.css not found!")
}
// Trim the BOM if present.
css = bytes.Trim(css, "\xef\xbb\xbf")
s = cssRegexp.ReplaceAllString(s, fmt.Sprintf(`<style type="text/css">%s</style>`, css))
}
return spacesRegexp.ReplaceAllString(s, "$1$2")
}
// truncate truncates a string to 'max' characters.
func truncate(s string, max int) string {
var numRunes = 0
for index := range s {
numRunes++
if numRunes > max {
return s[:index]
}
}
return s
}
// Simplify a hit URL for display.
func simplifyURL(s string) string {
return truncate(simplifyURLRegexp.ReplaceAllString(s, "$2"), 100)
}
// toJSON returns an object as a JSON string.
func toJSON(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
}
// getConfig returns the current config.
func getConfig() ConfigSpec {
return Config
}
// ParseTemplate returns a pre-processed and parsed template.
func ParseTemplate(filepath string) *template.Template {
cnt, err := ioutil.ReadFile(path.Join(Config.PathFront, "templates/"+filepath))
if err != nil {
log.Fatal(err)
}
funcMap := template.FuncMap{
"simplifyURL": simplifyURL,
"toJSON": toJSON,
"getConfig": getConfig,
"add": add,
}
t, err := template.New(filepath).Funcs(funcMap).Parse(preprocessTemplate(string(cnt)))
if err != nil {
log.Fatal(err)
}
return t
}
// LoadTemplates loads and parses all known templates at startup.
func LoadTemplates() {
Templates["index.html"] = ParseTemplate("index.html")
}
// Used to generate tabIndex for search links
func add(x, y int) int {
return x + y
}