forked from louketo/louketo-proxy
-
Notifications
You must be signed in to change notification settings - Fork 43
/
fake_upstream.go
91 lines (82 loc) · 2.46 KB
/
fake_upstream.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
86
87
88
89
90
91
package testsuite
import (
"encoding/json"
"io"
"net/http"
"strings"
"golang.org/x/net/websocket"
)
// fakeUpstreamResponse is the response from fake upstream
type fakeUpstreamResponse struct {
URI string `json:"uri"`
Method string `json:"method"`
Address string `json:"address"`
Headers http.Header `json:"headers"`
Body string `json:"body"`
}
// FakeUpstreamService acts as a fake upstream service, returns the headers and request
type FakeUpstreamService struct{}
func (f *FakeUpstreamService) ServeHTTP(wrt http.ResponseWriter, req *http.Request) {
upgrade := strings.ToLower(req.Header.Get("Upgrade"))
if upgrade == "websocket" {
wrt.Header().Set(TestProxyAccepted, "true")
websocket.Handler(func(wsock *websocket.Conn) {
defer wsock.Close()
var data []byte
err := websocket.Message.Receive(wsock, &data)
if err != nil {
wsock.WriteClose(http.StatusBadRequest)
return
}
content, _ := json.Marshal(&fakeUpstreamResponse{
URI: req.RequestURI,
Method: req.Method,
Address: req.RemoteAddr,
Headers: req.Header,
})
_ = websocket.Message.Send(wsock, content)
}).ServeHTTP(wrt, req)
} else {
reqBody, err := io.ReadAll(req.Body)
if err != nil {
wrt.WriteHeader(http.StatusInternalServerError)
}
wrt.Header().Set(TestProxyAccepted, "true")
wrt.Header().Set("Content-Type", "application/json")
content, err := json.Marshal(&fakeUpstreamResponse{
// r.RequestURI is what was received by the proxy.
// r.URL.String() is what is actually sent to the upstream service.
// KEYCLOAK-10864, KEYCLOAK-11276, KEYCLOAK-13315
URI: req.URL.String(),
Method: req.Method,
Address: req.RemoteAddr,
Headers: req.Header,
Body: string(reqBody),
})
if err != nil {
wrt.WriteHeader(http.StatusInternalServerError)
} else {
wrt.WriteHeader(http.StatusOK)
}
_, _ = wrt.Write(content)
}
}
// commented out see TestUpstreamProxy test comment
// func createTestProxy() (*http.Server, net.Listener, error) {
// proxy := goproxy.NewProxyHttpServer()
// proxy.OnRequest().DoFunc(
// func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
// r.Header.Set(TestProxyHeaderKey, TestProxyHeaderVal)
// return r, nil
// },
// )
// proxyHTTPServer := &http.Server{
// Handler: proxy,
// }
// ln, err := net.Listen("tcp", randomLocalHost)
// if err != nil {
//nolint:dupword
// return nil, nil, err
// }
// return proxyHTTPServer, ln, nil
// }