-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhttp_server.go
More file actions
69 lines (60 loc) · 1.23 KB
/
http_server.go
File metadata and controls
69 lines (60 loc) · 1.23 KB
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
package vexserver
import (
"errors"
"log"
"net"
"net/http"
"sync"
)
// HTTPServer extends net/http server and
// adds graceful shutdowns
type HTTPServer struct {
*http.Server
listener net.Listener
running chan error
isRunning bool
closer sync.Once
}
// NewHTTPServer creates a new HTTPServer instance
func NewHTTPServer() *HTTPServer {
return &HTTPServer{
Server: &http.Server{},
listener: nil,
running: make(chan error, 1),
}
}
// GoListenAndServe starts HTTPServer instance and listens on
// specified addr
func (h *HTTPServer) GoListenAndServe(addr string, handler http.Handler) error {
l, err := net.Listen("tcp", addr)
if err != nil {
return err
}
h.isRunning = true
h.Handler = handler
h.listener = l
log.Printf("HTTP server listening on %s...\n", addr)
go func() {
h.closeWith(h.Serve(l))
}()
return nil
}
func (h *HTTPServer) closeWith(err error) {
if !h.isRunning {
return
}
h.isRunning = false
h.running <- err
}
// Close closes the HTTPServer instance
func (h *HTTPServer) Close() error {
h.closeWith(nil)
return h.listener.Close()
}
// Wait waits for server to be stopped
func (h *HTTPServer) Wait() error {
if !h.isRunning {
return errors.New("already closed")
}
return <-h.running
}