-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgin.go
112 lines (98 loc) · 2.22 KB
/
gin.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
package golib
import (
"context"
"fmt"
"net/http"
"net/http/httputil"
"sync"
"github.com/gin-gonic/gin"
)
var initGinOnce sync.Once
func InitGin() {
initGinOnce.Do(func() {
gin.SetMode(gin.ReleaseMode)
})
}
func NewGinEngine() *gin.Engine {
return NewGinEngineWithHandler(nil)
}
func NewGinEngineWithHandler(logHandler *GinLogHandler) *gin.Engine {
InitGin()
engine := gin.New()
if logHandler == nil {
logHandler = DefaultGinLogHandler
}
engine.Use(logHandler.LogRequest, ginRecover)
engine.NoRoute(func(c *gin.Context) {
c.Writer.WriteHeader(http.StatusNotFound)
_, _ = c.Writer.WriteString("404 page not found\n")
})
return engine
}
func ginRecover(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
stack := stack(3)
httpRequest, _ := httputil.DumpRequest(c.Request, false)
Log.Errorf("[Recovery] panic recovered:\n%s\n%s\n%s", string(httpRequest), err, stack)
c.AbortWithStatus(500)
}
}()
c.Next()
}
type GinTask struct {
*gin.Engine
Endpoint string
ShutdownHook func()
server *http.Server
c StopChan
shutdownErr error
}
func NewGinTask(endpoint string) *GinTask {
return NewGinTaskWithHandler(endpoint, nil)
}
func NewGinTaskWithHandler(endpoint string, logHandler *GinLogHandler) *GinTask {
return &GinTask{
Engine: NewGinEngineWithHandler(logHandler),
Endpoint: endpoint,
}
}
func (task *GinTask) Start(wg *sync.WaitGroup) StopChan {
task.c = NewStopChan()
if wg != nil {
wg.Add(1)
}
go func() {
if wg != nil {
defer wg.Done()
}
task.server = &http.Server{Addr: task.Endpoint, Handler: task.Engine}
Log.Infoln("Starting", task)
err := task.server.ListenAndServe()
if hook := task.ShutdownHook; hook != nil {
hook()
}
if err == http.ErrServerClosed {
err = nil
}
if task.shutdownErr != nil {
if err == nil {
err = task.shutdownErr
} else {
err = MultiError([]error{task.shutdownErr, err})
}
}
task.c.StopErr(err)
}()
return task.c
}
func (task *GinTask) Stop() {
server := task.server
if server != nil {
Log.Infoln("Shutting down", task)
task.shutdownErr = server.Shutdown(context.Background())
}
}
func (task *GinTask) String() string {
return fmt.Sprintf("HTTP server on " + task.Endpoint)
}