Skip to content

Commit 84485d2

Browse files
committed
websocketproxy: support X-Forwarded-For and X-Forwarded-Proto headers
1 parent 2e6e0d3 commit 84485d2

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

websocketproxy.go

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@ package websocketproxy
44
import (
55
"io"
66
"log"
7+
"net"
78
"net/http"
89
"net/url"
10+
"strings"
911

1012
"github.com/gorilla/websocket"
1113
)
@@ -63,8 +65,6 @@ func (w *WebsocketProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
6365
dialer = DefaultDialer
6466
}
6567

66-
// TODO: Also consider adding x-fowarded-for and x-forwarded-proto headers.
67-
6868
// Pass headers from the incoming request to the dialer to forward them to
6969
// the final destinations.
7070
h := http.Header{}
@@ -78,6 +78,27 @@ func (w *WebsocketProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
7878
h.Add("Cookie", cookie)
7979
}
8080

81+
// Pass X-Forwarded-For headers too, code below is a part of
82+
// httputil.ReverseProxy. See http://en.wikipedia.org/wiki/X-Forwarded-For
83+
// for more information
84+
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
85+
// If we aren't the first proxy retain prior
86+
// X-Forwarded-For information as a comma+space
87+
// separated list and fold multiple headers into one.
88+
if prior, ok := req.Header["X-Forwarded-For"]; ok {
89+
clientIP = strings.Join(prior, ", ") + ", " + clientIP
90+
}
91+
h.Set("X-Forwarded-For", clientIP)
92+
}
93+
94+
// Set the originating protol of the incoming HTTP request. The SSL might
95+
// be terminated on our site and because we doing proxy adding this would
96+
// be helpful for applications on the backedn.
97+
h.Set("X-Forwarded-Proto", "http")
98+
if req.TLS != nil {
99+
h.Set("X-Forwarded-Proto", "https")
100+
}
101+
81102
// Connect to the backend url, also pass the headers we prepared above.
82103
connBackend, resp, err := dialer.Dial(backendURL.String(), h)
83104
if err != nil {

0 commit comments

Comments
 (0)