Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 368 lines (323 sloc) 10.651 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 {
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 }
182 return &BinaryResult{
1c74448 @robfig Make BinaryResult accept io.Readers instead of io.ReadSeeker
authored
183 Reader: file,
184 Name: filepath.Base(file.Name()),
185 Delivery: delivery,
186 Length: -1, // http.ServeContent gets the length itself
187 ModTime: modtime,
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
188 }
189 }
190
e693f0c @jcvernaleo Adjust function name and comments to better reflect what it does.
jcvernaleo authored
191 // RenderBinary is like RenderFile() except that it instead of a file on disk,
192 // it renders data from memory (which could be a file that has not been written,
193 // the output from some function, or bytes streamed from somewhere else, as long
194 // it implements io.Reader).
195 func (c *Controller) RenderBinary(memfile io.Reader, filename string, delivery ContentDisposition) Result {
278b71a @jcvernaleo Server a file from memory.
jcvernaleo authored
196 var (
197 modtime = time.Now()
198 )
199 return &BinaryResult{
200 Reader: memfile,
201 Name: filename,
202 Delivery: delivery,
203 Length: -1, // http.ServeContent gets the length itself
204 ModTime: modtime,
205 }
206 }
207
22f08f0 @robfig Refactor mvc.go into {mvc,controller,session,flash,params}.go
authored
208 // Redirect to an action or to a URL.
209 // c.Redirect(Controller.Action)
210 // c.Redirect("/controller/action")
211 // c.Redirect("/controller/%d/action", id)
212 func (c *Controller) Redirect(val interface{}, args ...interface{}) Result {
213 if url, ok := val.(string); ok {
214 if len(args) == 0 {
215 return &RedirectToUrlResult{url}
216 }
217 return &RedirectToUrlResult{fmt.Sprintf(url, args...)}
218 }
219 return &RedirectToActionResult{val}
220 }
2250607 @tmbrggmn Added basic version of i18n sample application.
tmbrggmn authored
221
8751a76 @robfig Tweak error formatting
authored
222 // Perform a message lookup for the given message name using the given arguments
2250607 @tmbrggmn Added basic version of i18n sample application.
tmbrggmn authored
223 // using the current language defined for this controller.
224 //
225 // The current language is set by the i18n plugin.
226 func (c *Controller) Message(message string, args ...interface{}) (value string) {
ae0235f @tmbrggmn Fixed minor issues found in pull request
tmbrggmn authored
227 return Message(c.Request.Locale, message, args...)
2250607 @tmbrggmn Added basic version of i18n sample application.
tmbrggmn authored
228 }
abc4648 @robfig Filters, booking app works, tests pass
authored
229
230 // SetAction sets the action that is being invoked in the current request.
231 // It sets the following properties: Name, Action, Type, MethodType
2f34d9c @robfig Revert the semantic change to Controller.Action and add MethodName in…
authored
232 func (c *Controller) SetAction(controllerName, methodName string) error {
abc4648 @robfig Filters, booking app works, tests pass
authored
233
2f34d9c @robfig Revert the semantic change to Controller.Action and add MethodName in…
authored
234 // Look up the controller and method types.
abc4648 @robfig Filters, booking app works, tests pass
authored
235 var ok bool
236 if c.Type, ok = controllers[strings.ToLower(controllerName)]; !ok {
237 return errors.New("revel/controller: failed to find controller " + controllerName)
238 }
2f34d9c @robfig Revert the semantic change to Controller.Action and add MethodName in…
authored
239 if c.MethodType = c.Type.Method(methodName); c.MethodType == nil {
240 return errors.New("revel/controller: failed to find action " + methodName)
abc4648 @robfig Filters, booking app works, tests pass
authored
241 }
242
1342d8e @pix64 Fix build failure
pix64 authored
243 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
244 c.Action = c.Name + "." + c.MethodName
2e3f6c5 @pix64 Make Controller Name use Controller Type instead of router output
pix64 authored
245
abc4648 @robfig Filters, booking app works, tests pass
authored
246 // Instantiate the controller.
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
247 c.AppController = initNewAppController(c.Type, c).Interface()
abc4648 @robfig Filters, booking app works, tests pass
authored
248
249 return nil
250 }
251
252 // This is a helper that initializes (zeros) a new app controller value.
5f8324e @robfig Improved testing
authored
253 // Specifically, it sets all *revel.Controller embedded types to the provided controller.
abc4648 @robfig Filters, booking app works, tests pass
authored
254 // Returns a value representing a pointer to the new app controller.
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
255 func initNewAppController(appControllerType *ControllerType, c *Controller) reflect.Value {
256 var (
257 appControllerPtr = reflect.New(appControllerType.Type)
258 appController = appControllerPtr.Elem()
259 cValue = reflect.ValueOf(c)
260 )
261 for _, index := range appControllerType.ControllerIndexes {
262 appController.FieldByIndex(index).Set(cValue)
263 }
264 return appControllerPtr
265 }
266
267 func findControllers(appControllerType reflect.Type) (indexes [][]int) {
5f8324e @robfig Improved testing
authored
268 // It might be a multi-level embedding. To find the controllers, we follow
269 // every anonymous field, using breadth-first search.
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
270 type nodeType struct {
271 val reflect.Value
272 index []int
273 }
abc4648 @robfig Filters, booking app works, tests pass
authored
274 appControllerPtr := reflect.New(appControllerType)
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
275 queue := []nodeType{{appControllerPtr, []int{}}}
276 for len(queue) > 0 {
abc4648 @robfig Filters, booking app works, tests pass
authored
277 // Get the next value and de-reference it if necessary.
278 var (
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
279 node = queue[0]
280 elem = node.val
281 elemType = elem.Type()
abc4648 @robfig Filters, booking app works, tests pass
authored
282 )
283 if elemType.Kind() == reflect.Ptr {
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
284 elem = elem.Elem()
abc4648 @robfig Filters, booking app works, tests pass
authored
285 elemType = elem.Type()
286 }
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
287 queue = queue[1:]
abc4648 @robfig Filters, booking app works, tests pass
authored
288
289 // Look at all the struct fields.
290 for i := 0; i < elem.NumField(); i++ {
291 // If this is not an anonymous field, skip it.
292 structField := elemType.Field(i)
293 if !structField.Anonymous {
294 continue
295 }
296
297 fieldValue := elem.Field(i)
298 fieldType := structField.Type
299
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
300 // If it's a Controller, record the field indexes to get here.
abc4648 @robfig Filters, booking app works, tests pass
authored
301 if fieldType == controllerPtrType {
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
302 indexes = append(indexes, append(node.index, i))
abc4648 @robfig Filters, booking app works, tests pass
authored
303 continue
304 }
305
5f8324e @robfig Improved testing
authored
306 queue = append(queue,
307 nodeType{fieldValue, append(append([]int{}, node.index...), i)})
abc4648 @robfig Filters, booking app works, tests pass
authored
308 }
309 }
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
310 return
abc4648 @robfig Filters, booking app works, tests pass
authored
311 }
312
313 // Controller registry and types.
314
315 type ControllerType struct {
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
316 Type reflect.Type
317 Methods []*MethodType
318 ControllerIndexes [][]int // FieldByIndex to all embedded *Controllers
abc4648 @robfig Filters, booking app works, tests pass
authored
319 }
320
321 type MethodType struct {
322 Name string
323 Args []*MethodArg
324 RenderArgNames map[int][]string
325 lowerName string
326 }
327
328 type MethodArg struct {
329 Name string
330 Type reflect.Type
331 }
332
333 // Searches for a given exported method (case insensitive)
334 func (ct *ControllerType) Method(name string) *MethodType {
335 lowerName := strings.ToLower(name)
336 for _, method := range ct.Methods {
337 if method.lowerName == lowerName {
338 return method
339 }
340 }
341 return nil
342 }
343
344 var controllers = make(map[string]*ControllerType)
345
346 // Register a Controller and its Methods with Revel.
347 func RegisterController(c interface{}, methods []*MethodType) {
348 // De-star the controller type
349 // (e.g. given TypeOf((*Application)(nil)), want TypeOf(Application))
350 var t reflect.Type = reflect.TypeOf(c)
351 var elem reflect.Type = t.Elem()
352
353 // De-star all of the method arg types too.
354 for _, m := range methods {
355 m.lowerName = strings.ToLower(m.Name)
356 for _, arg := range m.Args {
357 arg.Type = arg.Type.Elem()
358 }
359 }
360
2a7e77b @robfig Pre-calculate the indexes to embedded controllers.
authored
361 controllers[strings.ToLower(elem.Name())] = &ControllerType{
362 Type: elem,
363 Methods: methods,
364 ControllerIndexes: findControllers(elem),
365 }
abc4648 @robfig Filters, booking app works, tests pass
authored
366 TRACE.Printf("Registered controller: %s", elem.Name())
367 }
Something went wrong with that request. Please try again.