forked from jpillora/chisel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_server.go
87 lines (77 loc) · 1.67 KB
/
http_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
package cnet
import (
"context"
"errors"
"net"
"net/http"
"sync"
"golang.org/x/sync/errgroup"
)
//HTTPServer extends net/http Server and
//adds graceful shutdowns
type HTTPServer struct {
*http.Server
waiterMux sync.Mutex
waiter *errgroup.Group
listenErr error
}
//NewHTTPServer creates a new HTTPServer
func NewHTTPServer() *HTTPServer {
return &HTTPServer{
Server: &http.Server{},
}
}
func (h *HTTPServer) GoListenAndServe(addr string, handler http.Handler) error {
return h.GoListenAndServeContext(context.Background(), addr, handler)
}
func (h *HTTPServer) GoListenAndServeContext(ctx context.Context, addr string, handler http.Handler) error {
if ctx == nil {
return errors.New("ctx must be set")
}
l, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return h.GoServe(ctx, l, handler)
}
func (h *HTTPServer) GoServe(ctx context.Context, l net.Listener, handler http.Handler) error {
if ctx == nil {
return errors.New("ctx must be set")
}
h.waiterMux.Lock()
defer h.waiterMux.Unlock()
h.Handler = handler
h.waiter, ctx = errgroup.WithContext(ctx)
h.waiter.Go(func() error {
return h.Serve(l)
})
go func() {
<-ctx.Done()
h.Close()
}()
return nil
}
func (h *HTTPServer) Close() error {
h.waiterMux.Lock()
defer h.waiterMux.Unlock()
if h.waiter == nil {
return errors.New("not started yet")
}
return h.Server.Close()
}
func (h *HTTPServer) Wait() error {
h.waiterMux.Lock()
unset := h.waiter == nil
h.waiterMux.Unlock()
if unset {
return errors.New("not started yet")
}
h.waiterMux.Lock()
wait := h.waiter.Wait
h.waiterMux.Unlock()
err := wait()
if err == http.ErrServerClosed {
err = nil //success
}
return err
}