aboutsummaryrefslogtreecommitdiff
path: root/server_test.go
blob: 9a8e651b754cb45d3d45ab0cc5f12029b78fdbb2 (plain)
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
package goxy

import (
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"testing"
)

const cannary = "hello from backend"

func TestNewServer(t *testing.T) {
	backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, cannary)
	}))
	defer backendServer.Close()

	server, err := NewServer("data.gob")
	if err != nil {
		t.Error(err)
	}

	rpcServer := httptest.NewServer(nil)
	defer rpcServer.Close()

	rpcURL, err := url.Parse(rpcServer.URL)
	if err != nil {
		t.Error(err)
	}

	err = Add(Entry{ServerName: "whatever", Upstream: backendServer.URL}, rpcURL.Host)
	if err != nil {
		t.Error(err)
	}

	frontendServer := httptest.NewServer(server.Handler)
	if err != nil {
		t.Error(err)
	}

	client := &http.Client{}
	req, err := http.NewRequest("GET", frontendServer.URL, nil)
	if err != nil {
		t.Error(err)
	}
	req.Header.Set("Host", "whatever")
	resp, err := client.Do(req)
	if err != nil {
		t.Error(err)
	}
	defer resp.Body.Close()

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Error(err)
	}

	if string(b) != cannary {
		t.Error("got", string(b), "expected", cannary)
	}
}