forked from go-macaron/renders
-
Notifications
You must be signed in to change notification settings - Fork 0
/
macaron.go
229 lines (199 loc) · 5.93 KB
/
macaron.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package renders
import (
"bytes"
"encoding/json"
"encoding/xml"
"html/template"
"io"
"net/http"
"github.com/Unknwon/macaron"
"github.com/oxtoacart/bpool"
)
const (
ContentType = "Content-Type"
ContentLength = "Content-Length"
ContentBinary = "application/octet-stream"
ContentJSON = "application/json"
ContentHTML = "text/html"
ContentXHTML = "application/xhtml+xml"
ContentXML = "text/xml"
defaultCharset = "UTF-8"
)
// Provides a temporary buffer to execute templates into and catch errors.
var bufpool *bpool.BufferPool
var templates map[string]*template.Template
type Render interface {
// JSON writes the given status and JSON serialized version of the given value to the http.ResponseWriter.
JSON(status int, v interface{})
// HTML renders a html template specified by the name and writes the result and given status to the http.ResponseWriter.
HTML(status int, name string, v interface{})
// XML writes the given status and XML serialized version of the given value to the http.ResponseWriter.
XML(status int, v interface{})
// Data writes the raw byte array to the http.ResponseWriter.
Data(status int, v []byte)
// Error is a convenience function that writes an http status to the http.ResponseWriter.
Error(status int)
// Status is an alias for Error (writes an http status to the http.ResponseWriter)
Status(status int)
// Redirect is a convienience function that sends an HTTP redirect. If status is omitted, uses 302 (Found)
Redirect(location string, status ...int)
// Template returns the internal *template.Template used to render the HTML
Template(name string) *template.Template
// Header exposes the header struct from http.ResponseWriter.
Header() http.Header
}
// Options is a struct for specifying configuration options for the render.Renderer middleware
type Options struct {
// Directory to load templates. Default is "templates"
Directory string
// Extensions to parse template files from. Defaults to [".tmpl"]
Extensions []string
// Funcs is a slice of FuncMaps to apply to the template upon compilation. This is useful for helper functions. Defaults to [].
Funcs template.FuncMap
// Appends the given charset to the Content-Type header. Default is "UTF-8".
Charset string
// Outputs human readable JSON
IndentJSON bool
// Outputs human readable XML
IndentXML bool
// Prefixes the JSON output with the given bytes.
PrefixJSON []byte
// Prefixes the XML output with the given bytes.
PrefixXML []byte
// Allows changing of output to XHTML instead of HTML. Default is "text/html"
HTMLContentType string
}
func Renderer(options ...Options) macaron.Handler {
opt := prepareOptions(options)
cs := prepareCharset(opt.Charset)
bufpool = bpool.NewBufferPool(64)
return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
if macaron.Env == macaron.DEV {
// recompile for easy development
compile(opt)
}
c.MapTo(&renderer{res, req, templates, opt, cs}, (*Render)(nil))
}
}
func compile(options Options) error {
var tmplErr error
if len(options.Funcs) > 0 {
templates, tmplErr = LoadWithFuncMap(options)
return tmplErr
} else {
templates, tmplErr = Load(options)
return tmplErr
}
return nil
}
func prepareCharset(charset string) string {
if len(charset) != 0 {
return "; charset=" + charset
}
return "; charset=" + defaultCharset
}
func prepareOptions(options []Options) Options {
var opt Options
if len(options) > 0 {
opt = options[0]
}
// Defaults
if len(opt.Directory) == 0 {
opt.Directory = "templates"
}
if len(opt.Extensions) == 0 {
opt.Extensions = []string{".html"}
}
if len(opt.HTMLContentType) == 0 {
opt.HTMLContentType = ContentHTML
}
return opt
}
type renderer struct {
http.ResponseWriter
req *http.Request
t map[string]*template.Template
opt Options
compiledCharset string
}
func (r *renderer) JSON(status int, v interface{}) {
var result []byte
var err error
if r.opt.IndentJSON {
result, err = json.MarshalIndent(v, "", " ")
} else {
result, err = json.Marshal(v)
}
if err != nil {
http.Error(r, err.Error(), 500)
return
}
// json rendered fine, write out the result
r.Header().Set(ContentType, ContentJSON+r.compiledCharset)
r.WriteHeader(status)
if len(r.opt.PrefixJSON) > 0 {
r.Write(r.opt.PrefixJSON)
}
r.Write(result)
}
func (r *renderer) HTML(status int, name string, binding interface{}) {
buf, err := r.execute(name, binding)
//fmt.Println(buf.String())
if err != nil {
http.Error(r, err.Error(), http.StatusInternalServerError)
return
}
// template rendered fine, write out the result
r.Header().Set(ContentType, r.opt.HTMLContentType+r.compiledCharset)
r.WriteHeader(status)
io.Copy(r, buf)
bufpool.Put(buf)
}
func (r *renderer) XML(status int, v interface{}) {
var result []byte
var err error
if r.opt.IndentXML {
result, err = xml.MarshalIndent(v, "", " ")
} else {
result, err = xml.Marshal(v)
}
if err != nil {
http.Error(r, err.Error(), 500)
return
}
// XML rendered fine, write out the result
r.Header().Set(ContentType, ContentXML+r.compiledCharset)
r.WriteHeader(status)
if len(r.opt.PrefixXML) > 0 {
r.Write(r.opt.PrefixXML)
}
r.Write(result)
}
func (r *renderer) Data(status int, v []byte) {
if r.Header().Get(ContentType) == "" {
r.Header().Set(ContentType, ContentBinary)
}
r.WriteHeader(status)
r.Write(v)
}
// Error writes the given HTTP status to the current ResponseWriter
func (r *renderer) Error(status int) {
r.WriteHeader(status)
}
func (r *renderer) Status(status int) {
r.WriteHeader(status)
}
func (r *renderer) Redirect(location string, status ...int) {
code := http.StatusFound
if len(status) == 1 {
code = status[0]
}
http.Redirect(r, r.req, location, code)
}
func (r *renderer) Template(name string) *template.Template {
return r.t[name]
}
func (r *renderer) execute(name string, binding interface{}) (*bytes.Buffer, error) {
buf := bufpool.Get()
return buf, r.t[name].ExecuteTemplate(buf, name, binding)
}