forked from chapsuk/mserv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
61 lines (52 loc) · 1.16 KB
/
listener.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
package mserv
import (
"context"
"time"
)
type (
// Serve wrapper for Listener interface
Serve struct {
shutdownTimeout time.Duration
shutdownError error
server Listener
}
Listener interface {
ListenAndServe() error
Shutdown(context.Context) error
}
)
// NewListener returns new Listener wrapper
func NewListener(shutdownTimeout time.Duration, shutdownError error, server Listener) Server {
if server == nil {
log.Print("missing Listener, skip")
return nil
}
return &Serve{
shutdownTimeout: shutdownTimeout,
shutdownError: shutdownError,
server: server,
}
}
// Start listener in goroutine
// write fatal msg by log if cant start server
func (s *Serve) Start() {
go func() {
if err := s.server.ListenAndServe(); err != nil {
// to ignore shutdown error
if err != s.shutdownError {
log.Printf("start listener error: %s", err)
}
}
}()
}
// Stop listener with timeout
func (s *Serve) Stop() {
if s == nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), s.shutdownTimeout)
defer cancel()
if err := s.server.Shutdown(ctx); err != nil {
log.Printf("stop listener error: %s", err)
}
}