-
Notifications
You must be signed in to change notification settings - Fork 0
/
view.go
123 lines (106 loc) · 2.36 KB
/
view.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
package mano
import (
"encoding/json"
)
// View for a web interaction.
// Implementations are responsible for rendering content, and exposing the model.
type View interface {
// ContentType returns HTTP Content-type
ContentType() string
// Render the view given the specified model.
Render(ctx Context) error
}
type ActionView struct {
local string
contentType string
}
func (v *ActionView) ContentType() string {
if v.contentType == "" {
return "application/octet-stream; charset=UTF-8"
}
return v.contentType
}
type ContentView struct {
*ActionView
Content string
}
func (ar *ContentView) Render(ctx Context) error {
w := ctx.Response().Writer()
// w.Header().Set("Content-Type", ar.ContentType())
_, err := w.Write([]byte(ar.Content))
return err
}
func (ctx *RequestContext) Content(content string, contentType ...string) View {
view := &ContentView{
ActionView: &ActionView{
local: ctx.local,
},
Content: content,
}
if len(contentType) > 0 {
view.contentType = contentType[0]
}
return view
}
type JsonView struct {
*ActionView
Data interface{}
}
func (v *JsonView) Render(ctx Context) error {
content, err := json.Marshal(v.Data)
if err != nil {
return err
}
w := ctx.Response().Writer()
// w.Header().Set("Content-Type", v.ContentType())
_, err = w.Write([]byte(content))
return err
}
func (ctx *RequestContext) JSON(data interface{}, contentType ...string) View {
view := &JsonView{
ActionView: &ActionView{
local: ctx.local,
},
Data: data,
}
if len(contentType) > 0 {
view.contentType = contentType[0]
} else {
view.contentType = "application/json; charset=UTF-8"
}
return view
}
type TemplateView struct {
*ActionView
Template string
}
func (v *TemplateView) Render(ctx Context) error {
return ctx.App().viewEngine.Render(ctx.ViewData(), v.Template, ctx.Response().Writer())
}
func (ctx *RequestContext) View(template string, contentType ...string) View {
view := &TemplateView{
ActionView: &ActionView{
local: ctx.local,
},
Template: template,
}
if len(contentType) > 0 {
view.contentType = contentType[0]
} else {
view.contentType = "text/html; charset=UTF-8"
}
return view
}
type emptyView struct {
*ActionView
}
func (*emptyView) Render(ctx Context) error {
return nil
}
func (ctx *RequestContext) Empty() View {
return &emptyView{
ActionView: &ActionView{
local: ctx.local,
},
}
}