Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 370 lines (323 sloc) 10.948 kB
f164930 @robfig rev -> revel. Fixes #54
authored
1 package revel
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
2
3 import (
abc4648 @robfig Filters, booking app works, tests pass
authored
4 "errors"
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
5 "fmt"
278b71a @jcvernaleo Server a file from memory.
jcvernaleo authored
6 "io"
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
7 "net/http"
8 "os"
9 "path/filepath"
10 "reflect"
11 "runtime"
12 "strings"
1dccfef @jgraham909 Switch to use ServeContent instead of io.copy
jgraham909 authored
13 "time"
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
14 )
15
16 type Controller struct {
f7f405a @robfig Use a Plugin to run Interceptors
authored
17 Name string // The controller name, e.g. "Application"
18 Type *ControllerType // A description of the controller type.
2f34d9c @robfig Revert the semantic change to Controller.Action and add MethodName in…
authored
19 MethodName string // The method name, e.g. "Index"
f7f405a @robfig Use a Plugin to run Interceptors
authored
20 MethodType *MethodType // A description of the invoked action type.
21 AppController interface{} // The controller that was instantiated.
2f34d9c @robfig Revert the semantic change to Controller.Action and add MethodName in…
authored
22 Action string // The fully qualified action name, e.g. "App.Index"
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
23
24 Request *Request
25 Response *Response
f7f405a @robfig Use a Plugin to run Interceptors
authored
26 Result Result
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
27
f7f405a @robfig Use a Plugin to run Interceptors
authored
28 Flash Flash // User cookie, cleared after 1 request.
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
29 Session Session // Session, stored in cookie, signed.
30 Params *Params // Parameters from URL and form (including multipart).
31 Args map[string]interface{} // Per-request scratch space.
32 RenderArgs map[string]interface{} // Args passed to the template.
33 Validation *Validation // Data validation helpers
34 }
35
8f02aa0 @robfig Filters: Performance fix (7% on JSON benchmark!)
authored
36 func NewController(req *Request, resp *Response) *Controller {
37 return &Controller{
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
38 Request: req,
39 Response: resp,
da8b6b4 @robfig Params surgery: Split out the types of params and provided a unified …
authored
40 Params: new(Params),
9c0fbf3 @robfig Initialize Args with an empty map.
authored
41 Args: map[string]interface{}{},
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
42 RenderArgs: map[string]interface{}{
43 "RunMode": RunMode,
1381d14 @robfig Add .DevMode - a boolean to indicate if RunMode is a development mode.
authored
44 "DevMode": DevMode,
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
45 },
46 }
47 }
48
49 func (c *Controller) FlashParams() {
50 for key, vals := range c.Params.Values {
51 c.Flash.Out[key] = vals[0]
52 }
53 }
54
55 func (c *Controller) SetCookie(cookie *http.Cookie) {
56 http.SetCookie(c.Response.Out, cookie)
57 }
58
59 func (c *Controller) RenderError(err error) Result {
60 return ErrorResult{c.RenderArgs, err}
61 }
62
63 // Render a template corresponding to the calling Controller method.
64 // Arguments will be added to c.RenderArgs prior to rendering the template.
65 // They are keyed on their local identifier.
66 //
67 // For example:
68 //
f164930 @robfig rev -> revel. Fixes #54
authored
69 // func (c Users) ShowUser(id int) revel.Result {
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
70 // user := loadUser(id)
71 // return c.Render(user)
72 // }
73 //
74 // This action will render views/Users/ShowUser.html, passing in an extra
75 // key-value "user": (User).
76 func (c *Controller) Render(extraRenderArgs ...interface{}) Result {
77 // Get the calling function name.
abc4648 @robfig Filters, booking app works, tests pass
authored
78 _, _, line, ok := runtime.Caller(1)
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
79 if !ok {
80 ERROR.Println("Failed to get Caller information")
81 }
82
83 // Get the extra RenderArgs passed in.
abc4648 @robfig Filters, booking app works, tests pass
authored
84 if renderArgNames, ok := c.MethodType.RenderArgNames[line]; ok {
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
85 if len(renderArgNames) == len(extraRenderArgs) {
86 for i, extraRenderArg := range extraRenderArgs {
87 c.RenderArgs[renderArgNames[i]] = extraRenderArg
88 }
89 } else {
90 ERROR.Println(len(renderArgNames), "RenderArg names found for",
91 len(extraRenderArgs), "extra RenderArgs")
92 }
93 } else {
94 ERROR.Println("No RenderArg names found for Render call on line", line,
abc4648 @robfig Filters, booking app works, tests pass
authored
95 "(Method", c.MethodType.Name, ")")
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
96 }
97
abc4648 @robfig Filters, booking app works, tests pass
authored
98 return c.RenderTemplate(c.Name + "/" + c.MethodType.Name + "." + c.Request.Format)
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
99 }
100
101 // A less magical way to render a template.
102 // Renders the given template, using the current RenderArgs.
103 func (c *Controller) RenderTemplate(templatePath string) Result {
104
105 // Get the Template.
106 template, err := MainTemplateLoader.Template(templatePath)
107 if err != nil {
108 return c.RenderError(err)
109 }
110
111 return &RenderTemplateResult{
112 Template: template,
113 RenderArgs: c.RenderArgs,
114 }
115 }
116
117 // Uses encoding/json.Marshal to return JSON to the client.
118 func (c *Controller) RenderJson(o interface{}) Result {
f933936 @andrewmunsell Use existing RenderJsonResult
andrewmunsell authored
119 return RenderJsonResult{o, ""}
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
120 }
121
912ee0b @andrewmunsell Add JSONP result type and method to controller
andrewmunsell authored
122 // Renders a JSONP result using encoding/json.Marshal
123 func (c *Controller) RenderJsonP(callback string, o interface{}) Result {
f933936 @andrewmunsell Use existing RenderJsonResult
andrewmunsell authored
124 return RenderJsonResult{o, callback}
912ee0b @andrewmunsell Add JSONP result type and method to controller
andrewmunsell authored
125 }
126
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
127 // Uses encoding/xml.Marshal to return XML to the client.
128 func (c *Controller) RenderXml(o interface{}) Result {
129 return RenderXmlResult{o}
130 }
131
132 // Render plaintext in response, printf style.
133 func (c *Controller) RenderText(text string, objs ...interface{}) Result {
134 finalText := text
135 if len(objs) > 0 {
ae6480d @robfig Make NotFound behave like Printf
authored
136 finalText = fmt.Sprintf(text, objs...)
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
137 }
138 return &RenderTextResult{finalText}
139 }
140
a516de8 @romanoff Added method to render html
romanoff authored
141 // Render html in response
142 func (c *Controller) RenderHtml(html string) Result {
143 return &RenderHtmlResult{html}
144 }
145
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
146 // Render a "todo" indicating that the action isn't done yet.
147 func (c *Controller) Todo() Result {
148 c.Response.Status = http.StatusNotImplemented
149 return c.RenderError(&Error{
150 Title: "TODO",
151 Description: "This action is not implemented",
152 })
153 }
154
ae6480d @robfig Make NotFound behave like Printf
authored
155 func (c *Controller) NotFound(msg string, objs ...interface{}) Result {
156 finalText := msg
157 if len(objs) > 0 {
158 finalText = fmt.Sprintf(msg, objs...)
159 }
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
160 c.Response.Status = http.StatusNotFound
161 return c.RenderError(&Error{
162 Title: "Not Found",
ae6480d @robfig Make NotFound behave like Printf
authored
163 Description: finalText,
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
164 })
165 }
166
c09912d @robfig Add a Forbidden() Result
authored
167 func (c *Controller) Forbidden(msg string, objs ...interface{}) Result {
168 finalText := msg
169 if len(objs) > 0 {
170 finalText = fmt.Sprintf(msg, objs...)
171 }
172 c.Response.Status = http.StatusForbidden
173 return c.RenderError(&Error{
174 Title: "Forbidden",
175 Description: finalText,
176 })
177 }
178
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
179 // Return a file, either displayed inline or downloaded as an attachment.
180 // The name and size are taken from the file info.
181 func (c *Controller) RenderFile(file *os.File, delivery ContentDisposition) Result {
1c74448 @robfig Make BinaryResult accept io.Readers instead of io.ReadSeeker
authored
182 var (
183 modtime = time.Now()
184 fileInfo, err = file.Stat()
185 )
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
186 if err != nil {
187 WARN.Println("RenderFile error:", err)
188 }
189 if fileInfo != nil {
1dccfef @jgraham909 Switch to use ServeContent instead of io.copy
jgraham909 authored
190 modtime = fileInfo.ModTime()
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
191 }
34d8c95 @jcvernaleo Modify RenderFile to call RenderBinary.
jcvernaleo authored
192 return c.RenderBinary(file, filepath.Base(file.Name()), delivery, modtime)
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
193 }
194
e693f0c @jcvernaleo Adjust function name and comments to better reflect what it does.
jcvernaleo authored
195 // RenderBinary is like RenderFile() except that it instead of a file on disk,
196 // it renders data from memory (which could be a file that has not been written,
197 // the output from some function, or bytes streamed from somewhere else, as long
f5f5b26 @jcvernaleo Update some comments.
jcvernaleo authored
198 // it implements io.Reader). When called directly on something generated or
199 // streamed, modtime should mostly likely be time.Now().
34d8c95 @jcvernaleo Modify RenderFile to call RenderBinary.
jcvernaleo authored
200 func (c *Controller) RenderBinary(memfile io.Reader, filename string, delivery ContentDisposition, modtime time.Time) Result {
278b71a @jcvernaleo Server a file from memory.
jcvernaleo authored
201 return &BinaryResult{
202 Reader: memfile,
203 Name: filename,
204 Delivery: delivery,
f5f5b26 @jcvernaleo Update some comments.
jcvernaleo authored
205 Length: -1, // http.ServeContent gets the length itself unless memfile is a stream.
278b71a @jcvernaleo Server a file from memory.
jcvernaleo authored
206 ModTime: modtime,
207 }
208 }
209
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
210 // Redirect to an action or to a URL.
211 // c.Redirect(Controller.Action)
212 // c.Redirect("/controller/action")
213 // c.Redirect("/controller/%d/action", id)
214 func (c *Controller) Redirect(val interface{}, args ...interface{}) Result {
215 if url, ok := val.(string); ok {
216 if len(args) == 0 {
217 return &RedirectToUrlResult{url}
218 }
219 return &RedirectToUrlResult{fmt.Sprintf(url, args...)}
220 }
221 return &RedirectToActionResult{val}
222 }
2250607 @tmbrggmn Added basic version of i18n sample application.
tmbrggmn authored
223
8751a76 @robfig Tweak error formatting
authored
224 // Perform a message lookup for the given message name using the given arguments
2250607 @tmbrggmn Added basic version of i18n sample application.
tmbrggmn authored
225 // using the current language defined for this controller.
226 //
227 // The current language is set by the i18n plugin.
228 func (c *Controller) Message(message string, args ...interface{}) (value string) {
ae0235f @tmbrggmn Fixed minor issues found in pull request
tmbrggmn authored
229 return Message(c.Request.Locale, message, args...)
2250607 @tmbrggmn Added basic version of i18n sample application.
tmbrggmn authored
230 }
abc4648 @robfig Filters, booking app works, tests pass
authored
231
232 // SetAction sets the action that is being invoked in the current request.
233 // It sets the following properties: Name, Action, Type, MethodType
2f34d9c @robfig Revert the semantic change to Controller.Action and add MethodName in…
authored
234 func (c *Controller) SetAction(controllerName, methodName string) error {
abc4648 @robfig Filters, booking app works, tests pass
authored
235
2f34d9c @robfig Revert the semantic change to Controller.Action and add MethodName in…
authored
236 // Look up the controller and method types.
abc4648 @robfig Filters, booking app works, tests pass
authored
237 var ok bool
238 if c.Type, ok = controllers[strings.ToLower(controllerName)]; !ok {
239 return errors.New("revel/controller: failed to find controller " + controllerName)
240 }
2f34d9c @robfig Revert the semantic change to Controller.Action and add MethodName in…
authored
241 if c.MethodType = c.Type.Method(methodName); c.MethodType == nil {
242 return errors.New("revel/controller: failed to find action " + methodName)
abc4648 @robfig Filters, booking app works, tests pass
authored
243 }
244
1342d8e @pix64 Fix build failure
pix64 authored
245 c.Name, c.MethodName = c.Type.Type.Name(), methodName
94317fe @pix64 Use c.Name instead of c.Type.Type.Name() a second time
pix64 authored
246 c.Action = c.Name + "." + c.MethodName
2e3f6c5 @pix64 Make Controller Name use Controller Type instead of router output
pix64 authored
247
abc4648 @robfig Filters, booking app works, tests pass
authored
248 // Instantiate the controller.
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
249 c.AppController = initNewAppController(c.Type, c).Interface()
abc4648 @robfig Filters, booking app works, tests pass
authored
250
251 return nil
252 }
253
254 // This is a helper that initializes (zeros) a new app controller value.
5f8324e @robfig Improved testing
authored
255 // Specifically, it sets all *revel.Controller embedded types to the provided controller.
abc4648 @robfig Filters, booking app works, tests pass
authored
256 // Returns a value representing a pointer to the new app controller.
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
257 func initNewAppController(appControllerType *ControllerType, c *Controller) reflect.Value {
258 var (
259 appControllerPtr = reflect.New(appControllerType.Type)
260 appController = appControllerPtr.Elem()
261 cValue = reflect.ValueOf(c)
262 )
263 for _, index := range appControllerType.ControllerIndexes {
264 appController.FieldByIndex(index).Set(cValue)
265 }
266 return appControllerPtr
267 }
268
269 func findControllers(appControllerType reflect.Type) (indexes [][]int) {
5f8324e @robfig Improved testing
authored
270 // It might be a multi-level embedding. To find the controllers, we follow
271 // every anonymous field, using breadth-first search.
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
272 type nodeType struct {
273 val reflect.Value
274 index []int
275 }
abc4648 @robfig Filters, booking app works, tests pass
authored
276 appControllerPtr := reflect.New(appControllerType)
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
277 queue := []nodeType{{appControllerPtr, []int{}}}
278 for len(queue) > 0 {
abc4648 @robfig Filters, booking app works, tests pass
authored
279 // Get the next value and de-reference it if necessary.
280 var (
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
281 node = queue[0]
282 elem = node.val
283 elemType = elem.Type()
abc4648 @robfig Filters, booking app works, tests pass
authored
284 )
285 if elemType.Kind() == reflect.Ptr {
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
286 elem = elem.Elem()
abc4648 @robfig Filters, booking app works, tests pass
authored
287 elemType = elem.Type()
288 }
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
289 queue = queue[1:]
abc4648 @robfig Filters, booking app works, tests pass
authored
290
291 // Look at all the struct fields.
292 for i := 0; i < elem.NumField(); i++ {
293 // If this is not an anonymous field, skip it.
294 structField := elemType.Field(i)
295 if !structField.Anonymous {
296 continue
297 }
298
299 fieldValue := elem.Field(i)
300 fieldType := structField.Type
301
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
302 // If it's a Controller, record the field indexes to get here.
abc4648 @robfig Filters, booking app works, tests pass
authored
303 if fieldType == controllerPtrType {
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
304 indexes = append(indexes, append(node.index, i))
abc4648 @robfig Filters, booking app works, tests pass
authored
305 continue
306 }
307
5f8324e @robfig Improved testing
authored
308 queue = append(queue,
309 nodeType{fieldValue, append(append([]int{}, node.index...), i)})
abc4648 @robfig Filters, booking app works, tests pass
authored
310 }
311 }
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
312 return
abc4648 @robfig Filters, booking app works, tests pass
authored
313 }
314
315 // Controller registry and types.
316
317 type ControllerType struct {
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
318 Type reflect.Type
319 Methods []*MethodType
320 ControllerIndexes [][]int // FieldByIndex to all embedded *Controllers
abc4648 @robfig Filters, booking app works, tests pass
authored
321 }
322
323 type MethodType struct {
324 Name string
325 Args []*MethodArg
326 RenderArgNames map[int][]string
327 lowerName string
328 }
329
330 type MethodArg struct {
331 Name string
332 Type reflect.Type
333 }
334
335 // Searches for a given exported method (case insensitive)
336 func (ct *ControllerType) Method(name string) *MethodType {
337 lowerName := strings.ToLower(name)
338 for _, method := range ct.Methods {
339 if method.lowerName == lowerName {
340 return method
341 }
342 }
343 return nil
344 }
345
346 var controllers = make(map[string]*ControllerType)
347
348 // Register a Controller and its Methods with Revel.
349 func RegisterController(c interface{}, methods []*MethodType) {
350 // De-star the controller type
351 // (e.g. given TypeOf((*Application)(nil)), want TypeOf(Application))
352 var t reflect.Type = reflect.TypeOf(c)
353 var elem reflect.Type = t.Elem()
354
355 // De-star all of the method arg types too.
356 for _, m := range methods {
357 m.lowerName = strings.ToLower(m.Name)
358 for _, arg := range m.Args {
359 arg.Type = arg.Type.Elem()
360 }
361 }
362
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
363 controllers[strings.ToLower(elem.Name())] = &ControllerType{
364 Type: elem,
365 Methods: methods,
366 ControllerIndexes: findControllers(elem),
367 }
abc4648 @robfig Filters, booking app works, tests pass
authored
368 TRACE.Printf("Registered controller: %s", elem.Name())
369 }
Something went wrong with that request. Please try again.