Skip to content
Permalink
Browse files

Fix and tests for X-Forwarded-For support

  • Loading branch information
dunglas committed Jan 5, 2020
1 parent 6e63c9f commit 5a5e14752c37d117f2fd00306f05d06cf5f9d787
Showing with 8 additions and 3 deletions.
  1. +1 −1 fixtures/api/jsonld.go
  2. +6 −1 gateway/gateway.go
  3. +1 −1 gateway/server_test.go
@@ -50,7 +50,7 @@ func (h *JSONLDHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {

m := http.NewServeMux()
m.HandleFunc("/forwarded", func(rw http.ResponseWriter, req *http.Request) {
fmt.Fprint(rw, "X-Forwarded-Host: "+req.Header.Get("X-Forwarded-Host")+"\nX-Forwarded-Proto: "+req.Header.Get("X-Forwarded-Proto"))
fmt.Fprint(rw, "X-Forwarded-Host: "+req.Header.Get("X-Forwarded-Host")+"\nX-Forwarded-Proto: "+req.Header.Get("X-Forwarded-Proto")+"\nX-Forwarded-For: "+req.Header.Get("X-Forwarded-For"))
})
m.HandleFunc("/books.jsonld", func(rw http.ResponseWriter, req *http.Request) {
fmt.Fprint(rw, BooksContent)
@@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httputil"
"net/url"
@@ -184,7 +185,11 @@ func (g *Gateway) ServeHTTP(rw http.ResponseWriter, req *http.Request) {

req.Header.Set("X-Forwarded-Proto", proto)
req.Header.Set("X-Forwarded-Host", req.Host)
req.Header.Set("X-Forwarded-For", req.RemoteAddr)
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
req.Header.Set("X-Forwarded-For", clientIP)
} else {
req.Header.Del("X-Forwarded-For")
}
rp.ServeHTTP(rw, req)
}

@@ -64,7 +64,7 @@ func TestForwardedHeaders(t *testing.T) {

b, _ := ioutil.ReadAll(resp.Body)

assert.Equal(t, "X-Forwarded-Host: 127.0.0.1:4343\nX-Forwarded-Proto: https", string(b))
assert.Equal(t, "X-Forwarded-Host: 127.0.0.1:4343\nX-Forwarded-Proto: https\nX-Forwarded-For: 127.0.0.1, 127.0.0.1", string(b))
_ = g.server.Shutdown(context.Background())
}

0 comments on commit 5a5e147

Please sign in to comment.
You can’t perform that action at this time.