From 4e28e6999710feaf8d28b86b9d274f9d006652df Mon Sep 17 00:00:00 2001 From: Umputun Date: Sun, 4 Apr 2021 02:57:34 -0500 Subject: [PATCH] add X-Real-IP to proxied request --- app/proxy/proxy.go | 16 ++++++++++++++++ app/proxy/proxy_test.go | 5 ++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/app/proxy/proxy.go b/app/proxy/proxy.go index dd68dc3..1021795 100644 --- a/app/proxy/proxy.go +++ b/app/proxy/proxy.go @@ -2,6 +2,7 @@ package proxy import ( "context" + "net" "net/http" "net/http/httputil" "net/url" @@ -142,6 +143,7 @@ func (h *Http) proxyHandler() http.HandlerFunc { r.URL.Scheme = uu.Scheme r.Header.Add("X-Forwarded-Host", uu.Host) r.Header.Add("X-Origin-Host", r.Host) + h.setXRealIP(r) }, } @@ -196,3 +198,17 @@ func (h *Http) makeHTTPServer(addr string, router http.Handler) *http.Server { IdleTimeout: 30 * time.Second, } } + +func (h *Http) setXRealIP(r *http.Request) { + + ip, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return + } + + userIP := net.ParseIP(ip) + if userIP == nil { + return + } + r.Header.Add("X-Real-IP", ip) +} diff --git a/app/proxy/proxy_test.go b/app/proxy/proxy_test.go index 14b8d3c..4593c82 100644 --- a/app/proxy/proxy_test.go +++ b/app/proxy/proxy_test.go @@ -27,6 +27,7 @@ func TestHttp_Do(t *testing.T) { ds := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Logf("req: %v", r) w.Header().Add("h1", "v1") + require.Equal(t, "127.0.0.1", r.Header.Get("X-Real-IP")) fmt.Fprintf(w, "response %s", r.URL.String()) })) @@ -50,7 +51,9 @@ func TestHttp_Do(t *testing.T) { client := http.Client{} { - resp, err := client.Get("http://127.0.0.1:" + strconv.Itoa(port) + "/api/something") + req, err := http.NewRequest("GET", "http://127.0.0.1:"+strconv.Itoa(port)+"/api/something", nil) + require.NoError(t, err) + resp, err := client.Do(req) require.NoError(t, err) defer resp.Body.Close() assert.Equal(t, http.StatusOK, resp.StatusCode)