-
Notifications
You must be signed in to change notification settings - Fork 36
/
loader.go
83 lines (68 loc) · 1.89 KB
/
loader.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
package stick
import (
"bytes"
"io"
"os"
"path/filepath"
)
// Loader defines a type that can load Stick templates using the given name.
type Loader interface {
// Load attempts to load the specified template, returning a Template or an error.
Load(name string) (Template, error)
}
type stringTemplate struct {
name string
contents string
}
func (t *stringTemplate) Name() string {
return t.name
}
func (t *stringTemplate) Contents() io.Reader {
return bytes.NewBufferString(t.contents)
}
// StringLoader is intended to be used to load Stick templates directly from a string.
type StringLoader struct{}
// Load on a StringLoader simply returns the name that is passed in.
func (l *StringLoader) Load(name string) (Template, error) {
return &stringTemplate{name, name}, nil
}
// MemoryLoader loads templates from an in-memory map.
type MemoryLoader struct {
Templates map[string]string
}
// Load tries to load the template from the in-memory map.
func (l *MemoryLoader) Load(name string) (Template, error) {
v, ok := l.Templates[name]
if !ok {
return nil, os.ErrNotExist
}
return &stringTemplate{name, v}, nil
}
type fileTemplate struct {
name string
reader io.Reader
}
func (t *fileTemplate) Name() string {
return t.name
}
func (t *fileTemplate) Contents() io.Reader {
return t.reader
}
// A FilesystemLoader loads templates from a filesystem.
type FilesystemLoader struct {
rootDir string
}
// NewFilesystemLoader creates a new FilesystemLoader with the specified root directory.
func NewFilesystemLoader(rootDir string) *FilesystemLoader {
return &FilesystemLoader{rootDir}
}
// Load on a FileSystemLoader attempts to load the given file, relative to the
// configured root directory.
func (l *FilesystemLoader) Load(name string) (Template, error) {
path := filepath.Join(l.rootDir, name)
f, err := os.Open(path)
if err != nil {
return nil, err
}
return &fileTemplate{name, f}, nil
}