forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
169 lines (144 loc) · 4.58 KB
/
server.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
package revel
import (
"code.google.com/p/go.net/websocket"
"fmt"
"net/http"
"net/url"
"path"
"reflect"
"time"
)
var (
MainRouter *Router
MainTemplateLoader *TemplateLoader
MainWatcher *Watcher
Server *http.Server
websocketType = reflect.TypeOf((*websocket.Conn)(nil))
)
// This method handles all requests. It dispatches to handleInternal after
// handling / adapting websocket connections.
func handle(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Upgrade") == "websocket" {
websocket.Handler(func(ws *websocket.Conn) {
r.Method = "WS"
handleInternal(w, r, ws)
}).ServeHTTP(w, r)
} else {
handleInternal(w, r, nil)
}
}
func handleInternal(w http.ResponseWriter, r *http.Request, ws *websocket.Conn) {
// TODO: StaticPathsCache
req, resp := NewRequest(r), NewResponse(w)
if MainWatcher != nil {
err := MainWatcher.Notify()
if err != nil {
RenderError(req, resp, err)
return
}
}
// Figure out the Controller/Action
var route *RouteMatch = MainRouter.Route(r)
if route == nil {
NotFound(req, resp, "No matching route found")
return
}
// The route may want to explicitly return a 404.
if route.Action == "404" {
NotFound(req, resp, "(intentionally)")
return
}
// Construct the controller and get the method to call.
controller, appControllerPtr := NewAppController(req, resp, route.ControllerName, route.MethodName)
if controller == nil {
NotFound(req, resp, fmt.Sprintln("No matching action found:", route.Action))
return
}
var method reflect.Value = appControllerPtr.MethodByName(controller.MethodType.Name)
if !method.IsValid() {
WARN.Printf("Function %s not found on Controller %s",
route.MethodName, route.ControllerName)
NotFound(req, resp, fmt.Sprintln("No matching action found:", route.Action))
return
}
// Add the route Params to the Request Params.
for key, value := range route.Params {
url.Values(controller.Params.Values).Add(key, value)
}
// Add the fixed parameters mapped by name.
for i, value := range route.FixedParams {
if i < len(controller.MethodType.Args) {
arg := controller.MethodType.Args[i]
controller.Params.Values.Set(arg.Name, value)
} else {
WARN.Println("Too many parameters to", route.Action, "trying to add", value)
break
}
}
// Collect the values for the method's arguments.
var actualArgs []reflect.Value
for _, arg := range controller.MethodType.Args {
// If they accept a websocket connection, treat that arg specially.
var boundArg reflect.Value
if arg.Type == websocketType {
boundArg = reflect.ValueOf(ws)
} else {
TRACE.Println("Binding:", arg.Name, "as", arg.Type)
boundArg = controller.Params.Bind(arg.Name, arg.Type)
}
actualArgs = append(actualArgs, boundArg)
}
// Invoke the method.
// (Note that the method Value is already bound to the appController receiver.)
controller.Invoke(appControllerPtr, method, actualArgs)
}
// Run the server.
// This is called from the generated main file.
// If port is non-zero, use that. Else, read the port from app.conf.
func Run(port int) {
address := HttpAddr
if port == 0 {
port = HttpPort
}
MainRouter = NewRouter(path.Join(BasePath, "conf", "routes"))
MainTemplateLoader = NewTemplateLoader(TemplatePaths)
// The "watch" config variable can turn on and off all watching.
// (As a convenient way to control it all together.)
if Config.BoolDefault("watch", true) {
MainWatcher = NewWatcher()
}
// If desired (or by default), create a watcher for templates and routes.
// The watcher calls Refresh() on things on the first request.
if MainWatcher != nil && Config.BoolDefault("watch.templates", true) {
MainWatcher.Listen(MainTemplateLoader, MainTemplateLoader.paths...)
} else {
MainTemplateLoader.Refresh()
}
if MainWatcher != nil && Config.BoolDefault("watch.routes", true) {
MainWatcher.auditor = PluginNotifier{plugins}
MainWatcher.Listen(MainRouter, MainRouter.path)
} else {
MainRouter.Refresh()
plugins.OnRoutesLoaded(MainRouter)
}
Server = &http.Server{
Addr: fmt.Sprintf("%s:%d", address, port),
Handler: http.HandlerFunc(handle),
}
plugins.OnAppStart()
go func() {
time.Sleep(100 * time.Millisecond)
fmt.Printf("Listening on port %d...\n", port)
}()
ERROR.Fatalln("Failed to listen:", Server.ListenAndServe())
}
// The PluginNotifier glues the watcher and the plugin collection together.
// It audits refreshes and invokes the appropriate method to inform the plugins.
type PluginNotifier struct {
plugins PluginCollection
}
func (pn PluginNotifier) OnRefresh(l Listener) {
if l == MainRouter {
pn.plugins.OnRoutesLoaded(MainRouter)
}
}