-
Notifications
You must be signed in to change notification settings - Fork 10
/
serve.go
127 lines (103 loc) · 1.95 KB
/
serve.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
package twig
import (
"context"
"net"
"net/http"
"time"
)
// Server Http处理器接口
type Server interface {
Attacher
Cycler
}
type twigServer struct {
*http.Server
twig *Twig
ln net.Listener
}
func (s *twigServer) Attach(t *Twig) {
s.twig = t
s.Handler = t
}
func (s *twigServer) Shutdown(ctx context.Context) error {
return s.Server.Shutdown(ctx)
}
type httpServer struct {
*twigServer
}
func (h *httpServer) Start() (err error) {
go func() {
if err = h.Server.Serve(h.ln); err != nil {
h.twig.Logger.Panic(err)
}
}()
return
}
type tlsServer struct {
*twigServer
cert string
key string
}
func (h *tlsServer) Start() (err error) {
go func() {
if err = h.Server.ServeTLS(h.ln, h.cert, h.key); err != nil {
h.twig.Logger.Panic(err)
}
}()
return
}
type KeepAliveListener struct {
*net.TCPListener
}
func NewKeepAliveListener(address string) (l *KeepAliveListener) {
var addr *net.TCPAddr
var ln *net.TCPListener
var err error
if addr, err = net.ResolveTCPAddr("tcp", address); err != nil {
panic(err)
}
if ln, err = net.ListenTCP("tcp", addr); err != nil {
panic(err)
}
l = &KeepAliveListener{TCPListener: ln}
return
}
func (l *KeepAliveListener) Accept() (net.Conn, error) {
var conn *net.TCPConn
var err error
if conn, err = l.AcceptTCP(); err != nil {
return nil, err
}
conn.SetKeepAlive(true)
conn.SetKeepAlivePeriod(3 * time.Minute)
return conn, err
}
type lead struct {
twig *Twig
works []Server
}
func (l *lead) Attach(t *Twig) {
l.twig = t
}
func (l *lead) Start() error {
for _, s := range l.works {
if err := s.Start(); err != nil {
l.twig.Logger.Println(err)
}
}
return nil
}
func (l *lead) Shutdown(ctx context.Context) error {
for _, s := range l.works {
if err := s.Shutdown(ctx); err != nil {
l.twig.Logger.Println(err)
}
}
return nil
}
func (l *lead) AddServer(servers ...Server) {
l.works = append(l.works, servers...)
for _, s := range l.works {
s.Attach(l.twig)
}
}