-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
98 lines (81 loc) · 1.75 KB
/
server.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
package rice
import (
"context"
"net"
"net/http"
"time"
)
const (
_defaultReadTimeout = 5 * time.Second
_defaultWriteTimeout = 5 * time.Second
_defaultAddr = ":80"
_defaultShutdownTimeout = 3 * time.Second
)
// Server -.
type Server struct {
server *http.Server
notify chan error
shutdownTimeout time.Duration
}
// NewHttpServer -.
func NewHttpServer(handler http.Handler, opts ...ServerOption) *Server {
httpServer := &http.Server{
Handler: handler,
ReadTimeout: _defaultReadTimeout,
WriteTimeout: _defaultWriteTimeout,
Addr: _defaultAddr,
}
s := &Server{
server: httpServer,
notify: make(chan error, 1),
shutdownTimeout: _defaultShutdownTimeout,
}
// Custom options
for _, opt := range opts {
opt(s)
}
s.start()
return s
}
func (s *Server) start() {
go func() {
s.notify <- s.server.ListenAndServe()
close(s.notify)
}()
}
// Notify -.
func (s *Server) Notify() <-chan error {
return s.notify
}
// Shutdown -.
func (s *Server) Shutdown() error {
ctx, cancel := context.WithTimeout(context.Background(), s.shutdownTimeout)
defer cancel()
return s.server.Shutdown(ctx)
}
// ServerOption -.
type ServerOption func(*Server)
// Port -.
func Port(port string) ServerOption {
return func(s *Server) {
s.server.Addr = net.JoinHostPort("", port)
}
}
// ReadTimeout -.
func ReadTimeout(timeout time.Duration) ServerOption {
return func(s *Server) {
s.server.ReadTimeout = timeout
}
}
// WriteTimeout -.
func WriteTimeout(timeout time.Duration) ServerOption {
return func(s *Server) {
s.server.WriteTimeout = timeout
}
}
// ShutdownTimeout -.
func ShutdownTimeout(timeout time.Duration) ServerOption {
return func(s *Server) {
s.shutdownTimeout = timeout
}
}