/
angular-templatecache.go
61 lines (49 loc) · 1.36 KB
/
angular-templatecache.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
package ngcache
import (
"bytes"
"io"
"io/ioutil"
"text/template"
"github.com/omeid/gonzo"
"github.com/omeid/gonzo/context"
)
type Config struct {
Name string //Name of the generated file.
Module string //Name of AngularJS module.
}
func readall(r io.Reader) (string, error) {
var buff bytes.Buffer
_, err := buff.ReadFrom(r)
return buff.String(), err
}
var cacheTemplate = template.Must(template.New("").Funcs(template.FuncMap{"readall": readall}).Parse(`angular.module("{{ .Module }}", []).run(["$templateCache", function($templateCache) { {{ range $path, $file := .Files }}
$templateCache.put("{{ $path }}", "{{ readall $file | js }}");
{{ end }}
}])`))
type cache struct {
Config
Files map[string]gonzo.File
}
func Compile(conf Config) gonzo.Stage {
return func(ctx context.Context, in <-chan gonzo.File, out chan<- gonzo.File) error {
b := cache{conf, make(map[string]gonzo.File)}
for file := range in {
path := file.FileInfo().Name();
ctx.Infof("Adding %s", path)
b.Files[path] = file
defer file.Close() //Close files AFTER we have build our package.
}
buff := new(bytes.Buffer)
err := cacheTemplate.Execute(buff, b)
if err != nil {
ctx.Error(err)
return err
}
fi := gonzo.NewFileInfo()
fi.SetName(b.Name)
fi.SetSize(int64(buff.Len()))
sf := gonzo.NewFile(ioutil.NopCloser(buff), fi)
out <- sf
return nil
}
}