Skip to content

Commit 9834887

Browse files
committed
Add preserve host option
1 parent fae732f commit 9834887

File tree

3 files changed

+39
-3
lines changed

3 files changed

+39
-3
lines changed

build.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/usr/bin/env bash
22

3-
RELEASE=0.2.0
3+
RELEASE=0.3.0
44
dist=dist
55
bin=oauth-proxy
66

proxy/proxy.go

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"net/http"
66
"net/http/httputil"
77
"net/url"
8+
"strings"
89
"time"
910

1011
"github.com/anduintransaction/oauth-proxy/utils"
@@ -17,6 +18,7 @@ type Proxy struct {
1718
RedirectURI string `config:"redirect_uri"`
1819
RequestHost string `config:"request_host"`
1920
EndPoint string `config:"end_point"`
21+
PreserveHost bool `config:"preserve_host"`
2022
ClientID string `config:"client_id"`
2123
ClientSecret string `config:"client_secret"`
2224
CallbackURI string `config:"callback_uri"`
@@ -41,7 +43,41 @@ func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
4143
}
4244

4345
func (p *Proxy) createReverseProxy() {
44-
p.reverseProxy = httputil.NewSingleHostReverseProxy(p.target)
46+
p.reverseProxy = &httputil.ReverseProxy{
47+
Director: p.transformRequest,
48+
}
49+
}
50+
51+
func (p *Proxy) transformRequest(req *http.Request) {
52+
req.URL.Scheme = p.target.Scheme
53+
req.URL.Host = p.target.Host
54+
req.URL.Path = p.singleJoiningSlash(p.target.Path, req.URL.Path)
55+
targetQuery := p.target.RawQuery
56+
if targetQuery == "" || req.URL.RawQuery == "" {
57+
req.URL.RawQuery = targetQuery + req.URL.RawQuery
58+
} else {
59+
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
60+
}
61+
if _, ok := req.Header["User-Agent"]; !ok {
62+
// explicitly disable User-Agent so it's not set to default value
63+
req.Header.Set("User-Agent", "")
64+
}
65+
if !p.PreserveHost {
66+
req.Header.Set("Host", p.target.Host)
67+
req.Host = p.target.Host
68+
}
69+
}
70+
71+
func (p *Proxy) singleJoiningSlash(a, b string) string {
72+
aslash := strings.HasSuffix(a, "/")
73+
bslash := strings.HasPrefix(b, "/")
74+
switch {
75+
case aslash && bslash:
76+
return a + b[1:]
77+
case !aslash && !bslash:
78+
return a + "/" + b
79+
}
80+
return a + b
4581
}
4682

4783
var Config struct {

service/misc.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
)
77

88
func Version() string {
9-
return "0.2.0"
9+
return "0.3.0"
1010
}
1111

1212
func generateRandomState() (string, error) {

0 commit comments

Comments
 (0)