mirror of
https://github.com/kemko/reproxy.git
synced 2026-01-06 18:25:49 +03:00
add X-Real-IP to proxied request
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user