aboutsummaryrefslogtreecommitdiff
path: root/server_test.go
blob: b83edcd702d09b7ef93f4754c6e71e9e393d8584 (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
64
65
66
67
68
69
70
package goxy

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

const cannary = "hello from backend"

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

	server, err := NewServer("")
	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)
	}

	frontServer := httptest.NewServer(nil)
	if err != nil {
		t.Error(err)
	}
	frontURL, err := url.Parse(frontServer.URL)
	if err != nil {
		t.Error(err)
	}

	rpcClient, err := DialRPC(rpcURL.Host)
	if err != nil {
		t.Error(err)
	}
	err = rpcClient.Call("GoXY.Add", Entry{
		ServerName: frontURL.Host,
		Upstream:   backServer.URL,
	}, nil)
	if err != nil {
		t.Error(err)
	}

	frontServer.Config.Handler = server.Handler

	resp, err := http.Get(frontServer.URL)
	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)
	}
}