This repository has been archived by the owner on Jun 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
392 lines (345 loc) · 10 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package webx
import (
"crypto/tls"
"net"
"net/http"
"net/http/pprof"
"os"
"runtime"
runtimePprof "runtime/pprof"
"strconv"
"strings"
"time"
"github.com/coscms/webx/lib/httpsession"
"github.com/coscms/webx/lib/log"
S "github.com/coscms/webx/lib/manners"
"golang.org/x/net/netutil"
)
// ServerConfig is configuration for server objects.
type ServerConfig struct {
Addr string
Port int
RecoverPanic bool
Profiler bool
EnableGzip bool
StaticExtensionsToGzip []string
Url string
UrlPrefix string
UrlSuffix string
StaticHtmlDir string
SessionTimeout time.Duration
MaxConnections int
UseSSL bool
TlsConfig *tls.Config
Debug bool
GracefulShutdown bool
}
// Server represents a webx server.
type Server struct {
Config *ServerConfig
Apps map[string]*App //r["root"]
App2Domain map[string]string //r["root"]="www.coscms.com"
Domain2App map[string]string //r["www.coscms.com"]="root"
AppsNamePath map[string]string //r["root"]="/"
Name string
SessionManager *httpsession.Manager
RootApp *App
Logger *log.Logger
Env map[string]interface{}
Mux *http.ServeMux
//save the listener so it can be closed
l net.Listener
}
func NewServer(name string, args ...*ServerConfig) *Server {
s := &Server{
Env: map[string]interface{}{},
Apps: map[string]*App{},
App2Domain: map[string]string{},
Domain2App: map[string]string{},
AppsNamePath: map[string]string{},
Name: name,
}
if len(args) > 0 {
s.Config = args[0]
} else {
s.Config = Config
}
Servers[s.Name] = s
s.SetLogger(log.New(os.Stdout, "", log.Ldefault()))
app := NewApp("/", "root")
s.AddApp(app)
return s
}
func (s *Server) AddApp(a *App) {
a.BasePath = strings.TrimRight(a.BasePath, "/") + "/"
s.Apps[a.BasePath] = a
if a.Name != "" {
s.AppsNamePath[a.Name] = a.BasePath
}
a.Server = s
a.Logger = s.Logger
if a.BasePath == "/" {
s.RootApp = a
}
}
func (s *Server) AddAction(cs ...interface{}) {
s.RootApp.AddAction(cs...)
}
func (s *Server) AutoAction(c ...interface{}) {
s.RootApp.AutoAction(c...)
}
func (s *Server) AddRouter(url string, c interface{}) {
s.RootApp.AddRouter(url, c)
}
func (s *Server) Assign(name string, varOrFun interface{}) {
s.RootApp.Assign(name, varOrFun)
}
func (s *Server) MultiAssign(t *T) {
s.RootApp.MultiAssign(t)
}
func (s *Server) AddFilter(filter Filter) {
s.RootApp.AddFilter(filter)
}
func (s *Server) AddConfig(name string, value interface{}) {
s.RootApp.SetConfig(name, value)
}
func (s *Server) SetConfig(name string, value interface{}) {
s.RootApp.SetConfig(name, value)
}
func (s *Server) GetConfig(name string) interface{} {
return s.RootApp.GetConfig(name)
}
func (s *Server) error(w http.ResponseWriter, status int, content string) error {
return s.RootApp.error(w, status, content)
}
func (s *Server) initServer() {
if s.Config == nil {
s.Config = &ServerConfig{}
s.Config.Profiler = true
}
Event("webx."+s.Name+":initServer", s, func(r bool) {
if !r {
return
}
for _, app := range s.Apps {
app.initApp()
Event("webx."+s.Name+"."+app.Name+":initApp", app, func(_ bool) {})
}
})
}
// ServeHTTP is the interface method for Go's http server package
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
s.Process(w, req)
}
type ServerInformation struct {
*Server
http.ResponseWriter
*http.Request
}
// Process invokes the routing system for server s
// non-root app's route will override root app's if there is same path
func (s *Server) Process(w http.ResponseWriter, req *http.Request) {
s.RootApp.RequestTime = time.Now()
//set some default headers
w.Header().Set("Server", "webx v"+Version)
w.Header().Set("Date", webTime(s.RootApp.RequestTime.UTC()))
Event("webx:process", &ServerInformation{s, w, req}, func(result bool) {
if !result {
return
}
// static files, needed op
if req.Method == "GET" || req.Method == "HEAD" {
success, size := s.RootApp.TryServingFile(req.URL.Path, req, w)
if success {
s.RootApp.VisitedLog(req, 200, req.URL.Path, size)
return
}
if req.URL.Path == "/favicon.ico" {
s.RootApp.error(w, 404, "Page not found")
s.RootApp.VisitedLog(req, 404, req.URL.Path, size)
return
}
}
if s.Config.UrlSuffix != "" && strings.HasSuffix(req.URL.Path, s.Config.UrlSuffix) {
req.URL.Path = strings.TrimSuffix(req.URL.Path, s.Config.UrlSuffix)
}
if s.Config.UrlPrefix != "" && strings.HasPrefix(req.URL.Path, "/"+s.Config.UrlPrefix) {
req.URL.Path = strings.TrimPrefix(req.URL.Path, "/"+s.Config.UrlPrefix)
}
if req.URL.Path[0] != '/' {
req.URL.Path = "/" + req.URL.Path
}
if len(s.Domain2App) > 0 {
var hostKey string
if pos := strings.LastIndex(req.Host, ":"); pos <= 0 || req.Host[pos+1:] != "80" {
hostKey = req.Host
} else {
hostKey = req.Host[0:pos]
}
var appName string
if v, ok := s.Domain2App[hostKey]; ok {
appName = v
} else if v, ok := s.Domain2App["//"+hostKey]; ok {
appName = v
} else if v, ok := s.Domain2App[req.URL.Scheme+"://"+hostKey]; ok {
appName = v
}
if appName != "" {
if app := s.App(appName); app != nil {
app.RequestTime = s.RootApp.RequestTime
app.routeHandler(req, w)
return
}
}
}
for _, app := range s.Apps {
if app != s.RootApp && strings.HasPrefix(req.URL.Path, app.BasePath) {
app.RequestTime = s.RootApp.RequestTime
app.routeHandler(req, w)
return
}
}
s.RootApp.routeHandler(req, w)
})
}
// Run starts the web application and serves HTTP requests for s
func (s *Server) Run(addr string) error {
if s.Config.UseSSL {
return s.RunTLS(addr, s.Config.TlsConfig)
}
l, err := net.Listen("tcp", addr)
if err != nil {
s.Logger.Error("ListenAndServe:", err)
return err
}
s.Logger.Infof("http server is listening %s", addr)
return s.run(addr, l)
}
func (s *Server) run(addr string, l net.Listener) (err error) {
if s.Config.Debug {
println(`[webx] Server "` + s.Name + `" has been launched.`)
}
addrs := strings.Split(addr, ":")
s.Config.Addr = addrs[0]
s.Config.Port, _ = strconv.Atoi(addrs[1])
s.initServer()
mux := http.NewServeMux()
if s.Config.Profiler {
mux.Handle("/debug/pprof", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
redirect(rw, "/debug/pprof/")
}))
mux.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
mux.Handle("/debug/pprof/heap", pprof.Handler("heap"))
mux.Handle("/debug/pprof/block", pprof.Handler("block"))
mux.Handle("/debug/pprof/goroutine", pprof.Handler("goroutine"))
mux.Handle("/debug/pprof/threadcreate", pprof.Handler("threadcreate"))
mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
mux.Handle("/debug/pprof/startcpuprof", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
StartCPUProfile()
}))
mux.Handle("/debug/pprof/stopcpuprof", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
StopCPUProfile()
}))
mux.Handle("/debug/pprof/memprof", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
runtime.GC()
runtimePprof.WriteHeapProfile(rw)
}))
mux.Handle("/debug/pprof/gc", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
PrintGCSummary(rw)
}))
}
s.Mux = mux
Event("webx:muxHandle", s, func(result bool) {
if result {
mux.Handle("/", s)
}
})
if s.Config.MaxConnections > 0 {
l = netutil.LimitListener(l, s.Config.MaxConnections)
}
s.l = l
if s.Config.GracefulShutdown {
err = S.Serve(s.l, mux)
} else {
err = http.Serve(s.l, mux)
}
s.Close()
if s.Config.Debug {
println(`[webx] Server "` + s.Name + `" has been closed.`)
}
return
}
// RunFcgi starts the web application and serves FastCGI requests for s.
func (s *Server) RunFcgi(addr string) {
s.initServer()
s.Logger.Infof("fcgi server is listening %s", addr)
s.listenAndServeFcgi(addr)
}
// RunScgi starts the web application and serves SCGI requests for s.
func (s *Server) RunScgi(addr string) {
s.initServer()
s.Logger.Infof("scgi server is listening %s", addr)
s.listenAndServeScgi(addr)
}
// RunTLS starts the web application and serves HTTPS requests for s.
func (s *Server) RunTLS(addr string, config *tls.Config) error {
l, err := tls.Listen("tcp", addr, config)
if err != nil {
s.Logger.Errorf("Listen: %v", err)
return err
}
s.Logger.Infof("https server is listening %s", addr)
return s.run(addr, l)
}
// Close stops server s.
func (s *Server) Close() {
for _, app := range s.Apps {
app.Close()
}
if s.Config.GracefulShutdown {
S.Close()
s.l = nil
}
if s.l != nil {
s.l.Close()
s.l = nil
}
}
func (s *Server) IsRunning() bool {
return s.l != nil
}
// SetLogger sets the logger for server s
func (s *Server) SetLogger(logger *log.Logger) {
s.Logger = logger
s.Logger.SetPrefix("[" + s.Name + "] ")
if s.RootApp != nil {
s.RootApp.Logger = s.Logger
}
}
func (s *Server) InitSession() {
if s.SessionManager == nil {
s.SessionManager = httpsession.Default()
}
if s.Config.SessionTimeout > time.Second {
s.SessionManager.SetMaxAge(s.Config.SessionTimeout)
}
s.SessionManager.Run()
if s.RootApp != nil {
s.RootApp.SessionManager = s.SessionManager
}
}
func (s *Server) SetTemplateDir(path string) {
s.RootApp.SetTemplateDir(path)
}
func (s *Server) SetStaticDir(path string) {
s.RootApp.SetStaticDir(path)
}
func (s *Server) App(name string) *App {
path, ok := s.AppsNamePath[name]
if ok {
return s.Apps[path]
}
return nil
}