Uh oh!
There was an error while loading. Please reload this page.
This repository was archived by the owner on Mar 19, 2025. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
Latest commit
107 lines (91 loc) · 1.84 KB
/
Copy pathserver.go
File metadata and controls
107 lines (91 loc) · 1.84 KB
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
package httpserver
import (
"context"
"github.com/gobestsdk/log"
"os"
"os/signal"
"syscall"
"time"
"net/http"
)
// HttpServer http的server
typeHttpServerstruct {
namestring//服务名称
Server http.Server
Mux*http.ServeMux
quitChanchan os.Signal
Runflagbool
quitTimeout time.Duration
}
// New 生产Server实例
funcNew(serverNamestring) *HttpServer {
s:=&HttpServer{
name: serverName,
Server: http.Server{},
Runflag: true,
quitChan: make(chan os.Signal),
quitTimeout: 5*time.Second,
}
s.Mux=new(http.ServeMux)
s.Server.Handler=s.Mux
returns
}
// SetPort 设置服务端口
func (s*HttpServer) SetPort(portstring) {
s.Server.Addr=port
}
// Run server on addr
func (s*HttpServer) Run() {
gos.httpServer()
<-s.quitChan
}
func (s*HttpServer) httpServer() {
log.Info(log.Fields{"server "+s.name+"ListenAndServe addr:": s.Server.Addr})
err:=s.Server.ListenAndServe()
iferr!=nil {
log.Error(log.Fields{"app": "ListenAndServe failed", "error": err.Error()})
}
}
// Waitstop 阻塞主线程,直到进程结束
func (s*HttpServer) Waitstop() {
s.Runflag=false
s:
signal.Notify(s.quitChan,
os.Interrupt,
os.Kill,
syscall.SIGTERM,
syscall.SIGQUIT,
syscall.SIGINT,
syscall.SIGKILL,
syscall.SIGHUP,
)
sig:=<-s.quitChan
log.Info(log.Fields{
"signal": sig,
})
switchsig {
casesyscall.SIGUSR1:
fallthrough
casesyscall.SIGUSR2:
log.Loggoid=0
goto s
default:
}
s.Stop()
}
// Waitstop 停止server
func (s*HttpServer) Stop() {
s.Runflag=false
ctx, cancel:=context.WithTimeout(context.Background(), s.quitTimeout)
defercancel()
iferr:=s.Server.Shutdown(ctx); err!=nil {
log.Error(log.Fields{
"app": "Shutdown HttpServer",
"err": err.Error(),
})
}
log.Info(log.Fields{
"msg": "exiting...",
})
close(s.quitChan)
}