forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.go
304 lines (268 loc) · 8.47 KB
/
controller.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
package revel
import (
"database/sql"
"fmt"
"net/http"
"os"
"path/filepath"
"reflect"
"runtime"
"runtime/debug"
"strings"
"time"
)
type Controller struct {
Name string // The controller name, e.g. "Application"
Type *ControllerType // A description of the controller type.
MethodType *MethodType // A description of the invoked action type.
AppController interface{} // The controller that was instantiated.
Action string // The full action name, e.g. "Application.Index"
Request *Request
Response *Response
Result Result
Flash Flash // User cookie, cleared after 1 request.
Session Session // Session, stored in cookie, signed.
Params *Params // Parameters from URL and form (including multipart).
Args map[string]interface{} // Per-request scratch space.
RenderArgs map[string]interface{} // Args passed to the template.
Validation *Validation // Data validation helpers
Txn *sql.Tx // Nil by default, but may be used by the app / plugins
}
func NewController(req *Request, resp *Response, ct *ControllerType) *Controller {
c := &Controller{
Name: ct.Type.Name(),
Type: ct,
Request: req,
Response: resp,
Params: ParseParams(req),
Args: map[string]interface{}{},
RenderArgs: map[string]interface{}{
"RunMode": RunMode,
"DevMode": DevMode,
},
}
c.RenderArgs["Controller"] = c
return c
}
func (c *Controller) FlashParams() {
for key, vals := range c.Params.Values {
c.Flash.Out[key] = vals[0]
}
}
func (c *Controller) SetCookie(cookie *http.Cookie) {
http.SetCookie(c.Response.Out, cookie)
}
// Invoke the given method, save headers/cookies to the response, and apply the
// result. (e.g. render a template to the response)
func (c *Controller) Invoke(appControllerPtr reflect.Value, method reflect.Value, methodArgs []reflect.Value) {
// Handle panics.
defer func() {
if err := recover(); err != nil {
handleInvocationPanic(c, err)
}
plugins.Finally(c)
}()
// Clean up from the request.
defer func() {
// Delete temp files.
if c.Request.MultipartForm != nil {
err := c.Request.MultipartForm.RemoveAll()
if err != nil {
WARN.Println("Error removing temporary files:", err)
}
}
for _, tmpFile := range c.Params.tmpFiles {
err := os.Remove(tmpFile.Name())
if err != nil {
WARN.Println("Could not remove upload temp file:", err)
}
}
}()
// Run the plugins.
plugins.BeforeRequest(c)
if c.Result == nil {
// Invoke the action.
var resultValue reflect.Value
if method.Type().IsVariadic() {
resultValue = method.CallSlice(methodArgs)[0]
} else {
resultValue = method.Call(methodArgs)[0]
}
if resultValue.Kind() == reflect.Interface && !resultValue.IsNil() {
c.Result = resultValue.Interface().(Result)
}
plugins.AfterRequest(c)
if c.Result == nil {
return
}
}
// Apply the result, which generally results in the ResponseWriter getting written.
c.Result.Apply(c.Request, c.Response)
}
// This function handles a panic in an action invocation.
// It cleans up the stack trace, logs it, and displays an error page.
func handleInvocationPanic(c *Controller, err interface{}) {
plugins.OnException(c, err)
error := NewErrorFromPanic(err)
if error == nil {
c.Response.Out.WriteHeader(500)
c.Response.Out.Write(debug.Stack())
return
}
ERROR.Print(err, "\n", error.Stack)
c.RenderError(error).Apply(c.Request, c.Response)
}
func (c *Controller) RenderError(err error) Result {
return ErrorResult{c.RenderArgs, err}
}
// Render a template corresponding to the calling Controller method.
// Arguments will be added to c.RenderArgs prior to rendering the template.
// They are keyed on their local identifier.
//
// For example:
//
// func (c Users) ShowUser(id int) revel.Result {
// user := loadUser(id)
// return c.Render(user)
// }
//
// This action will render views/Users/ShowUser.html, passing in an extra
// key-value "user": (User).
func (c *Controller) Render(extraRenderArgs ...interface{}) Result {
// Get the calling function name.
pc, _, line, ok := runtime.Caller(1)
if !ok {
ERROR.Println("Failed to get Caller information")
return nil
}
// e.g. sample/app/controllers.(*Application).Index
var fqViewName string = runtime.FuncForPC(pc).Name()
var viewName string = fqViewName[strings.LastIndex(fqViewName, ".")+1 : len(fqViewName)]
// Determine what method we are in.
// (e.g. the invoked controller method might have delegated to another method)
methodType := c.MethodType
if methodType.Name != viewName {
methodType = c.Type.Method(viewName)
if methodType == nil {
return c.RenderError(fmt.Errorf(
"No Method %s in Controller %s when loading the view."+
" (delegating Render is only supported within the same controller)",
viewName, c.Name))
}
}
// Get the extra RenderArgs passed in.
if renderArgNames, ok := methodType.RenderArgNames[line]; ok {
if len(renderArgNames) == len(extraRenderArgs) {
for i, extraRenderArg := range extraRenderArgs {
c.RenderArgs[renderArgNames[i]] = extraRenderArg
}
} else {
ERROR.Println(len(renderArgNames), "RenderArg names found for",
len(extraRenderArgs), "extra RenderArgs")
}
} else {
ERROR.Println("No RenderArg names found for Render call on line", line,
"(Method", methodType, ", ViewName", viewName, ")")
}
return c.RenderTemplate(c.Name + "/" + viewName + "." + c.Request.Format)
}
// A less magical way to render a template.
// Renders the given template, using the current RenderArgs.
func (c *Controller) RenderTemplate(templatePath string) Result {
// Get the Template.
template, err := MainTemplateLoader.Template(templatePath)
if err != nil {
return c.RenderError(err)
}
return &RenderTemplateResult{
Template: template,
RenderArgs: c.RenderArgs,
}
}
// Uses encoding/json.Marshal to return JSON to the client.
func (c *Controller) RenderJson(o interface{}) Result {
return RenderJsonResult{o}
}
// Uses encoding/xml.Marshal to return XML to the client.
func (c *Controller) RenderXml(o interface{}) Result {
return RenderXmlResult{o}
}
// Render plaintext in response, printf style.
func (c *Controller) RenderText(text string, objs ...interface{}) Result {
finalText := text
if len(objs) > 0 {
finalText = fmt.Sprintf(text, objs...)
}
return &RenderTextResult{finalText}
}
// Render a "todo" indicating that the action isn't done yet.
func (c *Controller) Todo() Result {
c.Response.Status = http.StatusNotImplemented
return c.RenderError(&Error{
Title: "TODO",
Description: "This action is not implemented",
})
}
func (c *Controller) NotFound(msg string, objs ...interface{}) Result {
finalText := msg
if len(objs) > 0 {
finalText = fmt.Sprintf(msg, objs...)
}
c.Response.Status = http.StatusNotFound
return c.RenderError(&Error{
Title: "Not Found",
Description: finalText,
})
}
func (c *Controller) Forbidden(msg string, objs ...interface{}) Result {
finalText := msg
if len(objs) > 0 {
finalText = fmt.Sprintf(msg, objs...)
}
c.Response.Status = http.StatusForbidden
return c.RenderError(&Error{
Title: "Forbidden",
Description: finalText,
})
}
// Return a file, either displayed inline or downloaded as an attachment.
// The name and size are taken from the file info.
func (c *Controller) RenderFile(file *os.File, delivery ContentDisposition) Result {
var (
modtime = time.Now()
fileInfo, err = file.Stat()
)
if err != nil {
WARN.Println("RenderFile error:", err)
}
if fileInfo != nil {
modtime = fileInfo.ModTime()
}
return &BinaryResult{
Reader: file,
Name: filepath.Base(file.Name()),
Delivery: delivery,
Length: -1, // http.ServeContent gets the length itself
ModTime: modtime,
}
}
// Redirect to an action or to a URL.
// c.Redirect(Controller.Action)
// c.Redirect("/controller/action")
// c.Redirect("/controller/%d/action", id)
func (c *Controller) Redirect(val interface{}, args ...interface{}) Result {
if url, ok := val.(string); ok {
if len(args) == 0 {
return &RedirectToUrlResult{url}
}
return &RedirectToUrlResult{fmt.Sprintf(url, args...)}
}
return &RedirectToActionResult{val}
}
// Perform a message lookup for the given message name using the given arguments
// using the current language defined for this controller.
//
// The current language is set by the i18n plugin.
func (c *Controller) Message(message string, args ...interface{}) (value string) {
return Message(c.Request.Locale, message, args...)
}