-
Notifications
You must be signed in to change notification settings - Fork 22
/
http_server.go
51 lines (46 loc) · 1.14 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
package main
import (
"context"
"log"
"net"
"net/http"
neturl "net/url"
"time"
)
func startHTTPServer(ctx context.Context, handler http.Handler, logger *log.Logger) (url string, shutdown context.CancelFunc, err error) {
// Need to generate a random port every time for tests in parallel to run.
l, err := net.Listen("tcp", "localhost:")
if err != nil {
return "", nil, err
}
server := &http.Server{
Handler: handler,
}
go func() { // serves HTTP
err := server.Serve(l)
if err != http.ErrServerClosed {
logger.Println(err)
}
}()
shutdownCtx, startShutdown := context.WithCancel(ctx)
shutdownComplete := make(chan struct{}, 1)
go func() { // waits for canceled ctx or triggered shutdown, then shuts down HTTP
<-shutdownCtx.Done()
shutdownTimeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := server.Shutdown(shutdownTimeoutCtx)
if err != nil {
logger.Println(err)
}
shutdownComplete <- struct{}{}
}()
shutdown = func() {
startShutdown()
<-shutdownComplete
}
url = (&neturl.URL{
Scheme: "http",
Host: l.Addr().String(),
}).String()
return url, shutdown, nil
}