set HTTP_X_FORWARDED_FOR when proxying

https://github.com/chrislusf/seaweedfs/issues/214
This commit is contained in:
chrislusf 2015-11-22 09:31:39 -08:00
parent dcb8215482
commit 70d050416b
2 changed files with 24 additions and 1 deletions

View File

@ -6,6 +6,7 @@ import (
"net" "net"
"net/http" "net/http"
"regexp" "regexp"
"strings"
"github.com/chrislusf/seaweedfs/go/glog" "github.com/chrislusf/seaweedfs/go/glog"
) )
@ -81,12 +82,26 @@ func (g *Guard) Secure(f func(w http.ResponseWriter, r *http.Request)) func(w ht
} }
} }
func GetActualRemoteHost(r *http.Request) (host string, err error) {
host = r.Header.Get("HTTP_X_FORWARDED_FOR")
if host == "" {
host = r.Header.Get("X-FORWARDED-FOR")
}
if strings.Contains(host, ",") {
host = host[0:strings.Index(host, ",")]
}
if host == "" {
host, _, err = net.SplitHostPort(r.RemoteAddr)
}
return
}
func (g *Guard) checkWhiteList(w http.ResponseWriter, r *http.Request) error { func (g *Guard) checkWhiteList(w http.ResponseWriter, r *http.Request) error {
if len(g.whiteList) == 0 { if len(g.whiteList) == 0 {
return nil return nil
} }
host, _, err := net.SplitHostPort(r.RemoteAddr) host, err := GetActualRemoteHost(r)
if err == nil { if err == nil {
for _, ip := range g.whiteList { for _, ip := range g.whiteList {

View File

@ -113,6 +113,14 @@ func (ms *MasterServer) proxyToLeader(f func(w http.ResponseWriter, r *http.Requ
} }
glog.V(4).Infoln("proxying to leader", ms.Topo.RaftServer.Leader()) glog.V(4).Infoln("proxying to leader", ms.Topo.RaftServer.Leader())
proxy := httputil.NewSingleHostReverseProxy(targetUrl) proxy := httputil.NewSingleHostReverseProxy(targetUrl)
director := proxy.Director
proxy.Director = func(req *http.Request) {
actualHost, err := security.GetActualRemoteHost(req)
if err == nil {
req.Header.Set(("HTTP_X_FORWARDED_FOR", actualHost)
}
director(req)
}
proxy.Transport = util.Transport proxy.Transport = util.Transport
proxy.ServeHTTP(w, r) proxy.ServeHTTP(w, r)
} else { } else {