This repository has been archived by the owner on May 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
static_includes.go
90 lines (76 loc) · 1.7 KB
/
static_includes.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
//
// This file contains a helper method to allow parsing #include
// lines from static-resources included in our binary.
//
package main
import (
"fmt"
"strings"
)
//
// CACHE holds a cache of expanded templates
//
var CACHE = make(map[string]string)
// ExpandResource reads a file from our static-resources, and
// processes any lines that contain "includes".
//
// This is done to ensure that the HTML that we serve to clients
// doesn't require any CSS or JS requests
//
func ExpandResource(file string) (string, error) {
//
// Return from the cache, if we can.
//
tmp := CACHE[file]
if tmp != "" {
return tmp, nil
}
//
// Get the master template
//
data, err := getResource(file)
if err != nil {
return "", err
}
//
// Build up the output here, by expanding `#include` entries.
//
output := ""
// look for the "#include <xx>" lines
lines := strings.Split(string(data), "\n")
for _, line := range lines {
// If we found such a line
if strings.HasPrefix(line, "#include ") {
// Get the file which should be handled
inc := line
inc = strings.TrimPrefix(inc, "#include ")
// Look that up.
txt, err := getResource("data/" + inc)
if err != nil {
fmt.Printf("Failed to read 'data/" + inc + "'")
return "", nil
}
// If it succeeded then we'll add the contents
// to the output.
//
// NOTE: We don't allow recursion, an #include'd
// file cannot #include another.
//
output += string(txt)
} else {
//
// Otherwise add the literal contents
// and the newline we missed.
output += line
output += "\n"
}
}
//
// Save the expanded text in our cache.
//
CACHE[file] = output
//
// Before returning it.
//
return output, nil
}