-
Notifications
You must be signed in to change notification settings - Fork 250
/
faygo.go
577 lines (508 loc) · 16.2 KB
/
faygo.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
// Copyright 2022 AndeyaLee. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package faygo
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"reflect"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/andeya/faygo/acceptencoder"
"github.com/andeya/faygo/apiware"
"github.com/andeya/faygo/logging"
)
const (
// VERSION is faygo web framework's version
VERSION = "1.2.0"
banner = `
___
/ _/
_| |_ __ __ ___
/_ // _ |/\ /\/ _ \/ _ \
| | \/ /\ \/ / |/ / |/ /
/ / \_/\\ \ / \_ / \__/
/ / / / _\ \
\_/ \_/ \_\_/ VERSION ` + VERSION + " URL https://github.com/andeya/faygo\n"
)
// New uses the faygo web framework to create a new application.
func New(name string, version ...string) *Framework {
return newFramework(nil, name, version)
}
// NewWithConfig uses the faygo web framework to create a new application.
func NewWithConfig(config *Config, name string, version ...string) *Framework {
return newFramework(config, name, version)
}
// AllFrames returns the list of applications that have been created.
func AllFrames() []*Framework {
global.framesLock.RLock()
defer global.framesLock.RUnlock()
return global.frames
}
// GetFrame returns the specified frame instance by name and version.
func GetFrame(name string, version ...string) (*Framework, bool) {
if len(version) > 0 && len(version[0]) > 0 {
name = name + "_" + version[0]
}
global.framesLock.RLock()
defer global.framesLock.RUnlock()
for _, frame := range global.frames {
if frame.NameWithVersion() == name {
return frame, true
}
}
return nil, false
}
// Run starts all web services.
func Run() {
global.beforeRun()
global.framesLock.Lock()
for _, frame := range global.frames {
if !frame.Running() {
go frame.run()
time.Sleep(time.Second)
}
}
global.framesLock.Unlock()
select {}
}
// Running returns whether the frame service is running.
func Running(name string, version ...string) bool {
frame, ok := GetFrame(name, version...)
if !ok {
return false
}
return frame.Running()
}
// MinShutdownTimeout the default time-out period for the services shutdown.
const MinShutdownTimeout = 5 * time.Second
// SetShutdown sets the function which is called after the services shutdown,
// and the time-out period for the services shutdown.
// If 0<=timeout<5s, automatically use 'MinShutdownTimeout'(5s).
// If timeout<0, indefinite period.
// 'preCloseFunc' is executed before closing services, but not guaranteed to be completed.
// 'postCloseFunc' is executed after services are closed, but not guaranteed to be completed.
func SetShutdown(timeout time.Duration, preCloseFunc, postCloseFunc func() error) {
if timeout < 0 {
global.shutdownTimeout = 1<<63 - 1
} else if timeout < MinShutdownTimeout {
global.shutdownTimeout = MinShutdownTimeout
} else {
global.shutdownTimeout = timeout
}
global.preCloseFunc = preCloseFunc
global.postCloseFunc = postCloseFunc
}
// Shutdown closes all the frame services gracefully.
// Parameter timeout is used to reset time-out period for the services shutdown.
func Shutdown(timeout ...time.Duration) {
global.framesLock.Lock()
defer global.framesLock.Unlock()
defer CloseLog()
Print("\x1b[46m[SYS]\x1b[0m shutting down services...")
contextExec(timeout, "shutdown", func(ctxTimeout context.Context) <-chan struct{} {
endCh := make(chan struct{})
go func() {
defer close(endCh)
var graceful = true
if global.preCloseFunc != nil {
if err := global.preCloseFunc(); err != nil {
Errorf("[shutdown-preClose] %s", err.Error())
graceful = false
}
}
graceful = shutdown(ctxTimeout, "shutdown") && graceful
if graceful {
Print("\x1b[46m[SYS]\x1b[0m services are shutted down gracefully!")
} else {
Print("\x1b[46m[SYS]\x1b[0m services are shutted down, but not gracefully!")
}
}()
return endCh
})
}
func contextExec(timeout []time.Duration, action string, deferCallback func(ctxTimeout context.Context) <-chan struct{}) {
if len(timeout) > 0 {
SetShutdown(timeout[0], global.preCloseFunc, global.postCloseFunc)
}
ctxTimeout, _ := context.WithTimeout(context.Background(), global.shutdownTimeout)
select {
case <-ctxTimeout.Done():
if err := ctxTimeout.Err(); err != nil {
Errorf("[%s-timeout] %s", action, err.Error())
}
case <-deferCallback(ctxTimeout):
}
}
func shutdown(ctxTimeout context.Context, action string) bool {
var flag int32 = 1
count := new(sync.WaitGroup)
for _, frame := range global.frames {
count.Add(1)
go func(fm *Framework) {
graceful := fm.shutdown(ctxTimeout)
if !graceful {
atomic.StoreInt32(&flag, 0)
}
count.Done()
}(frame)
}
count.Wait()
if global.postCloseFunc != nil {
if err := global.postCloseFunc(); err != nil {
atomic.StoreInt32(&flag, 0)
Errorf("[%s-postClose] %s", action, err.Error())
}
}
return flag == 1
}
// HandleError calls the default error handler.
func HandleError(ctx *Context, errStr string, status int) {
global.errorFunc(ctx, errStr, status)
}
// SetErrorFunc sets the global default `ErrorFunc` function.
func SetErrorFunc(errorFunc ErrorFunc) {
if errorFunc == nil {
global.errorFunc = defaultErrorFunc
} else {
global.errorFunc = errorFunc
}
}
// DecodeBody decodes params from request body.
func DecodeBody(dest reflect.Value, body []byte) error {
return global.bodydecoder(dest, body)
}
// SetBodydecoder sets the global default `Bodydecoder` function.
func SetBodydecoder(bodydecoder apiware.Bodydecoder) {
if bodydecoder == nil {
global.bodydecoder = defaultBodydecoder
} else {
global.bodydecoder = bodydecoder
}
}
// HandleBinderror calls the default parameter binding failure handler.
func HandleBinderror(ctx *Context, err error) {
global.binderrorFunc(ctx, err)
}
// SetBinderrorFunc sets the global default `BinderrorFunc` function.
func SetBinderrorFunc(binderrorFunc BinderrorFunc) {
if binderrorFunc == nil {
global.binderrorFunc = defaultBinderrorFunc
} else {
global.binderrorFunc = binderrorFunc
}
}
// MapParamName maps the APIHander's parameter name from the structure field.
// When the APIHander's parameter name (struct tag) is unsetted,
// it is mapped from the structure field name by default.
// If `paramNameMapper` is nil, use snake style.
func MapParamName(fieldName string) (paramName string) {
return global.paramNameMapper(fieldName)
}
// SetParamNameMapper sets the global default `ParamNameMapper` function.
func SetParamNameMapper(paramNameMapper apiware.ParamNameMapper) {
if paramNameMapper == nil {
global.paramNameMapper = defaultParamNameMapper
} else {
global.paramNameMapper = paramNameMapper
}
}
// GetRender returns a custom faygo template renderer using pongo2.
func GetRender() *Render {
return global.render
}
// RenderVar sets the global template variable, function or pongo2.FilterFunction for pongo2 render.
func RenderVar(name string, v interface{}) {
global.render.TemplateVar(name, v)
}
// LogDir returns logs folder path with a slash at the end
func LogDir() string {
return global.logDir
}
// SetUpload sets upload folder path such as `./upload/`
// with a slash `/` at the end.
// note: it should be called before Run()
func SetUpload(dir string, nocompress bool, nocache bool, handlers ...Handler) {
if !strings.HasSuffix(dir, "/") {
dir += "/"
}
global.upload = PresetStatic{
root: dir,
nocompress: nocompress,
nocache: nocache,
handlers: handlers,
}
}
// UploadDir returns upload folder path with a slash at the end
func UploadDir() string {
return global.upload.root
}
// SetStatic sets static folder path, such as `./staic/`
// with a slash `/` at the end.
// note: it should be called before Run()
func SetStatic(dir string, nocompress bool, nocache bool, handlers ...Handler) {
if !strings.HasSuffix(dir, "/") {
dir += "/"
}
global.static = PresetStatic{
root: dir,
nocompress: nocompress,
nocache: nocache,
handlers: handlers,
}
}
// StaticDir returns static folder path with a slash at the end
func StaticDir() string {
return global.static.root
}
// CloseLog closes global loggers.
func CloseLog() {
global.bizlog.Close()
global.syslog.Close()
}
// Fatal is equivalent to l.Critical(fmt.Sprint()) followed by a call to os.Exit(1).
func Fatal(args ...interface{}) {
global.bizlog.Fatal(args...)
}
// Fatalf is equivalent to l.Critical followed by a call to os.Exit(1).
func Fatalf(format string, args ...interface{}) {
global.bizlog.Fatalf(format, args...)
}
// Panic is equivalent to l.Critical(fmt.Sprint()) followed by a call to panic().
func Panic(args ...interface{}) {
global.bizlog.Panic(args...)
}
// Panicf is equivalent to l.Critical followed by a call to panic().
func Panicf(format string, args ...interface{}) {
global.bizlog.Panicf(format, args...)
}
// Critical logs a message using CRITICAL as log level.
func Critical(args ...interface{}) {
global.bizlog.Critical(args...)
}
// Criticalf logs a message using CRITICAL as log level.
func Criticalf(format string, args ...interface{}) {
global.bizlog.Criticalf(format, args...)
}
// Error logs a message using ERROR as log level.
func Error(args ...interface{}) {
global.bizlog.Error(args...)
}
// Errorf logs a message using ERROR as log level.
func Errorf(format string, args ...interface{}) {
global.bizlog.Errorf(format, args...)
}
// Warning logs a message using WARNING as log level.
func Warning(args ...interface{}) {
global.bizlog.Warning(args...)
}
// Warningf logs a message using WARNING as log level.
func Warningf(format string, args ...interface{}) {
global.bizlog.Warningf(format, args...)
}
// Notice logs a message using NOTICE as log level.
func Notice(args ...interface{}) {
global.bizlog.Notice(args...)
}
// Noticef logs a message using NOTICE as log level.
func Noticef(format string, args ...interface{}) {
global.bizlog.Noticef(format, args...)
}
// Info logs a message using INFO as log level.
func Info(args ...interface{}) {
global.bizlog.Info(args...)
}
// Infof logs a message using INFO as log level.
func Infof(format string, args ...interface{}) {
global.bizlog.Infof(format, args...)
}
// Debug logs a message using DEBUG as log level.
func Debug(args ...interface{}) {
global.bizlog.Debug(args...)
}
// Debugf logs a message using DEBUG as log level.
func Debugf(format string, args ...interface{}) {
global.bizlog.Debugf(format, args...)
}
// Print logs a message using CRITICAL as log level, only with time prefix.
func Print(args ...interface{}) {
global.syslog.Critical(args...)
}
// Printf logs a message using CRITICAL as log level, only with time prefix.
func Printf(format string, args ...interface{}) {
global.syslog.Criticalf(format, args...)
}
type (
// GlobalVariables defines the global frames, configuration, function and so on.
GlobalVariables struct {
// the list of applications that have been created.
frames []*Framework
framesLock sync.RWMutex
// global config
config GlobalConfig
// Error replies to the request with the specified error message and HTTP code.
// It does not otherwise end the request; the caller should ensure no further
// writes are done to response.
// The error message should be plain text.
errorFunc ErrorFunc
// The following is only for the APIHandler
binderrorFunc BinderrorFunc
// Decode params from request body.
bodydecoder apiware.Bodydecoder
// When the APIHander's parameter name (struct tag) is unsetted,
// it is mapped from the structure field name by default.
// If `paramNameMapper` is nil, use snake style.
// If the APIHander's parameter binding fails, the default handler is invoked
paramNameMapper apiware.ParamNameMapper
// global file cache system manager
fsManager *FileServerManager
// Render is a custom faygo template renderer using pongo2.
render *Render
// The path for the upload files.
// When does not have a custom route, the route is automatically created.
upload PresetStatic
// The path for the static files.
// When does not have a custom route, the route is automatically created.
static PresetStatic
// The path for the log files
logDir string
syslog *logging.Logger
bizlog *logging.Logger
// the time-out period for the services shutdown.
shutdownTimeout time.Duration
// executed before closing services, but not guaranteed to be completed.
preCloseFunc func() error
// executed after services are closed, but not guaranteed to be completed.
postCloseFunc func() error
beforeRunOnce sync.Once
}
// PresetStatic is the system default static file routing information
PresetStatic struct {
root string
nocompress bool
nocache bool
handlers []Handler
}
)
var (
// global is the global configuration, functions and so on.
global = func() *GlobalVariables {
global := &GlobalVariables{
frames: []*Framework{},
config: globalConfig,
errorFunc: defaultErrorFunc,
bodydecoder: defaultBodydecoder,
binderrorFunc: defaultBinderrorFunc,
paramNameMapper: defaultParamNameMapper,
fsManager: newFileServerManager(
globalConfig.Cache.SizeMB*1024*1024,
globalConfig.Cache.ExpireSecond,
globalConfig.Cache.Enable,
globalConfig.Gzip.Enable,
),
upload: defaultUpload,
static: defaultStatic,
logDir: defaultLogDir,
shutdownTimeout: MinShutdownTimeout,
}
if globalConfig.Cache.Enable {
global.render = newRender(func(name string) (http.File, error) {
return global.fsManager.Open(name, "", false)
})
} else {
global.render = newRender(nil)
}
global.initLogger()
return global
}()
defaultErrorFunc = func(ctx *Context, errStr string, status int) {
if ctx.W.Committed() {
if status >= 500 {
ctx.Log().Debug(errStr)
}
return
}
if status >= 500 {
ctx.Log().Error(errStr)
}
statusText := http.StatusText(status)
if len(errStr) > 0 {
errStr = `<br><p><b style="color:red;">[ERROR]</b> <pre>` + errStr + `</pre></p>`
}
ctx.W.Header().Set(HeaderXContentTypeOptions, nosniff)
ctx.HTML(status, fmt.Sprintf("<html>\n"+
"<head><title>%d %s</title></head>\n"+
"<body bgcolor=\"white\">\n"+
"<center><h1>%d %s</h1></center>\n"+
"<hr>\n<center>faygo/%s</center>\n%s\n</body>\n</html>\n",
status, statusText, status, statusText, VERSION, errStr),
)
}
// The default body decoder is json format decoding
defaultBodydecoder = func(dest reflect.Value, body []byte) error {
var err error
if dest.Kind() == reflect.Ptr {
err = json.Unmarshal(body, dest.Interface())
} else {
err = json.Unmarshal(body, dest.Addr().Interface())
}
return err
}
defaultBinderrorFunc = func(ctx *Context, err error) {
ctx.String(http.StatusBadRequest, "%v", err)
}
defaultParamNameMapper = SnakeString
// The default path for the upload files
defaultUpload = PresetStatic{
root: "./upload/",
}
// The default path for the static files
defaultStatic = PresetStatic{
root: "./static/",
}
// The default path for the log files
defaultLogDir = "./log/"
)
func init() {
fmt.Println(banner[1:])
global.syslog.Criticalf("The PID of the current process is %d", os.Getpid())
if global.config.warnMsg != "" {
Warning(global.config.warnMsg)
global.config.warnMsg = ""
}
// init file cache
acceptencoder.InitGzip(global.config.Gzip.MinLength, global.config.Gzip.CompressLevel, global.config.Gzip.Methods)
}
func addFrame(frame *Framework) {
global.framesLock.Lock()
defer global.framesLock.Unlock()
name := frame.NameWithVersion()
for _, v := range global.frames {
if v.NameWithVersion() == name {
frame.Log().Panicf("frame %s is registered repeatedly", name)
}
}
global.frames = append(global.frames, frame)
}
func (g *GlobalVariables) beforeRun() {
g.beforeRunOnce.Do(func() {
resetFlag()
WritePid(LogDir() + "app.pid")
go graceSignal()
})
}