-
Notifications
You must be signed in to change notification settings - Fork 53
/
web.go
465 lines (431 loc) · 10.7 KB
/
web.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
package znet
import (
"context"
"crypto/tls"
"fmt"
"html/template"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/sohaha/zlsgo/zcli"
"github.com/sohaha/zlsgo/zdi"
"github.com/sohaha/zlsgo/zfile"
"github.com/sohaha/zlsgo/zjson"
"github.com/sohaha/zlsgo/zutil"
"github.com/sohaha/zlsgo/zcache"
"github.com/sohaha/zlsgo/zlog"
"github.com/sohaha/zlsgo/zshell"
"github.com/sohaha/zlsgo/zstring"
)
type (
// Context context
Context struct {
stopHandle *zutil.Bool
rawData string
cacheJSON *zjson.Res
startTime time.Time
middleware []handlerFn
customizeData map[string]interface{}
header map[string][]string
render render
prevData *PrevData
Writer http.ResponseWriter
Request *http.Request
Engine *Engine
Log *zlog.Logger
Cache *zcache.Table
mu sync.RWMutex
cacheQuery url.Values
cacheForm url.Values
injector zdi.Injector
renderError ErrHandlerFunc
}
// Engine is a simple HTTP route multiplexer that parses a request path
Engine struct {
// Log Log
Log *zlog.Logger
// Deprecated: 以后可能移除
Cache *zcache.Table
readTimeout time.Duration
writeTimeout time.Duration
webModeName string
webMode int
ShowFavicon bool
MaxMultipartMemory int64
BindTag string
customMethodType string
addr []addrSt
router *router
preHandler Handler
pool sync.Pool
templateFuncMap template.FuncMap
BindStructDelimiter string
BindStructSuffix string
template *tpl
injector zdi.Injector
}
TlsCfg struct {
Cert string
Key string
HTTPAddr string
HTTPProcessing interface{}
Config *tls.Config
}
tpl struct {
tpl *template.Template
pattern string
templateFuncMap template.FuncMap
}
addrSt struct {
addr string
TlsCfg
}
router struct {
prefix string
middleware []handlerFn
trees map[string]*Tree
parameters Parameters
notFound handlerFn
}
// Handler handler func
Handler interface{}
// HandlerFunc old handler func
HandlerFunc func(c *Context)
handlerFn func(c *Context) error
// MiddlewareFunc Middleware Func
MiddlewareFunc func(c *Context, fn Handler)
// ErrHandlerFunc ErrHandlerFunc
ErrHandlerFunc func(c *Context, err error)
// MiddlewareType is a public type that is used for middleware
MiddlewareType Handler
// Parameters records some parameters
Parameters struct {
routeName string
}
serverMap struct {
engine *Engine
srv *http.Server
}
)
const (
defaultMultipartMemory = 32 << 20 // 32 MB
// DebugMode dev
DebugMode = "dev"
// ProdMode release
ProdMode = "prod"
// TestMode test
TestMode = "test"
// QuietMode quiet
QuietMode = "quiet"
defaultServerName = "Z"
defaultBindTag = "json"
quietCode = -1
prodCode = 0
debugCode = iota
testCode
)
var (
// Log Log
Log = zlog.New(zlog.ColorTextWrap(zlog.ColorGreen, "[Z] "))
Cache = zcache.New("__ZNET__")
// ShutdownDone Shutdown Done executed after shutting down the server
ShutdownDone func()
// CloseHotRestart Close Hot Restart
CloseHotRestart bool
fileMd5 string
zservers = map[string]*Engine{}
defaultAddr = addrSt{
addr: ":3788",
}
// BindStructDelimiter structure route delimiter
BindStructDelimiter = "-"
// BindStructSuffix structure route suffix
BindStructSuffix = ""
)
func init() {
Log.ResetFlags(zlog.BitTime | zlog.BitLevel)
fileMd5, _ = zstring.Md5File(os.Args[0])
}
// New returns a newly initialized Engine object that implements the Engine
func New(serverName ...string) *Engine {
name := defaultServerName
if len(serverName) > 0 {
name = serverName[0]
}
log := zlog.New("[" + name + "] ")
log.ResetFlags(zlog.BitTime | zlog.BitLevel)
log.SetLogLevel(zlog.LogInfo)
route := &router{
prefix: "/",
trees: make(map[string]*Tree),
}
r := &Engine{
Log: log,
Cache: Cache,
MaxMultipartMemory: defaultMultipartMemory,
BindTag: defaultBindTag,
BindStructDelimiter: BindStructDelimiter,
BindStructSuffix: BindStructSuffix,
router: route,
readTimeout: 0 * time.Second,
writeTimeout: 0 * time.Second,
webModeName: ProdMode,
webMode: prodCode,
addr: []addrSt{defaultAddr},
templateFuncMap: template.FuncMap{},
injector: zdi.New(),
}
r.pool.New = func() interface{} {
return r.NewContext(nil, nil)
}
if _, ok := zservers[name]; ok {
Log.Fatal("serverName: [", name, "] it already exists")
}
zservers[name] = r
// r.Use(withRequestLog)
return r
}
// Server Server
func Server(serverName ...string) (engine *Engine, ok bool) {
name := defaultServerName
if len(serverName) > 0 {
name = serverName[0]
}
if engine, ok = zservers[name]; !ok {
Log.Warnf("serverName: %s is not", name)
engine = New(name)
}
return
}
// SetShutdown Set Shutdown Func
func SetShutdown(done func()) {
ShutdownDone = done
}
// SetAddr SetAddr
func (e *Engine) SetAddr(addrString string, tlsConfig ...TlsCfg) {
e.addr = []addrSt{
resolveAddr(addrString, tlsConfig...),
}
}
// AddAddr AddAddr
func (e *Engine) AddAddr(addrString string, tlsConfig ...TlsCfg) {
e.addr = append(e.addr, resolveAddr(addrString, tlsConfig...))
}
// SetCustomMethodField Set Custom Method Field
func (e *Engine) SetCustomMethodField(field string) {
e.customMethodType = field
}
// CloseHotRestartFileMd5 CloseHotRestartFileMd5
func CloseHotRestartFileMd5() {
fileMd5 = ""
}
// SetTemplateFuncMap Set Template Func
func (e *Engine) SetTemplateFuncMap(funcMap template.FuncMap) {
e.templateFuncMap = funcMap
}
// Injector Call Injector
func (e *Engine) Injector() zdi.TypeMapper {
return e.injector
}
// SetHTMLTemplate Set HTML Template
func (e *Engine) SetHTMLTemplate(t *template.Template) {
val := &tpl{
tpl: t,
templateFuncMap: template.FuncMap{},
}
e.template = val
}
// LoadHTMLGlob Load Glob HTML
func (e *Engine) LoadHTMLGlob(pattern string) {
pattern = zfile.RealPath(pattern)
t, err := template.New("").Funcs(e.templateFuncMap).ParseGlob(pattern)
if err != nil {
e.Log.Fatalf("Template loading failed: %s\n", err)
return
}
isDebug := e.IsDebug()
val := &tpl{
pattern: pattern,
tpl: t,
templateFuncMap: template.FuncMap{},
}
if isDebug {
templatesDebug(t)
val.templateFuncMap = e.templateFuncMap
}
e.template = val
}
// SetMode Setting Server Mode
func (e *Engine) SetMode(value string) {
var level int
switch value {
case ProdMode, "":
level = zlog.LogSuccess
e.webMode = prodCode
case QuietMode:
level = zlog.LogPanic
e.webMode = quietCode
case DebugMode:
level = zlog.LogDump
e.webMode = debugCode
case TestMode:
level = zlog.LogInfo
e.webMode = testCode
default:
e.Log.Panic("web mode unknown: " + value)
}
if value == "" {
value = ProdMode
}
e.webModeName = value
e.Log.SetLogLevel(level)
}
// GetMode Get Mode
func (e *Engine) GetMode() string {
switch e.webMode {
case prodCode:
return ProdMode
case quietCode:
return QuietMode
case debugCode:
return DebugMode
case testCode:
return TestMode
default:
return "unknown"
}
}
// IsDebug IsDebug
func (e *Engine) IsDebug() bool {
return e.webMode > prodCode
}
// SetTimeout set Timeout
func (e *Engine) SetTimeout(Timeout time.Duration, WriteTimeout ...time.Duration) {
if len(WriteTimeout) > 0 {
e.writeTimeout = WriteTimeout[0]
e.readTimeout = Timeout
} else {
e.writeTimeout = Timeout
e.readTimeout = Timeout
}
}
func (e *Engine) StartUp() []*serverMap {
var wg sync.WaitGroup
var srvMap sync.Map
for _, cfg := range e.addr {
wg.Add(1)
go func(cfg addrSt, e *Engine) {
var err error
isTls := cfg.Cert != "" || cfg.Config != nil
addr := getAddr(cfg.addr)
hostname := getHostname(addr, isTls)
srv := &http.Server{
Addr: addr,
Handler: e,
ReadTimeout: e.readTimeout,
WriteTimeout: e.writeTimeout,
// MaxHeaderBytes: 1 << 20,
}
srvMap.Store(addr, &serverMap{e, srv})
time.AfterFunc(time.Millisecond*100, func() {
wrapPid := e.Log.ColorTextWrap(zlog.ColorLightGrey, fmt.Sprintf("Pid: %d", os.Getpid()))
wrapMode := ""
if e.webMode > 0 {
wrapMode = e.Log.ColorTextWrap(zlog.ColorYellow, fmt.Sprintf("%s ", strings.ToUpper(e.webModeName)))
}
e.Log.Successf("%s %s %s%s\n", "Listen:", e.Log.ColorTextWrap(zlog.ColorLightGreen, e.Log.OpTextWrap(zlog.OpBold, hostname)), wrapMode, wrapPid)
})
wg.Done()
if isTls {
if cfg.Config != nil {
srv.TLSConfig = cfg.Config
}
if cfg.HTTPAddr != "" {
httpAddr := getAddr(cfg.HTTPAddr)
go func(e *Engine) {
newHostname := "http://" + resolveHostname(httpAddr)
e.Log.Success(e.Log.ColorBackgroundWrap(zlog.ColorYellow, zlog.ColorDefault, e.Log.OpTextWrap(zlog.OpBold, "Listen: "+newHostname)))
var err error
switch processing := cfg.HTTPProcessing.(type) {
case string:
err = http.ListenAndServe(httpAddr, &tlsRedirectHandler{Domain: processing})
case http.Handler:
err = http.ListenAndServe(httpAddr, processing)
default:
err = http.ListenAndServe(httpAddr, e)
}
e.Log.Errorf("HTTP Listen: %s\n", err)
}(e)
}
err = srv.ListenAndServeTLS(cfg.Cert, cfg.Key)
} else {
err = srv.ListenAndServe()
}
if err != nil && err != http.ErrServerClosed {
e.Log.Fatalf("Listen: %s\n", err)
} else if err != http.ErrServerClosed {
e.Log.Info(err)
}
}(cfg, e)
}
wg.Wait()
srvs := make([]*serverMap, 0)
srvMap.Range(func(addr, value interface{}) bool {
srvs = append(srvs, value.(*serverMap))
return true
})
return srvs
}
// Run run serve
func Run() {
var (
srvs []*serverMap
m sync.WaitGroup
)
for _, e := range zservers {
ss := e.StartUp()
m.Add(len(ss))
srvs = append(srvs, ss...)
}
sigkill := zcli.KillSignal()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if !sigkill && !CloseHotRestart {
runNewProcess()
}
for _, s := range srvs {
r := s.engine
if sigkill {
r.Log.Info("Shutdown server ...")
}
err := s.srv.Shutdown(ctx)
if err != nil {
if sigkill {
r.Log.Error("Timeout forced close")
}
_ = s.srv.Close()
} else {
if sigkill {
r.Log.Success("Shutdown server done")
}
}
m.Done()
}
m.Wait()
if ShutdownDone != nil {
ShutdownDone()
}
time.Sleep(100 * time.Millisecond)
}
func runNewProcess() {
if fileMd5 == "" {
Log.Warn("ignore execution file md5 check")
}
_, err := zshell.RunNewProcess(fileMd5)
if err != nil {
Log.Error(err)
}
}