-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve_test.go
58 lines (48 loc) · 1.28 KB
/
serve_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
package stargate
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
)
func TestServe(t *testing.T) {
okCode := "ok"
backend := httptest.NewServer(namedHandler(okCode))
defer backend.Close()
origin, err := NewOriginServer(makeRouteOption(backend, "http"), defaultDirector("/"))
if err != nil {
t.Fatal(err)
}
backends := []OriginServer{origin}
roundRobin, err := RoundRobin(backends)
if err != nil {
t.Errorf("Cannot create roundRobin LB : %v", err)
}
server := httptest.NewServer(serve(roundRobin))
defer server.Close()
client := &http.Client{}
get, err := client.Get(makeRouteOption(server, "http").Address)
if err != nil {
t.Errorf("Cannot execute GET request : %v", err)
}
b, err := io.ReadAll(get.Body)
if err != nil {
t.Fatalf("cannot read response from server: %v", err)
}
resp := string(b)
if resp != okCode {
t.Errorf(`Expected "%s" but got "%s"`, okCode, resp)
}
}
func namedHandler(name string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
if _, err := io.WriteString(w, name); err != nil {
panic(err)
}
}
}
func makeRouteOption(s *httptest.Server, protocol string) *RouteOptions {
return &RouteOptions{Address: fmt.Sprintf("%s://%s", protocol, s.Listener.Addr().String())}
}