-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.go
391 lines (353 loc) · 8.57 KB
/
render.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package peony
import (
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"time"
)
var (
RendererType reflect.Type = reflect.TypeOf((*Renderer)(nil)).Elem()
Attachment string = "attachment"
Inline string = "inline"
)
type Renderer interface {
Apply(c *Controller)
}
type TextRenderer struct {
Renderer
ContentType string
TextSlice []byte
Text string
}
type JsonRenderer struct {
Renderer
Json interface{}
}
type RedirectRenderer struct {
Renderer
Url string
action interface{} //e.g. Controller.Method (*Controller).Method function
param interface{}
}
type XmlRenderer struct {
Renderer
Xml interface{}
}
type autoRenderer struct {
Renderer
Params interface{}
}
type TemplateRenderer struct {
Renderer
RenderParam interface{}
TemplateName string
}
type ErrorRenderer struct {
Renderer
Status int
Error error
}
type BinaryRenderer struct {
Renderer
Reader io.Reader
Name string
ContentDisposition string
Len int64
ModTime time.Time
}
func RenderError(err error) *ErrorRenderer {
return &ErrorRenderer{Error: err}
}
func NotFound(msg string, args ...interface{}) *ErrorRenderer {
text := msg
if len(args) > 0 {
text = fmt.Sprintf(msg, args...)
}
render := RenderError(&Error{Title: "Not Found", Description: text})
render.Status = 404
return render
}
func (a *autoRenderer) Apply(c *Controller) {
switch c.Req.Accept {
case "json":
RenderJson(a.Params).Apply(c)
case "xml":
RenderXml(a.Params).Apply(c)
default:
RenderTemplate(a.Params).Apply(c)
}
}
func (r *RedirectRenderer) getRedirctUrl(svr *Server) (string, error) {
if r.Url != "" {
return r.Url, nil
}
locType := reflect.TypeOf(r.action)
actionName := ""
if locType.NumIn() > 0 {
recvType := locType.In(0)
//support Controller.Method as redirect argument.
meth := FindMethod(recvType, reflect.ValueOf(r.action))
if meth != nil {
recvName := ""
if recvType.Kind() == reflect.Ptr {
recvName = recvType.Elem().Name()
} else {
recvName = recvType.Name()
}
actionName = fmt.Sprintf("%s.%s", recvName, meth.Name)
}
}
var action *Action
if actionName != "" {
action = svr.FindAction(actionName)
} else {
action = svr.FindActionByFunc(r.action)
}
if action == nil {
return "", NoSuchAction
}
var err error
var rsurl string
var buildParams map[string]string
if params, ok := r.param.(map[string]interface{}); ok {
buildParams = make(map[string]string, len(params))
for k, v := range params {
svr.convertors.ReverseConvert(buildParams, k, v)
}
}
if params, ok := r.param.(map[string]string); ok {
buildParams = params
}
err, rsurl = svr.Router.Build(action.Name, buildParams)
if err != nil {
return "", err
}
queryValues := make(url.Values)
for k, v := range buildParams {
queryValues.Set(k, v)
}
if len(queryValues) > 0 {
rsurl += "?" + queryValues.Encode()
}
return rsurl, nil
}
func (r *RedirectRenderer) Apply(c *Controller) {
url, err := r.getRedirctUrl(c.Server)
if err != nil {
RenderError(err).Apply(c)
return
}
c.Resp.Header().Set("Location", url)
c.Resp.WriteContentTypeCode(http.StatusFound, "")
}
func ParseAction(action string) string {
return strings.Replace(action, ".", "/", 1)
}
func (b *BinaryRenderer) Apply(c *Controller) {
resp := c.Resp
prefix := b.ContentDisposition
if b.ContentDisposition == "" {
prefix = Inline
}
contentDisposition := fmt.Sprintf("%s; filename=%s", prefix, b.Name)
resp.Header().Set("Content-Disposition", contentDisposition)
if readSeeker, ok := b.Reader.(io.ReadSeeker); ok {
http.ServeContent(c.Resp.ResponseWriter, c.Req.Request, b.Name, b.ModTime, readSeeker)
} else {
if b.Len >= 0 {
resp.Header().Set("Content-Length", strconv.FormatInt(b.Len, 10))
}
io.Copy(resp, b.Reader)
}
if closer, ok := b.Reader.(io.Closer); ok {
closer.Close()
}
}
func RenderFile(path string) Renderer {
var err error
var finfo os.FileInfo
var file *os.File
if finfo, err = os.Stat(path); err != nil {
notFound := &Error{Title: "Not Found", Description: err.Error()}
render := RenderError(notFound)
render.Status = http.StatusNotFound
return render
}
if finfo.IsDir() {
render := RenderError(&Error{Title: "Forbidden", Description: "Directory listing not allowed"})
render.Status = http.StatusForbidden
return render
}
if file, err = os.Open(path); err != nil {
return RenderError(err)
}
return &BinaryRenderer{ModTime: finfo.ModTime(), Name: finfo.Name(), Reader: file, Len: finfo.Size()}
}
func (r *ErrorRenderer) Apply(c *Controller) {
resp := c.Resp
req := c.Req
status := r.Status
if status == 0 {
status = http.StatusInternalServerError
}
tplName := fmt.Sprintf("errors/%d.%s", status, req.Accept)
tpl := c.templateLoader.Lookup(tplName)
if tpl == nil {
resp.WriteContentTypeCode(status, "text/"+req.Accept)
resp.Write([]byte(r.Error.Error()))
WARN.Println("can't find template", tplName)
return
}
resp.WriteContentTypeCode(status, "text/html")
var err *Error
switch r.Error.(type) {
case *Error:
err = r.Error.(*Error)
default:
err = &Error{
Title: "error",
Description: r.Error.Error(),
}
}
if e := tpl.Execute(c.Resp, err); e != nil {
ERROR.Println("template execute error:", e)
ERROR.Println("origin error:", r.Error)
}
}
func (j *JsonRenderer) Apply(c *Controller) {
resp := c.Resp
rs, err := json.Marshal(j.Json)
if err != nil {
(&ErrorRenderer{Error: err}).Apply(c)
return
}
resp.WriteContentTypeCode(http.StatusOK, "application/json")
resp.Write(rs)
}
func (r *XmlRenderer) Apply(c *Controller) {
resp := c.Resp
bs, err := xml.Marshal(r.Xml)
if err != nil {
(&ErrorRenderer{Error: err}).Apply(c)
return
}
resp.WriteContentTypeCode(http.StatusOK, "application/xml")
resp.Write(bs)
}
func (r *TextRenderer) Apply(c *Controller) {
resp := c.Resp
contentType := r.ContentType
if contentType == "" {
contentType = "text/pain"
}
resp.WriteContentTypeCode(http.StatusOK, r.ContentType)
if r.Text != "" {
resp.Write([]byte(r.Text))
} else {
resp.Write(r.TextSlice)
}
}
func (t *TemplateRenderer) Apply(c *Controller) {
resp := c.Resp
templateLoader := c.templateLoader
resp.WriteContentTypeCode(http.StatusOK, "text/html")
tmplName := t.TemplateName
//if user choose a template, use the choosed, esle use the default rule for find tempate
if tmplName == "" {
tmplName = ParseAction(c.actionName) + ".html"
}
template := templateLoader.Lookup(tmplName)
if template == nil {
ERROR.Println("can't find template", tmplName)
resp.Write([]byte("can't find template " + tmplName))
return
}
var ok bool
var p map[string]interface{}
if t.RenderParam == nil {
p = map[string]interface{}{}
t.RenderParam = p
} else if p, ok = t.RenderParam.(map[string]interface{}); !ok {
p = nil
}
if p != nil {
//merge session and flash
p["session"] = c.Session.Attribute
p["flash"] = c.Flash.In
}
err := template.Execute(resp, t.RenderParam)
if err != nil {
//TODO parse error
resp.Write([]byte(err.Error()))
}
}
func RenderJson(json interface{}) Renderer {
return &JsonRenderer{Json: json}
}
func RenderXml(xml interface{}) Renderer {
return &XmlRenderer{Xml: xml}
}
func RenderText(s string) Renderer {
return &TextRenderer{Text: s}
}
func Render(param ...interface{}) Renderer {
var renderParam interface{}
l := len(param)
if l > 0 {
if l == 1 {
renderParam = param[0]
}
}
return &autoRenderer{Params: renderParam}
}
//renderParam for is the parameter for template execute. templateName is for point the template.
func RenderTemplate(param interface{}, templateName ...string) Renderer {
name := ""
if len(templateName) > 0 {
name = templateName[0]
}
return &TemplateRenderer{RenderParam: param, TemplateName: name}
}
var descript = `Redirect parameter must be (function, map[string]string or map[string]interface{}) or ("/%s/%i", "index", 1)`
func Redirect(r interface{}, param ...interface{}) Renderer {
if loc, ok := r.(string); ok {
var url string
if len(param) == 0 {
url = loc
} else {
url = fmt.Sprintf(loc, param)
}
return &RedirectRenderer{Url: url}
}
var p interface{}
if reflect.TypeOf(r).Kind() != reflect.Func || len(param) > 1 {
goto ERR
}
if len(param) == 1 {
p = param[0]
switch p.(type) {
case map[string]string, map[string]interface{}:
default:
goto ERR
}
}
return &RedirectRenderer{action: r, param: p}
ERR:
_, f, l, _ := runtime.Caller(1)
lines, _ := ReadLines(f)
return RenderError(&Error{
Title: "Parameter error",
Description: descript,
Path: f,
Line: l,
SourceLines: lines,
})
}