forked from revel/revel
/
mvc.go
218 lines (186 loc) · 6.03 KB
/
mvc.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
package rev
import (
"net/http"
"reflect"
"strings"
)
type Request struct {
*http.Request
ContentType string
Format string // "html", "xml", "json", or "text"
}
type Response struct {
Status int
ContentType string
Out http.ResponseWriter
}
func NewRequest(r *http.Request) *Request {
return &Request{
Request: r,
ContentType: ResolveContentType(r),
Format: ResolveFormat(r),
}
}
func NewResponse(w http.ResponseWriter) *Response {
return &Response{Out: w}
}
var (
controllerType = reflect.TypeOf(Controller{})
controllerPtrType = reflect.TypeOf(&Controller{})
)
func NewAppController(req *Request, resp *Response, controllerName, methodName string) (*Controller, reflect.Value) {
var appControllerType *ControllerType = LookupControllerType(controllerName)
if appControllerType == nil {
INFO.Printf("Controller %s not found: %s", controllerName, req.URL)
return nil, reflect.ValueOf(nil)
}
controller := NewController(req, resp, appControllerType)
appControllerPtr := initNewAppController(appControllerType.Type, controller)
// Set the method being called.
controller.AppController = appControllerPtr.Interface()
controller.MethodType = appControllerType.Method(methodName)
if controller.MethodType == nil {
INFO.Println("Failed to find method", methodName, "on Controller",
controllerName)
return nil, reflect.ValueOf(nil)
}
return controller, appControllerPtr
}
// This is a helper that initializes (zeros) a new app controller value.
// Generally, everything is set to its zero value, except:
// 1. Embedded controller pointers are newed up.
// 2. The rev.Controller embedded type is set to the value provided.
// Returns a value representing a pointer to the new app controller.
func initNewAppController(appControllerType reflect.Type, c *Controller) reflect.Value {
// It might be a multi-level embedding, so we have to create new controllers
// at every level of the hierarchy.
// ASSUME: the first field in each type is the way up to rev.Controller.
appControllerPtr := reflect.New(appControllerType)
ptr := appControllerPtr
for {
var (
embeddedField reflect.Value = ptr.Elem().Field(0)
embeddedFieldType reflect.Type = embeddedField.Type()
)
// Check if it's the controller.
if embeddedFieldType == controllerType {
embeddedField.Set(reflect.ValueOf(c).Elem())
break
} else if embeddedFieldType == controllerPtrType {
embeddedField.Set(reflect.ValueOf(c))
break
}
// If the embedded field is a pointer, then instantiate an object and set it.
// (If it's not a pointer, then it's already initialized)
if embeddedFieldType.Kind() == reflect.Ptr {
embeddedField.Set(reflect.New(embeddedFieldType.Elem()))
ptr = embeddedField
} else {
ptr = embeddedField.Addr()
}
}
return appControllerPtr
}
func RenderError(req *Request, resp *Response, err error) {
stubController(req, resp).RenderError(err).Apply(req, resp)
}
// This function is useful if there is no relevant Controller available.
// It writes the 404 response immediately.
func NotFound(req *Request, resp *Response, msg string) {
stubController(req, resp).NotFound(msg).Apply(req, resp)
}
func stubController(req *Request, resp *Response) *Controller {
return &Controller{
Response: resp,
RenderArgs: map[string]interface{}{
"RunMode": RunMode,
},
}
}
// Get the content type.
// e.g. From "multipart/form-data; boundary=--" to "multipart/form-data"
// If none is specified, returns "text/html" by default.
func ResolveContentType(req *http.Request) string {
contentType := req.Header.Get("Content-Type")
if contentType == "" {
return "text/html"
}
return strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0]))
}
func ResolveFormat(req *http.Request) string {
accept := req.Header.Get("accept")
switch {
case accept == "",
strings.HasPrefix(accept, "*/*"), // */
strings.Contains(accept, "application/xhtml"),
strings.Contains(accept, "text/html"):
return "html"
case strings.Contains(accept, "application/xml"),
strings.Contains(accept, "text/xml"):
return "xml"
case strings.Contains(accept, "text/plain"):
return "txt"
case strings.Contains(accept, "application/json"),
strings.Contains(accept, "text/javascript"):
return "json"
}
return "html"
}
// Write the header (for now, just the status code).
// The status may be set directly by the application (c.Response.Status = 501).
// if it isn't, then fall back to the provided status code.
func (resp *Response) WriteHeader(defaultStatusCode int, defaultContentType string) {
if resp.Status == 0 {
resp.Status = defaultStatusCode
}
if resp.ContentType == "" {
resp.ContentType = defaultContentType
}
resp.Out.Header().Set("Content-Type", resp.ContentType)
resp.Out.WriteHeader(resp.Status)
}
// Internal bookeeping
type ControllerType struct {
Type reflect.Type
Methods []*MethodType
}
type MethodType struct {
Name string
Args []*MethodArg
RenderArgNames map[int][]string
lowerName string
}
type MethodArg struct {
Name string
Type reflect.Type
}
// Searches for a given exported method (case insensitive)
func (ct *ControllerType) Method(name string) *MethodType {
lowerName := strings.ToLower(name)
for _, method := range ct.Methods {
if method.lowerName == lowerName {
return method
}
}
return nil
}
var controllers = make(map[string]*ControllerType)
// Register a Controller and its Methods with Revel.
func RegisterController(c interface{}, methods []*MethodType) {
// De-star the controller type
// (e.g. given TypeOf((*Application)(nil)), want TypeOf(Application))
var t reflect.Type = reflect.TypeOf(c)
var elem reflect.Type = t.Elem()
// De-star all of the method arg types too.
for _, m := range methods {
m.lowerName = strings.ToLower(m.Name)
for _, arg := range m.Args {
arg.Type = arg.Type.Elem()
}
}
controllers[strings.ToLower(elem.Name())] = &ControllerType{Type: elem, Methods: methods}
TRACE.Printf("Registered controller: %s", elem.Name())
}
func LookupControllerType(name string) *ControllerType {
return controllers[strings.ToLower(name)]
}