This repository has been archived by the owner on Oct 27, 2022. It is now read-only.
forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
242 lines (212 loc) · 6.69 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
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Copyright (c) 2012-2016 The Revel Framework Authors, All rights reserved.
// Revel Framework source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package revel
import (
"fmt"
"io"
"net"
"net/http"
"sort"
"strconv"
"strings"
"time"
"golang.org/x/net/websocket"
)
// Revel's variables server, router, etc
var (
MainRouter *Router
MainTemplateLoader *TemplateLoader
MainWatcher *Watcher
Server *http.Server
)
// This method handles all requests. It dispatches to handleInternal after
// handling / adapting websocket connections.
func handle(w http.ResponseWriter, r *http.Request) {
if maxRequestSize := int64(Config.IntDefault("http.maxrequestsize", 0)); maxRequestSize > 0 {
r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
}
upgrade := r.Header.Get("Upgrade")
if upgrade == "websocket" || upgrade == "Websocket" {
websocket.Handler(func(ws *websocket.Conn) {
//Override default Read/Write timeout with sane value for a web socket request
if err := ws.SetDeadline(time.Now().Add(time.Hour * 24)); err != nil {
ERROR.Println("SetDeadLine failed:", err)
}
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 For now this okay to put logger here for all the requests
// However, it's best to have logging handler at server entry level
start := time.Now()
clientIP := ClientIP(r)
var (
req = NewRequest(r)
resp = NewResponse(w)
c = NewController(req, resp)
)
req.Websocket = ws
c.ClientIP = clientIP
Filters[0](c, Filters[1:])
if c.Result != nil {
c.Result.Apply(req, resp)
} else if c.Response.Status != 0 {
c.Response.Out.WriteHeader(c.Response.Status)
}
// Close the Writer if we can
if w, ok := resp.Out.(io.Closer); ok {
_ = w.Close()
}
// Revel request access log format
// RequestStartTime ClientIP ResponseStatus RequestLatency HTTPMethod URLPath
// Sample format:
// 2016/05/25 17:46:37.112 127.0.0.1 200 270.157µs GET /
requestLog.Printf("%v %v %v %10v %v %v",
start.Format(requestLogTimeFormat),
clientIP,
c.Response.Status,
time.Since(start),
r.Method,
r.URL.Path,
)
}
// InitServer intializes the server and returns the handler
// It can be used as an alternative entry-point if one needs the http handler
// to be exposed. E.g. to run on multiple addresses and ports or to set custom
// TLS options.
func InitServer() http.HandlerFunc {
runStartupHooks()
// Load templates
MainTemplateLoader = NewTemplateLoader(TemplatePaths)
if err := MainTemplateLoader.Refresh(); err != nil {
ERROR.Println(err)
}
// 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()
Filters = append([]Filter{WatchFilter}, Filters...)
}
// 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...)
}
return http.HandlerFunc(handle)
}
// 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
}
var network = "tcp"
var localAddress string
// If the port is zero, treat the address as a fully qualified local address.
// This address must be prefixed with the network type followed by a colon,
// e.g. unix:/tmp/app.socket or tcp6:::1 (equivalent to tcp6:0:0:0:0:0:0:0:1)
if port == 0 {
parts := strings.SplitN(address, ":", 2)
network = parts[0]
localAddress = parts[1]
} else {
localAddress = address + ":" + strconv.Itoa(port)
}
Server = &http.Server{
Addr: localAddress,
Handler: http.HandlerFunc(handle),
ReadTimeout: time.Duration(Config.IntDefault("http.timeout.read", 0)) * time.Second,
WriteTimeout: time.Duration(Config.IntDefault("http.timeout.write", 0)) * time.Second,
}
InitServer()
go func() {
time.Sleep(100 * time.Millisecond)
fmt.Printf("Listening on %s...\n", Server.Addr)
}()
if HTTPSsl {
if network != "tcp" {
// This limitation is just to reduce complexity, since it is standard
// to terminate SSL upstream when using unix domain sockets.
ERROR.Fatalln("SSL is only supported for TCP sockets. Specify a port to listen on.")
}
ERROR.Fatalln("Failed to listen:",
Server.ListenAndServeTLS(HTTPSslCert, HTTPSslKey))
} else {
listener, err := net.Listen(network, Server.Addr)
if err != nil {
ERROR.Fatalln("Failed to listen:", err)
}
ERROR.Fatalln("Failed to serve:", Server.Serve(listener))
}
}
func runStartupHooks() {
sort.Sort(startupHooks)
for _, hook := range startupHooks {
hook.f()
}
}
type StartupHook struct {
order int
f func()
}
type StartupHooks []StartupHook
var startupHooks StartupHooks
func (slice StartupHooks) Len() int {
return len(slice)
}
func (slice StartupHooks) Less(i, j int) bool {
return slice[i].order < slice[j].order
}
func (slice StartupHooks) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// OnAppStart registers a function to be run at app startup.
//
// The order you register the functions will be the order they are run.
// You can think of it as a FIFO queue.
// This process will happen after the config file is read
// and before the server is listening for connections.
//
// Ideally, your application should have only one call to init() in the file init.go.
// The reason being that the call order of multiple init() functions in
// the same package is undefined.
// Inside of init() call revel.OnAppStart() for each function you wish to register.
//
// Example:
//
// // from: yourapp/app/controllers/somefile.go
// func InitDB() {
// // do DB connection stuff here
// }
//
// func FillCache() {
// // fill a cache from DB
// // this depends on InitDB having been run
// }
//
// // from: yourapp/app/init.go
// func init() {
// // set up filters...
//
// // register startup functions
// revel.OnAppStart(InitDB)
// revel.OnAppStart(FillCache)
// }
//
// This can be useful when you need to establish connections to databases or third-party services,
// setup app components, compile assets, or any thing you need to do between starting Revel and accepting connections.
//
func OnAppStart(f func(), order ...int) {
o := 1
if len(order) > 0 {
o = order[0]
}
startupHooks = append(startupHooks, StartupHook{order: o, f: f})
}