1// Code in this file is based on net/http/httputil/reverseproxy.go from the Go
2// standard library, and covered by licenses/golang.org/x/sys/LICENSE.
3
4package http
5
6import (
7 "net/http"
8 "net/http/httputil"
9 "net/url"
10 "strings"
11)
12
13func newSingleHostReverseProxy(target *url.URL) *httputil.ReverseProxy {
14 director := func(req *http.Request) {
15 rewriteRequestURL(req, target)
16 }
17 return &httputil.ReverseProxy{Director: director}
18}
19
20func rewriteRequestURL(req *http.Request, target *url.URL) {
21 targetQuery := target.RawQuery
22 req.URL.Scheme = target.Scheme
23 req.URL.Host = target.Host
24 req.URL.Path, req.URL.RawPath = joinURLPath(target, req.URL)
25 if targetQuery == "" || req.URL.RawQuery == "" {
26 req.URL.RawQuery = targetQuery + req.URL.RawQuery
27 } else {
28 req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
29 }
30}
31
32// Like in httputil, but we won't add a trailing slash if the original request did
33// not have one.
34func joinURLPath(a, b *url.URL) (path, rawpath string) {
35 if a.RawPath == "" && b.RawPath == "" {
36 return singleJoiningSlash(a.Path, b.Path), ""
37 }
38 // Same as singleJoiningSlash, but uses EscapedPath to determine
39 // whether a slash should be added
40 apath := a.EscapedPath()
41 bpath := b.EscapedPath()
42
43 aslash := strings.HasSuffix(apath, "/")
44 bslash := strings.HasPrefix(bpath, "/")
45
46 switch {
47 case aslash && bslash:
48 return a.Path + b.Path[1:], apath + bpath[1:]
49 case !aslash && !bslash && bpath != "":
50 return a.Path + "/" + b.Path, apath + "/" + bpath
51 }
52 return a.Path + b.Path, apath + bpath
53}
54
55func singleJoiningSlash(a, b string) string {
56 aslash := strings.HasSuffix(a, "/")
57 bslash := strings.HasPrefix(b, "/")
58 switch {
59 case aslash && bslash:
60 return a + b[1:]
61 case !aslash && !bslash && b != "":
62 return a + "/" + b
63 }
64 return a + b
65}
66