-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
297 lines (276 loc) · 6.34 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
package frame
import (
"bufio"
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"github.com/gin-gonic/gin"
"io"
"net/http"
"os"
"os/signal"
"reflect"
"runtime"
"runtime/debug"
"strconv"
"strings"
"syscall"
"time"
)
//web服务器结构体
type server struct {
port int //监听端口
httpServer *http.Server
router []func(gin *gin.Engine)
pidFile string
}
//启动
func (server *server) Start() {
//注册信号监听
server.registerSignal()
//记录pid
oriPid := server.getPid() //获取原始pid
server.logPid()
go func() {
server.shutdown()
}()
//服务启动
server.httpServer = &http.Server{
Addr: ":" + strconv.Itoa(server.port),
Handler: server.initRoute(),
ReadTimeout: 3 * time.Second,
WriteTimeout: 5 * time.Second,
}
err := server.httpServer.ListenAndServe() //成功的话会阻塞住,不会执行之后 所以进程文件不会记录
if err != nil && err != http.ErrServerClosed {
//将原来pid重写回去
server.logPid(oriPid)
fmt.Println(err)
os.Exit(1)
}
}
//重启
func (server *server) Restart() {
server.Stop(true)
server.Start()
}
//停止
func (server *server) Stop(restart ...bool) {
server.kill()
//阻塞等待接收上个程序结束
pid := server.getPid()
fmt.Printf("开始关闭进程,进程id:%d\n", pid)
if pid != -1 {
for {
if err := syscall.Kill(pid, 0); err == nil {
//继续循环等待
fmt.Printf("进程关闭中,等待0.5s\n")
time.Sleep(500 * time.Millisecond)
} else {
fmt.Printf("进程关闭状态:%s\n", err.Error())
break
}
}
}
if len(restart) <= 0 || !restart[0] {
os.Exit(0)
}
}
//信号监听
var stopFlag chan bool
func (server *server) registerSignal() {
stopFlag = make(chan bool, 0)
go func() {
listenSignal := []os.Signal{
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT,
syscall.SIGKILL,
syscall.SIGHUP,
}
sig := make(chan os.Signal, 0)
signal.Notify(sig, listenSignal...)
<-sig
server.stop()
}()
}
func (server *server) stop() {
stopFlag <- true
}
//关闭
func (server *server) shutdown() {
<-stopFlag
defer func() {
//关闭系统资源
CloseResource()
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := server.httpServer.Shutdown(ctx)
if err != nil {
//关闭报错
defer func() {
serverError(err)
}()
}
}
func (server *server) kill() {
pid := server.getPid()
if pid == -1 {
return
}
sig := syscall.SIGTERM
proc := new(os.Process)
proc.Pid = pid
err := proc.Signal(sig)
if err != nil {
defer func() {
serverError(err)
}()
}
return
}
//记录Pid
func (server *server) logPid(setPid ...int) {
pid := os.Getpid()
if len(setPid) > 0 {
pid = setPid[0]
}
file, err := os.OpenFile(server.pidFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
defer func() {
serverError(err)
}()
if err != nil {
return
}
defer file.Close()
writer := bufio.NewWriter(file)
_, err = writer.WriteString(strconv.Itoa(pid))
if err != nil {
return
}
_ = writer.Flush()
}
//获取Pid
func (server *server) getPid() int {
file, err := os.Open(server.pidFile)
defer func() {
serverError(err)
}()
if err != nil {
return -1
}
defer file.Close()
reader := bufio.NewReader(file)
pidByte, _, err := reader.ReadLine()
if err != nil {
return -1
}
pid, err := strconv.Atoi(string(pidByte))
if err != nil {
return -1
}
return pid
}
func (server *server) initRoute() *gin.Engine {
gin.SetMode(gin.ReleaseMode)
route := gin.Default()
for _, f := range server.router {
f(route)
}
return route
}
//注册路由
func (server *server) RegisterRoute(f func(gin *gin.Engine)) *server {
server.router = append(server.router, f)
return server
}
func serverError(err error) {
if err != nil {
msg := map[string]interface{}{
"error": err.Error(),
"stack": string(debug.Stack()),
}
App().Log.Error(msg, LogServerError)
}
}
//路由和中间件设置
const MethodGet = "GET"
const MethodPost = "POST"
type Router struct {
Method string
Uri string
Handle gin.HandlerFunc
SpecialMiddleware []gin.HandlerFunc
NoMiddleware []gin.HandlerFunc
}
type RouterMap map[string][]*Router
func SetRouter(gin *gin.Engine, routerMap RouterMap, globalMiddleware []gin.HandlerFunc) { //注册路由
for k, v := range routerMap {
if k == "_" {
for _, r := range v {
middleware := filterMiddleware(globalMiddleware, r.SpecialMiddleware, r.NoMiddleware)
middleware = append(middleware, r.Handle)
uriArr := strings.Split(r.Uri, "|") //支持多个
for _, uri := range uriArr {
if r.Method == MethodGet {
gin.GET(formatUri(uri), middleware...)
} else if r.Method == MethodPost {
gin.POST(formatUri(uri), middleware...)
}
}
}
} else {
group := gin.Group(formatUri(k))
for _, r := range v {
middleware := filterMiddleware(globalMiddleware, r.SpecialMiddleware, r.NoMiddleware)
middleware = append(middleware, r.Handle)
uriArr := strings.Split(r.Uri, "|") //支持多个
for _, uri := range uriArr {
if r.Method == MethodGet {
group.GET(formatUri(uri), middleware...)
} else if r.Method == MethodPost {
group.POST(formatUri(uri), middleware...)
}
}
}
}
}
}
func formatUri(uri string) string {
return "/" + strings.TrimLeft(uri, "/")
}
func filterMiddleware(globalMiddleware []gin.HandlerFunc, specialMiddleware []gin.HandlerFunc, filterMiddleware []gin.HandlerFunc) []gin.HandlerFunc {
totalMiddleware := make(map[string]gin.HandlerFunc, 0)
for _, v := range globalMiddleware {
name := runtime.FuncForPC(reflect.ValueOf(v).Pointer()).Name()
totalMiddleware[name] = v
}
for _, v := range specialMiddleware {
name := runtime.FuncForPC(reflect.ValueOf(v).Pointer()).Name()
totalMiddleware[name] = v
}
for _, v := range filterMiddleware {
name := runtime.FuncForPC(reflect.ValueOf(v).Pointer()).Name()
if _, ok := totalMiddleware[name]; ok {
delete(totalMiddleware, name)
}
}
resultMiddleware := make([]gin.HandlerFunc, 1)
resultMiddleware[0] = requestId
for _, v := range totalMiddleware {
resultMiddleware = append(resultMiddleware, v)
}
return resultMiddleware
}
//注册统一请求id
func requestId(c *gin.Context) {
b := make([]byte, 48)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
c.Next()
return
}
c.Set("requestId", Md5(base64.URLEncoding.EncodeToString(b)))
c.Next()
}