-
Notifications
You must be signed in to change notification settings - Fork 2
/
proxy_test.go
85 lines (80 loc) · 2.17 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
74
75
76
77
78
79
80
81
82
83
84
85
package gproxy_test
import (
"context"
"fmt"
"github.com/graphikDB/gproxy"
"github.com/graphikDB/gproxy/logger"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func ExampleNew() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
}))
defer srv.Close()
proxy, err := gproxy.New(ctx,
// serve unencrypted http/gRPC traffic on port 8080
gproxy.WithInsecurePort(8080),
// serve encrypted http/gRPC traffic on port 443
gproxy.WithSecurePort(443),
// if the request is http & the request host contains localhost, proxy to the target server
gproxy.WithRoute(fmt.Sprintf(`this.http && this.host.contains('localhost') => '%s'`, srv.URL)),
// when deploying, set the letsencrypt allowed domains
gproxy.WithAcmePolicy("this.host.contains('graphikdb.io')"))
if err != nil {
fmt.Println(err.Error())
return
}
if err := proxy.Serve(ctx); err != nil {
fmt.Println(err.Error())
return
}
// Output:
}
func Test(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
}))
defer srv.Close()
lgger := logger.New(true)
proxy, err := gproxy.New(ctx,
gproxy.WithInsecurePort(8081),
gproxy.WithSecurePort(8082),
gproxy.WithLogger(lgger),
gproxy.WithRoute(
fmt.Sprintf(
`this.http && this.host.contains("localhost") => "%s"`,
srv.URL,
)),
// when deploying, set the letsencrypt allowed domains
gproxy.WithAcmePolicy("this.host.contains('graphikdb.io')"))
if err != nil {
t.Fatal(err.Error())
}
go func() {
if err := proxy.Serve(ctx); err != nil {
t.Fatal(err.Error())
}
}()
time.Sleep(2 * time.Second)
resp, err := http.DefaultClient.Get("http://localhost:8081/")
if err != nil {
t.Fatal(err.Error())
}
defer resp.Body.Close()
bits, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err.Error())
}
if string(bits) != "hello world" {
t.Fatal("failed to proxy in mem request")
}
cancel()
}