This repository has been archived by the owner on Apr 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
97 lines (77 loc) · 2.01 KB
/
app.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
package serverz
import (
"context"
"net"
)
// AppServer wraps a server and provides all kinds of functionalities, such as:
//
// - Logging server events
// - Registering custom closers in the server
// - Listening on a net.Addr
type AppServer struct {
Server
// Name is used in logs to identify the server.
Name string
// Addr is optionally used for listening if specified.
Addr net.Addr
// Closer is called together with the servers regular Close method.
Closer Closer
// Logger specifies an optional logger.
// If nil, logging goes to os.Stderr via the log package's
// standard logger.
Logger logger
}
// Serve calls the underlying server.
func (s *AppServer) Serve(l net.Listener) error {
s.logger().Log(
"msg", "starting server",
"addr", l.Addr(),
"server", s.Name,
)
return s.Server.Serve(l)
}
// Shutdown attempts to gracefully shut the underlying server down.
func (s *AppServer) Shutdown(ctx context.Context) error {
s.logger().Log(
"msg", "shutting server gracefully down",
"server", s.Name,
)
return s.Server.Shutdown(ctx)
}
// Close invokes the wrapped server's closer first then the ones from s.Closer if any.
func (s *AppServer) Close() error {
s.logger().Log(
"msg", "closing all remaining connections",
"server", s.Name,
)
closers := Closers{s.Server}
if s.Closer != nil {
closers = append(closers, s.Closer)
}
return closers.Close()
}
// ListenAndServe listens on a network address and then
// calls Serve to handle requests on incoming connections.
func (s *AppServer) ListenAndServe(addr net.Addr) error {
// If no address is passed, try using the one configured in the server
if addr == nil {
addr = s.Addr
}
lis, err := listen(addr)
if err != nil {
return err
}
s.logger().Log(
"msg", "listening on address",
"addr", lis.Addr().String(),
"server", s.Name,
)
return s.Serve(lis)
}
// logger returns the configured logger instance or the default logger.
func (s *AppServer) logger() logger {
if s.Logger == nil {
return DefaultLogger
}
return s.Logger
}