-
Notifications
You must be signed in to change notification settings - Fork 85
/
proxy.go
62 lines (53 loc) · 1.56 KB
/
proxy.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
package proxy
import (
"net/http"
"net/http/httputil"
"net/url"
"strings"
"github.com/kyma-incubator/compass/components/director/pkg/log"
"github.com/pkg/errors"
)
type Proxy struct {
targetURL *url.URL
reverseProxy *httputil.ReverseProxy
}
func New(targetOrigin, proxyPath string, transport http.RoundTripper) (*httputil.ReverseProxy, error) {
targetURL, err := url.Parse(targetOrigin)
if err != nil {
return nil, errors.Wrapf(err, "while parsing URL %s", targetOrigin)
}
targetQuery := targetURL.RawQuery
director := func(req *http.Request) {
req.URL.Scheme = targetURL.Scheme
req.URL.Host = targetURL.Host
req.URL.Path = requestURL(req.URL.Path, proxyPath)
req.Host = targetURL.Host
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
if _, ok := req.Header["User-Agent"]; !ok {
// explicitly disable User-Agent so it's not set to default value
req.Header.Set("User-Agent", "")
}
}
return &httputil.ReverseProxy{
Director: director,
Transport: transport,
ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) {
log.C(req.Context()).WithError(err).Errorf("Error while proxying request to %q", req.URL.String())
rw.WriteHeader(http.StatusBadGateway)
},
}, nil
}
func requestURL(requestPath, proxyPath string) string {
if proxyPath == "/" {
return requestPath
}
trimmedPath := strings.TrimPrefix(requestPath, proxyPath)
if trimmedPath == "" {
return "/"
}
return trimmedPath
}