This repository has been archived by the owner on Nov 26, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
proxy_test.go
73 lines (54 loc) · 1.64 KB
/
proxy_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
73
package main
import (
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttputil"
)
type fakeBalancer struct{}
var fakeBackend = Backend{}
func setFakeBackend(url string, weight int) {
fakeBackend.Weight = weight
fakeBackend.URL = url
fakeBackend.client = &fasthttp.HostClient{Addr: url, MaxConns: fasthttp.DefaultMaxConnsPerHost}
}
func (b fakeBalancer) Select() (*Backend, bool) {
if fakeBackend.Weight == 0 {
return nil, false
}
return &fakeBackend, true
}
func fakeHandler(ctx *fasthttp.RequestCtx) {
ctx.WriteString("hoho!")
}
func TestProxyBackendNotFound(t *testing.T) {
ln := fasthttputil.NewInmemoryListener()
defer ln.Close()
go fasthttp.Serve(ln, fakeHandler)
setFakeBackend(ln.Addr().String(), 0)
fb := fakeBalancer{}
ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("/")
Proxy(fb, ctx)
if code := ctx.Response.StatusCode(); code != fasthttp.StatusForbidden {
t.Errorf("response code should be %d but got: %d", fasthttp.StatusForbidden, code)
}
}
func TestProxyWorks(t *testing.T) {
fakeServer := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}),
)
defer fakeServer.Close()
u, _ := url.ParseRequestURI(fakeServer.URL)
setFakeBackend(u.Host, 1)
fb := fakeBalancer{}
ctx := &fasthttp.RequestCtx{}
// RequestURI is used first if it's not empty: https://github.com/valyala/fasthttp/issues/114
ctx.Request.SetRequestURI("http://" + u.Host + "/")
Proxy(fb, ctx)
if code := ctx.Response.StatusCode(); code != fasthttp.StatusOK {
t.Errorf("response code should be %d but got: %d", fasthttp.StatusOK, code)
}
}