-
Notifications
You must be signed in to change notification settings - Fork 4
/
http_test.go
68 lines (62 loc) · 1.24 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
package PaxiBFT
import (
"context"
"io"
"io/ioutil"
"math/rand"
"net/http"
"strconv"
"testing"
)
func RunServer(t *testing.T, port string) *http.Server {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("id")
i := r.URL.Path[1:]
t.Log("server", id, i)
w.Header().Set("id", id)
_, err := io.WriteString(w, i)
if err != nil {
t.Fatal(err)
}
})
server := &http.Server{
Addr: ":" + port,
Handler: mux,
}
go func() {
err := server.ListenAndServe()
if err != http.ErrServerClosed {
t.Fatal(err)
}
}()
return server
}
func RunClient(t *testing.T, port string) {
i := rand.Intn(1000)
url := "http://127.0.0.1:" + port + "/" + strconv.Itoa(i)
r, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
t.Fatal(err)
return
}
r.Header.Set("id", strconv.Itoa(i))
res, err := http.DefaultClient.Do(r)
if err != nil {
t.Fatal("client", err)
return
}
defer res.Body.Close()
if res.StatusCode == http.StatusOK {
b, _ := ioutil.ReadAll(res.Body)
t.Log("client", string(b))
}
}
func TestHTTP(t *testing.T) {
s := RunServer(t, "8087")
RunClient(t, "8087")
err := s.Shutdown(context.Background())
if err != nil {
t.Fatal(err)
}
}