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