Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 360 lines (315 sloc) 10.659 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 inste...
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 inste...
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 vie...
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 {
119 return RenderJsonResult{o}
120 }
121
122 // Uses encoding/xml.Marshal to return XML to the client.
123 func (c *Controller) RenderXml(o interface{}) Result {
124 return RenderXmlResult{o}
125 }
126
127 // Render plaintext in response, printf style.
128 func (c *Controller) RenderText(text string, objs ...interface{}) Result {
129 finalText := text
130 if len(objs) > 0 {
ae6480d @robfig Make NotFound behave like Printf
authored
131 finalText = fmt.Sprintf(text, objs...)
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
132 }
133 return &RenderTextResult{finalText}
134 }
135
136 // Render a "todo" indicating that the action isn't done yet.
137 func (c *Controller) Todo() Result {
138 c.Response.Status = http.StatusNotImplemented
139 return c.RenderError(&Error{
140 Title: "TODO",
141 Description: "This action is not implemented",
142 })
143 }
144
ae6480d @robfig Make NotFound behave like Printf
authored
145 func (c *Controller) NotFound(msg string, objs ...interface{}) Result {
146 finalText := msg
147 if len(objs) > 0 {
148 finalText = fmt.Sprintf(msg, objs...)
149 }
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
150 c.Response.Status = http.StatusNotFound
151 return c.RenderError(&Error{
152 Title: "Not Found",
ae6480d @robfig Make NotFound behave like Printf
authored
153 Description: finalText,
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
154 })
155 }
156
c09912d @robfig Add a Forbidden() Result
authored
157 func (c *Controller) Forbidden(msg string, objs ...interface{}) Result {
158 finalText := msg
159 if len(objs) > 0 {
160 finalText = fmt.Sprintf(msg, objs...)
161 }
162 c.Response.Status = http.StatusForbidden
163 return c.RenderError(&Error{
164 Title: "Forbidden",
165 Description: finalText,
166 })
167 }
168
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
169 // Return a file, either displayed inline or downloaded as an attachment.
170 // The name and size are taken from the file info.
171 func (c *Controller) RenderFile(file *os.File, delivery ContentDisposition) Result {
1c74448 @robfig Make BinaryResult accept io.Readers instead of io.ReadSeeker
authored
172 var (
173 modtime = time.Now()
174 fileInfo, err = file.Stat()
175 )
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
176 if err != nil {
177 WARN.Println("RenderFile error:", err)
178 }
179 if fileInfo != nil {
1dccfef @jgraham909 Switch to use ServeContent instead of io.copy
jgraham909 authored
180 modtime = fileInfo.ModTime()
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
181 }
34d8c95 @jcvernaleo Modify RenderFile to call RenderBinary.
jcvernaleo authored
182 return c.RenderBinary(file, filepath.Base(file.Name()), delivery, modtime)
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
183 }
184
e693f0c @jcvernaleo Adjust function name and comments to better reflect what it does.
jcvernaleo authored
185 // RenderBinary is like RenderFile() except that it instead of a file on disk,
186 // it renders data from memory (which could be a file that has not been written,
187 // the output from some function, or bytes streamed from somewhere else, as long
f5f5b26 @jcvernaleo Update some comments.
jcvernaleo authored
188 // it implements io.Reader). When called directly on something generated or
189 // streamed, modtime should mostly likely be time.Now().
34d8c95 @jcvernaleo Modify RenderFile to call RenderBinary.
jcvernaleo authored
190 func (c *Controller) RenderBinary(memfile io.Reader, filename string, delivery ContentDisposition, modtime time.Time) Result {
278b71a @jcvernaleo Server a file from memory.
jcvernaleo authored
191 return &BinaryResult{
192 Reader: memfile,
193 Name: filename,
194 Delivery: delivery,
f5f5b26 @jcvernaleo Update some comments.
jcvernaleo authored
195 Length: -1, // http.ServeContent gets the length itself unless memfile is a stream.
278b71a @jcvernaleo Server a file from memory.
jcvernaleo authored
196 ModTime: modtime,
197 }
198 }
199
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
200 // Redirect to an action or to a URL.
201 // c.Redirect(Controller.Action)
202 // c.Redirect("/controller/action")
203 // c.Redirect("/controller/%d/action", id)
204 func (c *Controller) Redirect(val interface{}, args ...interface{}) Result {
205 if url, ok := val.(string); ok {
206 if len(args) == 0 {
207 return &RedirectToUrlResult{url}
208 }
209 return &RedirectToUrlResult{fmt.Sprintf(url, args...)}
210 }
211 return &RedirectToActionResult{val}
212 }
2250607 @tmbrggmn Added basic version of i18n sample application.
tmbrggmn authored
213
8751a76 @robfig Tweak error formatting
authored
214 // Perform a message lookup for the given message name using the given arguments
2250607 @tmbrggmn Added basic version of i18n sample application.
tmbrggmn authored
215 // using the current language defined for this controller.
216 //
217 // The current language is set by the i18n plugin.
218 func (c *Controller) Message(message string, args ...interface{}) (value string) {
ae0235f @tmbrggmn Fixed minor issues found in pull request
tmbrggmn authored
219 return Message(c.Request.Locale, message, args...)
2250607 @tmbrggmn Added basic version of i18n sample application.
tmbrggmn authored
220 }
abc4648 @robfig Filters, booking app works, tests pass
authored
221
222 // SetAction sets the action that is being invoked in the current request.
223 // It sets the following properties: Name, Action, Type, MethodType
2f34d9c @robfig Revert the semantic change to Controller.Action and add MethodName inste...
authored
224 func (c *Controller) SetAction(controllerName, methodName string) error {
abc4648 @robfig Filters, booking app works, tests pass
authored
225
2f34d9c @robfig Revert the semantic change to Controller.Action and add MethodName inste...
authored
226 // Look up the controller and method types.
abc4648 @robfig Filters, booking app works, tests pass
authored
227 var ok bool
228 if c.Type, ok = controllers[strings.ToLower(controllerName)]; !ok {
229 return errors.New("revel/controller: failed to find controller " + controllerName)
230 }
2f34d9c @robfig Revert the semantic change to Controller.Action and add MethodName inste...
authored
231 if c.MethodType = c.Type.Method(methodName); c.MethodType == nil {
232 return errors.New("revel/controller: failed to find action " + methodName)
abc4648 @robfig Filters, booking app works, tests pass
authored
233 }
234
1342d8e @pix64 Fix build failure
pix64 authored
235 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
236 c.Action = c.Name + "." + c.MethodName
2e3f6c5 @pix64 Make Controller Name use Controller Type instead of router output
pix64 authored
237
abc4648 @robfig Filters, booking app works, tests pass
authored
238 // Instantiate the controller.
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
239 c.AppController = initNewAppController(c.Type, c).Interface()
abc4648 @robfig Filters, booking app works, tests pass
authored
240
241 return nil
242 }
243
244 // This is a helper that initializes (zeros) a new app controller value.
5f8324e @robfig Improved testing
authored
245 // Specifically, it sets all *revel.Controller embedded types to the provided controller.
abc4648 @robfig Filters, booking app works, tests pass
authored
246 // Returns a value representing a pointer to the new app controller.
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
247 func initNewAppController(appControllerType *ControllerType, c *Controller) reflect.Value {
248 var (
249 appControllerPtr = reflect.New(appControllerType.Type)
250 appController = appControllerPtr.Elem()
251 cValue = reflect.ValueOf(c)
252 )
253 for _, index := range appControllerType.ControllerIndexes {
254 appController.FieldByIndex(index).Set(cValue)
255 }
256 return appControllerPtr
257 }
258
259 func findControllers(appControllerType reflect.Type) (indexes [][]int) {
5f8324e @robfig Improved testing
authored
260 // It might be a multi-level embedding. To find the controllers, we follow
261 // every anonymous field, using breadth-first search.
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
262 type nodeType struct {
263 val reflect.Value
264 index []int
265 }
abc4648 @robfig Filters, booking app works, tests pass
authored
266 appControllerPtr := reflect.New(appControllerType)
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
267 queue := []nodeType{{appControllerPtr, []int{}}}
268 for len(queue) > 0 {
abc4648 @robfig Filters, booking app works, tests pass
authored
269 // Get the next value and de-reference it if necessary.
270 var (
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
271 node = queue[0]
272 elem = node.val
273 elemType = elem.Type()
abc4648 @robfig Filters, booking app works, tests pass
authored
274 )
275 if elemType.Kind() == reflect.Ptr {
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
276 elem = elem.Elem()
abc4648 @robfig Filters, booking app works, tests pass
authored
277 elemType = elem.Type()
278 }
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
279 queue = queue[1:]
abc4648 @robfig Filters, booking app works, tests pass
authored
280
281 // Look at all the struct fields.
282 for i := 0; i < elem.NumField(); i++ {
283 // If this is not an anonymous field, skip it.
284 structField := elemType.Field(i)
285 if !structField.Anonymous {
286 continue
287 }
288
289 fieldValue := elem.Field(i)
290 fieldType := structField.Type
291
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
292 // If it's a Controller, record the field indexes to get here.
abc4648 @robfig Filters, booking app works, tests pass
authored
293 if fieldType == controllerPtrType {
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
294 indexes = append(indexes, append(node.index, i))
abc4648 @robfig Filters, booking app works, tests pass
authored
295 continue
296 }
297
5f8324e @robfig Improved testing
authored
298 queue = append(queue,
299 nodeType{fieldValue, append(append([]int{}, node.index...), i)})
abc4648 @robfig Filters, booking app works, tests pass
authored
300 }
301 }
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
302 return
abc4648 @robfig Filters, booking app works, tests pass
authored
303 }
304
305 // Controller registry and types.
306
307 type ControllerType struct {
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
308 Type reflect.Type
309 Methods []*MethodType
310 ControllerIndexes [][]int // FieldByIndex to all embedded *Controllers
abc4648 @robfig Filters, booking app works, tests pass
authored
311 }
312
313 type MethodType struct {
314 Name string
315 Args []*MethodArg
316 RenderArgNames map[int][]string
317 lowerName string
318 }
319
320 type MethodArg struct {
321 Name string
322 Type reflect.Type
323 }
324
325 // Searches for a given exported method (case insensitive)
326 func (ct *ControllerType) Method(name string) *MethodType {
327 lowerName := strings.ToLower(name)
328 for _, method := range ct.Methods {
329 if method.lowerName == lowerName {
330 return method
331 }
332 }
333 return nil
334 }
335
336 var controllers = make(map[string]*ControllerType)
337
338 // Register a Controller and its Methods with Revel.
339 func RegisterController(c interface{}, methods []*MethodType) {
340 // De-star the controller type
341 // (e.g. given TypeOf((*Application)(nil)), want TypeOf(Application))
342 var t reflect.Type = reflect.TypeOf(c)
343 var elem reflect.Type = t.Elem()
344
345 // De-star all of the method arg types too.
346 for _, m := range methods {
347 m.lowerName = strings.ToLower(m.Name)
348 for _, arg := range m.Args {
349 arg.Type = arg.Type.Elem()
350 }
351 }
352
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
353 controllers[strings.ToLower(elem.Name())] = &ControllerType{
354 Type: elem,
355 Methods: methods,
356 ControllerIndexes: findControllers(elem),
357 }
abc4648 @robfig Filters, booking app works, tests pass
authored
358 TRACE.Printf("Registered controller: %s", elem.Name())
359 }
Something went wrong with that request. Please try again.