-
Notifications
You must be signed in to change notification settings - Fork 180
/
Copy pathserver.go
607 lines (526 loc) · 21.8 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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
package dotweb
import (
"compress/gzip"
"github.com/devfeel/dotweb/logger"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/devfeel/dotweb/core"
"github.com/devfeel/dotweb/session"
"strconv"
"github.com/devfeel/dotweb/config"
"github.com/devfeel/dotweb/framework/file"
jsonutil "github.com/devfeel/dotweb/framework/json"
)
const (
DefaultGzipLevel = 9
gzipScheme = "gzip"
DefaultIndexPage = "index.html"
)
type (
HttpServer struct {
stdServer *http.Server
router Router
groups []Group
Modules []*HttpModule
DotApp *DotWeb
Validator Validator
sessionManager *session.SessionManager
lock_session *sync.RWMutex
pool *pool
contextCreater ContextCreater
binder Binder
render Renderer
offline bool
}
pool struct {
request sync.Pool
response sync.Pool
context sync.Pool
}
ContextCreater func() Context
)
func NewHttpServer() *HttpServer {
server := &HttpServer{
Modules: make([]*HttpModule, 0),
lock_session: new(sync.RWMutex),
binder: newBinder(),
contextCreater: defaultContextCreater,
}
server.pool = &pool{
response: sync.Pool{
New: func() interface{} {
return &Response{}
},
},
request: sync.Pool{
New: func() interface{} {
return &Request{}
},
},
context: sync.Pool{
New: func() interface{} {
return server.contextCreater()
},
},
}
// setup router
server.router = NewRouter(server)
server.stdServer = &http.Server{Handler: server}
return server
}
// initConfig init config from app config
func (server *HttpServer) initConfig(config *config.Config) {
if config.Server.WriteTimeout > 0 {
server.stdServer.WriteTimeout = time.Duration(config.Server.WriteTimeout) * time.Millisecond
}
if config.Server.ReadTimeout > 0 {
server.stdServer.ReadTimeout = time.Duration(config.Server.ReadTimeout) * time.Millisecond
}
if config.Server.ReadHeaderTimeout > 0 {
server.stdServer.ReadHeaderTimeout = time.Duration(config.Server.ReadHeaderTimeout) * time.Millisecond
}
if config.Server.IdleTimeout > 0 {
server.stdServer.IdleTimeout = time.Duration(config.Server.IdleTimeout) * time.Millisecond
}
}
// ServerConfig a shortcut for App.Config.ServerConfig
func (server *HttpServer) ServerConfig() *config.ServerNode {
return server.DotApp.Config.Server
}
// SessionConfig a shortcut for App.Config.SessionConfig
func (server *HttpServer) SessionConfig() *config.SessionNode {
return server.DotApp.Config.Session
}
// SetBinder set custom Binder on HttpServer
func (server *HttpServer) SetBinder(binder Binder) {
server.binder = binder
}
// SetContextCreater
func (server *HttpServer) SetContextCreater(creater ContextCreater) {
server.contextCreater = creater
server.pool.context = sync.Pool{
New: func() interface{} {
return server.contextCreater()
},
}
server.DotApp.Logger().Debug("DotWeb:HttpServer SetContextCreater()", LogTarget_HttpServer)
}
// ListenAndServe listens on the TCP network address srv.Addr and then
// calls Serve to handle requests on incoming connections.
func (server *HttpServer) ListenAndServe(addr string) error {
server.stdServer.Addr = addr
server.DotApp.Logger().Debug("DotWeb:HttpServer ListenAndServe ["+addr+"]", LogTarget_HttpServer)
return server.stdServer.ListenAndServe()
}
// ListenAndServeTLS listens on the TCP network address srv.Addr and
// then calls Serve to handle requests on incoming TLS connections.
// Accepted connections are configured to enable TCP keep-alives.
//
// Filenames containing a certificate and matching private key for the
// server must be provided if neither the Server's TLSConfig.Certificates
// nor TLSConfig.GetCertificate are populated. If the certificate is
// signed by a certificate authority, the certFile should be the
// concatenation of the server's certificate, any intermediates, and
// the CA's certificate.
//
// If srv.Addr is blank, ":https" is used.
//
// ListenAndServeTLS always returns a non-nil error.
func (server *HttpServer) ListenAndServeTLS(addr string, certFile, keyFile string) error {
server.stdServer.Addr = addr
// check tls config
if !file.Exist(certFile) {
server.DotApp.Logger().Error("DotWeb:HttpServer ListenAndServeTLS ["+addr+","+certFile+","+keyFile+"] error => Server EnabledTLS is true, but TLSCertFile not exists", LogTarget_HttpServer)
panic("Server EnabledTLS is true, but TLSCertFile not exists")
}
if !file.Exist(keyFile) {
server.DotApp.Logger().Error("DotWeb:HttpServer ListenAndServeTLS ["+addr+","+certFile+","+keyFile+"] error => Server EnabledTLS is true, but TLSKeyFile not exists", LogTarget_HttpServer)
panic("Server EnabledTLS is true, but TLSKeyFile not exists")
}
server.DotApp.Logger().Debug("DotWeb:HttpServer ListenAndServeTLS ["+addr+","+certFile+","+keyFile+"]", LogTarget_HttpServer)
return server.stdServer.ListenAndServeTLS(certFile, keyFile)
}
// ServeHTTP make sure request can be handled correctly
func (server *HttpServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
server.StateInfo().AddCurrentRequest(1)
defer server.StateInfo().SubCurrentRequest(1)
// special handling for websocket and debugging
if checkIsWebSocketRequest(req) {
http.DefaultServeMux.ServeHTTP(w, req)
server.StateInfo().AddRequestCount(req.URL.Path, defaultHttpCode, 1)
} else {
// setup header
w.Header().Set(HeaderServer, DefaultServerName)
httpCtx := prepareHttpContext(server, w, req)
// process OnBeginRequest of modules
for _, module := range server.Modules {
if module.OnBeginRequest != nil {
module.OnBeginRequest(httpCtx)
}
}
if !httpCtx.IsEnd() {
server.Router().ServeHTTP(httpCtx)
}
// process OnEndRequest of modules
for _, module := range server.Modules {
if module.OnEndRequest != nil {
module.OnEndRequest(httpCtx)
}
}
server.StateInfo().AddRequestCount(httpCtx.Request().Path(), httpCtx.Response().HttpCode(), 1)
releaseHttpContext(server, httpCtx)
}
}
// IsOffline check server is set offline state
func (server *HttpServer) IsOffline() bool {
return server.offline
}
// SetVirtualPath set current server's VirtualPath
func (server *HttpServer) SetVirtualPath(path string) {
server.ServerConfig().VirtualPath = path
server.DotApp.Logger().Debug("DotWeb:HttpServer SetVirtualPath ["+path+"]", LogTarget_HttpServer)
}
// VirtualPath return current server's VirtualPath
func (server *HttpServer) VirtualPath() string {
return server.ServerConfig().VirtualPath
}
// SetOffline set server offline config
func (server *HttpServer) SetOffline(offline bool, offlineText string, offlineUrl string) {
server.offline = offline
server.DotApp.Logger().Debug("DotWeb:HttpServer SetOffline ["+strconv.FormatBool(offline)+", "+offlineText+", "+offlineUrl+"]", LogTarget_HttpServer)
}
// IndexPage default index page name
func (server *HttpServer) IndexPage() string {
if server.ServerConfig().IndexPage == "" {
return DefaultIndexPage
} else {
return server.ServerConfig().IndexPage
}
}
// SetIndexPage set default index page name
func (server *HttpServer) SetIndexPage(indexPage string) {
server.ServerConfig().IndexPage = indexPage
server.DotApp.Logger().Debug("DotWeb:HttpServer SetIndexPage ["+indexPage+"]", LogTarget_HttpServer)
}
// SetSessionConfig set session store config
func (server *HttpServer) SetSessionConfig(storeConfig *session.StoreConfig) {
// sync session config
server.SessionConfig().Timeout = storeConfig.Maxlifetime
server.SessionConfig().SessionMode = storeConfig.StoreName
server.SessionConfig().ServerIP = storeConfig.ServerIP
server.SessionConfig().BackupServerUrl = storeConfig.BackupServerUrl
server.SessionConfig().StoreKeyPre = storeConfig.StoreKeyPre
server.SessionConfig().CookieName = storeConfig.CookieName
server.SessionConfig().MaxIdle = storeConfig.MaxIdle
server.SessionConfig().MaxActive = storeConfig.MaxActive
server.DotApp.Logger().Debug("DotWeb:HttpServer SetSessionConfig ["+jsonutil.GetJsonString(storeConfig)+"]", LogTarget_HttpServer)
}
// InitSessionManager init session manager
func (server *HttpServer) InitSessionManager() {
storeConfig := new(session.StoreConfig)
storeConfig.Maxlifetime = server.SessionConfig().Timeout
storeConfig.StoreName = server.SessionConfig().SessionMode
storeConfig.ServerIP = server.SessionConfig().ServerIP
storeConfig.BackupServerUrl = server.SessionConfig().BackupServerUrl
storeConfig.StoreKeyPre = server.SessionConfig().StoreKeyPre
storeConfig.MaxIdle = server.SessionConfig().MaxIdle
storeConfig.MaxActive = server.SessionConfig().MaxActive
storeConfig.CookieName = server.SessionConfig().CookieName
if server.sessionManager == nil {
// setup session
server.lock_session.Lock()
if manager, err := session.NewDefaultSessionManager(server.Logger(), storeConfig); err != nil {
// panic error with create session manager
panic(err.Error())
} else {
server.sessionManager = manager
}
server.lock_session.Unlock()
}
server.Logger().Debug("DotWeb:HttpServer InitSessionManager ["+jsonutil.GetJsonString(storeConfig)+"]", LogTarget_HttpServer)
}
// setDotApp associates the dotApp to the current HttpServer
func (server *HttpServer) setDotApp(dotApp *DotWeb) {
server.DotApp = dotApp
}
// GetSessionManager get session manager in current httpserver
func (server *HttpServer) GetSessionManager() *session.SessionManager {
if !server.SessionConfig().EnabledSession {
return nil
}
return server.sessionManager
}
// Logger is a shortcut for dotweb.Logger
func (server *HttpServer) Logger() logger.AppLog {
return server.DotApp.Logger()
}
// StateInfo is a shortcut for dotweb.StateInfo
func (server *HttpServer) StateInfo() *core.ServerStateInfo {
return server.DotApp.serverStateInfo
}
// Router get router interface in server
func (server *HttpServer) Router() Router {
return server.router
}
// GET is a shortcut for router.Handle("GET", path, handle)
func (server *HttpServer) GET(path string, handle HttpHandle) RouterNode {
return server.Router().GET(path, handle)
}
// ANY is a shortcut for router.Handle("Any", path, handle)
// it support GET\HEAD\POST\PUT\PATCH\OPTIONS\DELETE
func (server *HttpServer) Any(path string, handle HttpHandle) {
server.Router().Any(path, handle)
}
// HEAD is a shortcut for router.Handle("HEAD", path, handle)
func (server *HttpServer) HEAD(path string, handle HttpHandle) RouterNode {
return server.Router().HEAD(path, handle)
}
// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
func (server *HttpServer) OPTIONS(path string, handle HttpHandle) RouterNode {
return server.Router().OPTIONS(path, handle)
}
// POST is a shortcut for router.Handle("POST", path, handle)
func (server *HttpServer) POST(path string, handle HttpHandle) RouterNode {
return server.Router().POST(path, handle)
}
// PUT is a shortcut for router.Handle("PUT", path, handle)
func (server *HttpServer) PUT(path string, handle HttpHandle) RouterNode {
return server.Router().PUT(path, handle)
}
// PATCH is a shortcut for router.Handle("PATCH", path, handle)
func (server *HttpServer) PATCH(path string, handle HttpHandle) RouterNode {
return server.Router().PATCH(path, handle)
}
// DELETE is a shortcut for router.Handle("DELETE", path, handle)
func (server *HttpServer) DELETE(path string, handle HttpHandle) RouterNode {
return server.Router().DELETE(path, handle)
}
// ServerFile a shortcut for router.ServeFiles(path, fileRoot)
// simple demo:server.ServerFile("/src/*filepath", "/var/www")
func (server *HttpServer) ServerFile(path string, fileRoot string) RouterNode {
return server.Router().ServerFile(path, fileRoot)
}
// RegisterHandlerFunc a shortcut for router.RegisterHandlerFunc(routeMethod string, path string, handler http.HandlerFunc)
func (server *HttpServer) RegisterHandlerFunc(routeMethod string, path string, handler http.HandlerFunc) RouterNode {
return server.Router().RegisterHandlerFunc(routeMethod, path, handler)
}
// RegisterRoute a shortcut for router.RegisterRoute(routeMethod string, path string,handle HttpHandle)
func (server *HttpServer) RegisterRoute(routeMethod string, path string, handle HttpHandle) RouterNode {
return server.Router().RegisterRoute(routeMethod, path, handle)
}
// RegisterServerFile a shortcut for router.RegisterServerFile(routeMethod, path, fileRoot)
// simple demo:server.RegisterServerFile(RouteMethod_GET, "/src/*", "/var/www", nil)
// simple demo:server.RegisterServerFile(RouteMethod_GET, "/src/*filepath", "/var/www", []string{".zip", ".rar"})
func (server *HttpServer) RegisterServerFile(routeMethod string, path string, fileRoot string, excludeExtension []string) RouterNode {
return server.Router().RegisterServerFile(routeMethod, path, fileRoot, excludeExtension)
}
// HiJack is a shortcut for router.HiJack(path, handle)
func (server *HttpServer) HiJack(path string, handle HttpHandle) {
server.Router().HiJack(path, handle)
}
// WebSocket is a shortcut for router.WebSocket(path, handle)
func (server *HttpServer) WebSocket(path string, handle HttpHandle) {
server.Router().WebSocket(path, handle)
}
// Group create new group with current HttpServer
func (server *HttpServer) Group(prefix string) Group {
return NewGroup(prefix, server)
}
// Binder get binder interface in server
func (server *HttpServer) Binder() Binder {
return server.binder
}
// Renderer get renderer interface in server
// if no set, init InnerRenderer
func (server *HttpServer) Renderer() Renderer {
if server.render == nil {
if server.DotApp.RunMode() == RunMode_Development {
server.SetRenderer(NewInnerRendererNoCache())
} else {
server.SetRenderer(NewInnerRenderer())
}
}
return server.render
}
// SetRenderer set custom renderer in server
func (server *HttpServer) SetRenderer(r Renderer) {
server.render = r
server.Logger().Debug("DotWeb:HttpServer SetRenderer", LogTarget_HttpServer)
}
// SetEnabledAutoHEAD set route use auto head
// set EnabledAutoHEAD true or false
// default is false
func (server *HttpServer) SetEnabledAutoHEAD(isEnabled bool) {
server.ServerConfig().EnabledAutoHEAD = isEnabled
server.Logger().Debug("DotWeb:HttpServer SetEnabledAutoHEAD ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer)
}
// SetEnabledAutoOPTIONS set route use auto options
// set SetEnabledAutoOPTIONS true or false
// default is false
func (server *HttpServer) SetEnabledAutoOPTIONS(isEnabled bool) {
server.ServerConfig().EnabledAutoOPTIONS = isEnabled
server.Logger().Debug("DotWeb:HttpServer SetEnabledAutoOPTIONS ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer)
}
// SetEnabledRequestID set create unique request id per request
// set EnabledRequestID true or false
// default is false
func (server *HttpServer) SetEnabledRequestID(isEnabled bool) {
server.ServerConfig().EnabledRequestID = isEnabled
server.Logger().Debug("DotWeb:HttpServer SetEnabledRequestID ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer)
}
// SetEnabledListDir set whether to allow listing of directories, default is false
func (server *HttpServer) SetEnabledListDir(isEnabled bool) {
server.ServerConfig().EnabledListDir = isEnabled
server.DotApp.Logger().Debug("DotWeb:HttpServer SetEnabledListDir ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer)
}
// SetEnabledSession set whether to enable session, default is false
func (server *HttpServer) SetEnabledSession(isEnabled bool) {
server.SessionConfig().EnabledSession = isEnabled
server.Logger().Debug("DotWeb:HttpServer SetEnabledSession ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer)
}
// SetEnabledGzip set whether to enable gzip, default is false
func (server *HttpServer) SetEnabledGzip(isEnabled bool) {
server.ServerConfig().EnabledGzip = isEnabled
server.Logger().Debug("DotWeb:HttpServer SetEnabledGzip ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer)
}
// SetEnabledBindUseJsonTag set whethr to enable json tab on Bind, default is false
func (server *HttpServer) SetEnabledBindUseJsonTag(isEnabled bool) {
server.ServerConfig().EnabledBindUseJsonTag = isEnabled
server.Logger().Debug("DotWeb:HttpServer SetEnabledBindUseJsonTag ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer)
}
// SetEnabledIgnoreFavicon set IgnoreFavicon Enabled
// default is false
func (server *HttpServer) SetEnabledIgnoreFavicon(isEnabled bool) {
server.ServerConfig().EnabledIgnoreFavicon = isEnabled
server.Logger().Debug("DotWeb:HttpServer SetEnabledIgnoreFavicon ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer)
server.RegisterModule(getIgnoreFaviconModule())
}
// SetEnabledTLS set tls enabled
// default is false
// if it's true, must input certificate\private key fileName
func (server *HttpServer) SetEnabledTLS(isEnabled bool, certFile, keyFile string) {
server.ServerConfig().EnabledTLS = isEnabled
server.ServerConfig().TLSCertFile = certFile
server.ServerConfig().TLSKeyFile = keyFile
server.Logger().Debug("DotWeb:HttpServer SetEnabledTLS ["+strconv.FormatBool(isEnabled)+","+certFile+","+keyFile+"]", LogTarget_HttpServer)
}
// SetEnabledDetailRequestData 设置是否启用详细请求数据统计,默认为false
func (server *HttpServer) SetEnabledDetailRequestData(isEnabled bool) {
server.ServerConfig().EnabledDetailRequestData = isEnabled
server.Logger().Debug("DotWeb:HttpServer SetEnabledDetailRequestData ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer)
}
// SetEnabledStaticFileMiddleware set flag which enabled or disabled middleware for static-file route
func (server *HttpServer) SetEnabledStaticFileMiddleware(isEnabled bool) {
server.ServerConfig().EnabledStaticFileMiddleware = isEnabled
server.Logger().Debug("DotWeb:HttpServer SetEnabledStaticFileMiddleware ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer)
}
// SetReadTimeout To limit the request's body size to be read with Millisecond
func (server *HttpServer) SetReadTimeout(readTimeout int64) {
server.ServerConfig().ReadTimeout = readTimeout
server.Logger().Debug("DotWeb:HttpServer SetReadTimeout ["+strconv.FormatInt(readTimeout, 10)+"]", LogTarget_HttpServer)
}
// SetReadHeaderTimeout ReadHeaderTimeout is the amount of time allowed to read request headers with Millisecond
func (server *HttpServer) SetReadHeaderTimeout(readHeaderTimeout int64) {
server.ServerConfig().ReadHeaderTimeout = readHeaderTimeout
server.Logger().Debug("DotWeb:HttpServer SetReadHeaderTimeout ["+strconv.FormatInt(readHeaderTimeout, 10)+"]", LogTarget_HttpServer)
}
// SetIdleTimeout IdleTimeout is the maximum amount of time to wait for the next request when keep-alives are enabled with Millisecond
func (server *HttpServer) SetIdleTimeout(idleTimeout int64) {
server.ServerConfig().IdleTimeout = idleTimeout
server.Logger().Debug("DotWeb:HttpServer SetIdleTimeout ["+strconv.FormatInt(idleTimeout, 10)+"]", LogTarget_HttpServer)
}
// SetWriteTimeout WriteTimeout is the maximum duration before timing out
// writes of the response with Millisecond
func (server *HttpServer) SetWriteTimeout(writeTimeout int64) {
server.ServerConfig().WriteTimeout = writeTimeout
server.Logger().Debug("DotWeb:HttpServer SetWriteTimeout ["+strconv.FormatInt(writeTimeout, 10)+"]", LogTarget_HttpServer)
}
// SetMaxBodySize set body size to limit read
func (server *HttpServer) SetMaxBodySize(maxBodySize int64) {
server.ServerConfig().MaxBodySize = maxBodySize
server.Logger().Debug("DotWeb:HttpServer SetMaxBodySize ["+strconv.FormatInt(maxBodySize, 10)+"]", LogTarget_HttpServer)
}
// RegisterModule add HttpModule
func (server *HttpServer) RegisterModule(module *HttpModule) {
server.Modules = append(server.Modules, module)
server.Logger().Debug("DotWeb:HttpServer RegisterModule ["+module.Name+"]", LogTarget_HttpServer)
}
type LogJson struct {
RequestUrl string
HttpHeader string
HttpBody string
}
// check request is the websocket request
// check Connection contains upgrade
func checkIsWebSocketRequest(req *http.Request) bool {
if strings.Contains(strings.ToLower(req.Header.Get("Connection")), "upgrade") {
return true
}
return false
}
// check request is startwith /debug/
func checkIsDebugRequest(req *http.Request) bool {
if strings.Index(req.RequestURI, "/debug/") == 0 {
return true
}
return false
}
// prepareHttpContext init HttpContext, init session & gzip config on HttpContext
func prepareHttpContext(server *HttpServer, w http.ResponseWriter, req *http.Request) Context {
// get from pool
response := server.pool.response.Get().(*Response)
request := server.pool.request.Get().(*Request)
httpCtx := server.pool.context.Get().(Context)
httpCtx.reset(response, request, server, nil, nil, nil)
response.reset(w)
request.reset(req, httpCtx)
// session
// if exists client-sessionid, use it
// if not exists client-sessionid, new one
if httpCtx.HttpServer().SessionConfig().EnabledSession {
sessionId, err := httpCtx.HttpServer().GetSessionManager().GetClientSessionID(httpCtx.Request().Request)
if err == nil && sessionId != "" {
httpCtx.setSessionID(sessionId)
} else {
httpCtx.setSessionID(httpCtx.HttpServer().GetSessionManager().NewSessionID())
cookie := &http.Cookie{
Name: httpCtx.HttpServer().sessionManager.StoreConfig().CookieName,
Value: url.QueryEscape(httpCtx.SessionID()),
Path: "/",
}
httpCtx.SetCookie(cookie)
}
}
// init gzip
if httpCtx.HttpServer().ServerConfig().EnabledGzip {
gw, err := gzip.NewWriterLevel(httpCtx.Response().Writer(), DefaultGzipLevel)
if err != nil {
panic("use gzip error -> " + err.Error())
}
grw := &gzipResponseWriter{Writer: gw, ResponseWriter: httpCtx.Response().Writer()}
httpCtx.Response().reset(grw)
httpCtx.Response().SetHeader(HeaderContentEncoding, gzipScheme)
}
return httpCtx
}
// releaseHttpContext release HttpContext, release gzip writer
func releaseHttpContext(server *HttpServer, httpCtx Context) {
if server.ServerConfig().EnabledGzip {
var w io.Writer
w = httpCtx.Response().Writer().(*gzipResponseWriter).Writer
w.(*gzip.Writer).Close()
}
// release response
httpCtx.Response().release()
server.pool.response.Put(httpCtx.Response())
// release request
httpCtx.Request().release()
server.pool.request.Put(httpCtx.Request())
// release context
httpCtx.release()
server.pool.context.Put(httpCtx)
}