-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
48 lines (43 loc) · 910 Bytes
/
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
package server
import (
"crypto/tls"
"net"
"net/http"
)
// Asynchronous HTTP server that can be started and stopped asynchronously.
type AsyncServer struct {
http.Server
listener net.Listener
stopped chan bool
}
// Create a new server instance. Note that Start() must be called before the
// server will begin accepting new connections.
func New(addr string) *AsyncServer {
a := &AsyncServer{
stopped: make(chan bool),
}
a.Addr = addr
return a
}
// Start the server.
func (a *AsyncServer) Start() error {
l, err := net.Listen("tcp", a.Addr)
if err != nil {
return err
}
a.Addr = l.Addr().String()
if a.TLSConfig != nil {
l = tls.NewListener(l, a.TLSConfig)
}
a.listener = l
go func() {
a.Serve(a.listener)
close(a.stopped)
}()
return nil
}
// Stop the server. This method blocks until the server is stopped.
func (a *AsyncServer) Stop() {
a.listener.Close()
<-a.stopped
}