forked from savsgio/atreugo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
atreugo_unix.go
92 lines (72 loc) · 1.84 KB
/
atreugo_unix.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
// +build !windows
package atreugo
import (
"net"
"os"
"os/signal"
"runtime"
"syscall"
"github.com/valyala/fasthttp/prefork"
)
// IsPreforkChild checks if the current thread/process is a child.
func IsPreforkChild() bool {
return prefork.IsChild()
}
func (s *Atreugo) newPreforkServer() *prefork.Prefork {
p := &prefork.Prefork{
Network: s.cfg.Network,
Reuseport: s.cfg.Reuseport,
RecoverThreshold: runtime.GOMAXPROCS(0) / 2,
Logger: s.log,
ServeFunc: s.Serve,
}
if s.cfg.GracefulShutdown {
p.ServeFunc = s.ServeGracefully
}
return p
}
// ServeGracefully serves incoming connections from the given listener with graceful shutdown
//
// It's blocked until the given listener returns permanent error.
//
// WARNING: Windows is not supportted.
func (s *Atreugo) ServeGracefully(ln net.Listener) error {
s.cfg.GracefulShutdown = true
if s.server.ReadTimeout <= 0 {
s.server.ReadTimeout = defaultReadTimeout
s.cfg.ReadTimeout = defaultReadTimeout
}
listenErr := make(chan error, 1)
go func() {
listenErr <- s.Serve(ln)
}()
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, syscall.SIGINT, syscall.SIGTERM)
select {
case err := <-listenErr:
return err
case <-osSignals:
s.log.Infof("Shutdown signal received")
if err := s.server.Shutdown(); err != nil {
return err
}
s.log.Infof("Server gracefully stopped")
}
return nil
}
// ListenAndServe serves requests from the given network and address in the atreugo configuration.
//
// Pass custom listener to Serve/ServeGracefully if you want to use it.
func (s *Atreugo) ListenAndServe() error {
if s.cfg.Prefork {
return s.newPreforkServer().ListenAndServe(s.cfg.Addr)
}
ln, err := s.getListener()
if err != nil {
return err
}
if s.cfg.GracefulShutdown {
return s.ServeGracefully(ln)
}
return s.Serve(ln)
}