forked from sprungknoedl/minions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformats.go
168 lines (144 loc) · 4.27 KB
/
formats.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package minions
import (
"encoding/json"
"encoding/xml"
"errors"
"html/template"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
)
// JSON outputs the data encoded as JSON.
func JSON(w http.ResponseWriter, r *http.Request, code int, data interface{}) error {
w.Header().Add("content-type", "application/json; charset=utf-8")
w.WriteHeader(code)
if data == nil {
return nil
}
enc := json.NewEncoder(w)
enc.SetIndent("", "\t")
err := enc.Encode(data)
return err
}
// XML outputs the data encoded as XML.
func XML(w http.ResponseWriter, r *http.Request, code int, data interface{}) error {
w.Header().Add("content-type", "application/xml; charset=utf-8")
w.WriteHeader(code)
if data == nil {
return nil
}
enc := xml.NewEncoder(w)
enc.Indent("", "\t")
err := enc.Encode(data)
return err
}
func NewFileServer(prefix string, root string) http.HandlerFunc {
fs := http.Dir(root)
handler := http.StripPrefix(prefix, http.FileServer(fs))
return handler.ServeHTTP
}
// Templates is a collection of HTML templates in the html/template format of the
// go stdlib. The templates are loaded and parsed on the first request, on every request
// when reload is enabled on explicitly when Load() is called.
type Templates struct {
dir string
templates *template.Template
funcmap template.FuncMap
reload bool
}
// NewTemplates creates a new template collection. The templates are loaded from dir
// on the first request or when Load() is called. When reload is true, the templates
// are reloaded on each request.
func NewTemplates(dir string, reload bool) Templates {
return Templates{
dir: filepath.FromSlash(dir),
funcmap: template.FuncMap{
"div": func(dividend, divisor int) float64 {
return float64(dividend) / float64(divisor)
},
"dict": func(values ...interface{}) (map[string]interface{}, error) {
if len(values)%2 != 0 {
return nil, errors.New("invalid dict call")
}
dict := make(map[string]interface{}, len(values)/2)
for i := 0; i < len(values); i += 2 {
key, ok := values[i].(string)
if !ok {
return nil, errors.New("dict keys must be strings")
}
dict[key] = values[i+1]
}
return dict, nil
},
},
reload: reload,
}
}
// Funcs adds the elements of the argument map to the template's function map.
// The return value is the updated template.
func (tpl Templates) Funcs(funcmap template.FuncMap) Templates {
// create new funcmap to avoid race conditions
newmap := template.FuncMap{}
for name, fn := range tpl.funcmap {
newmap[name] = fn
}
// overwrite/add functions
for name, fn := range funcmap {
newmap[name] = fn
}
tpl.funcmap = newmap
return tpl
}
// Load loads any template from the filesystem.
func (tpl Templates) Load() (Templates, error) {
tpl.templates = template.New("").Funcs(tpl.funcmap)
err := filepath.Walk(tpl.dir, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
b, err := ioutil.ReadFile(path)
if err != nil {
return err
}
tpl.templates, err = tpl.templates.
New(strings.TrimPrefix(path, tpl.dir)).
Parse(string(b))
return err
}
return nil
})
return tpl, err
}
// HTML outputs a rendered HTML template to the client.
func (tpl Templates) HTML(w http.ResponseWriter, r *http.Request, code int, name string, data interface{}) error {
w.Header().Add("content-type", "text/html; charset=utf-8")
w.WriteHeader(code)
return tpl.Execute(w, name, data, nil)
}
// Execute outputs a rendered template to the Writer. If you want to stream
// HTML to an ResponseWriter, use HTML(..) as it sets some required headers.
// ctxFuncs can be used to add functions to the cloned templates, so that
// the original templates will not be changed (multi threading)
func (tpl Templates) Execute(w io.Writer, name string, data interface{}, ctxFuncs template.FuncMap) error {
// reload templates in debug mode
if tpl.reload {
var err error
tpl, err = tpl.Load()
if err != nil {
return err
}
}
// clone underlying templates, so we can safely update the functions
templates, err := tpl.templates.Clone()
if err != nil {
return err
}
templates.Funcs(tpl.funcmap) // update funcmap
templates.Funcs(ctxFuncs) // update funcmap
err = templates.ExecuteTemplate(w, name, data)
if err != nil {
return err
}
return nil
}