forked from Azure/aks-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testServer.go
52 lines (44 loc) · 1.18 KB
/
testServer.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package testserver
import (
"fmt"
"net"
"net/http"
"strconv"
"strings"
)
// TestServer wraps a http.Server that runs on a separate goroutine
// and is intended for unit testing.
type TestServer struct {
Port int
server *http.Server
}
// CreateAndStart creates and returns a TestServer that waits for web
// requests on the provided port using the provided multiplexer on a
// different goroutine.
//
// If the port is 0, a port number is dynamically chosen. This port
// can be retrieved by checking the Port field of the TestServer struct.
func CreateAndStart(port int, mux *http.ServeMux) (*TestServer, error) {
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
return nil, err
}
port, err = strconv.Atoi(strings.Split(ln.Addr().String(), ":")[1])
if err != nil {
return nil, err
}
server := &http.Server{Handler: mux}
go func() {
_ = server.Serve(ln)
}()
return &TestServer{
Port: port,
server: server,
}, nil
}
// Stop immediately closes all connections and shuts down the server.
func (ms TestServer) Stop() {
_ = ms.server.Close()
}