forked from chapsuk/mserv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
68 lines (57 loc) · 1.28 KB
/
http.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
package mserv
import (
"context"
"net/http"
"time"
)
// HTTPServer wrapper of http.Server
type HTTPServer struct {
shutdownTimeout time.Duration
server *http.Server
}
// NewHTTPServer returns new http.Server wrapper
func NewHTTPServer(shutdownTimeout time.Duration, server *http.Server) Server {
if server == nil {
log.Print("missing http.Server, skip")
return nil
}
if server.Addr == "" {
log.Print("missing bind address for http.Server, skip")
return nil
}
return &HTTPServer{
shutdownTimeout: shutdownTimeout,
server: server,
}
}
// Start http server in goroutine
// write fatal msg by log if cant start server
func (h *HTTPServer) Start() {
if h == nil {
return
}
go func() {
if err := h.server.ListenAndServe(); err != nil {
if err != http.ErrServerClosed {
log.Printf("start http server error: %s", err)
}
}
}()
}
// Stop http server with timeout
func (h *HTTPServer) Stop() {
if h == nil {
return
}
if h.shutdownTimeout == 0 {
if err := h.server.Close(); err != nil {
log.Printf("stop http server error: %s", err)
}
return
}
ctx, cancel := context.WithTimeout(context.Background(), h.shutdownTimeout)
defer cancel()
if err := h.server.Shutdown(ctx); err != nil {
log.Printf("stop http server error: %s", err)
}
}