-
Notifications
You must be signed in to change notification settings - Fork 4
/
http_test.go
72 lines (59 loc) · 1.44 KB
/
http_test.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
package main
import (
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"testing"
"time"
"golang.org/x/net/context"
)
func setupServer(t testing.TB, handlerFunc func()) string {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("net.Listen failed: %v", err)
}
helloWorldBytes := []byte("Hello world")
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handlerFunc()
w.Write(helloWorldBytes)
})
go http.Serve(ln, handler)
return fmt.Sprintf("http://%v/test", ln.Addr().String())
}
func doGet(t testing.TB, client *http.Client, url string) {
resp, err := client.Get(url)
defer resp.Body.Close()
if err != nil {
t.Fatalf("Get failed: %v", err)
}
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {
t.Fatalf("ReadAll failed: %v", err)
}
}
func BenchmarkHTTPCall(b *testing.B) {
client := &http.Client{}
url := setupServer(b, func() {})
// Create a connection that will be reused.
doGet(b, client, url)
b.ResetTimer()
for i := 0; i < b.N; i++ {
doGet(b, client, url)
}
}
func BenchmarkHTTPCallWithCtx(b *testing.B) {
client := &http.Client{}
url := setupServer(b, func() {
_, cancel := context.WithTimeout(context.Background(), time.Second)
cancel()
})
// Create a connection that will be reused.
doGet(b, client, url)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, cancel := context.WithTimeout(context.Background(), time.Second)
doGet(b, client, url)
cancel()
}
}