traefik/server/header_rewriter.go

61 lines
1.3 KiB
Go
Raw Normal View History

2017-10-16 10:46:03 +00:00
package server
import (
"net"
"net/http"
"os"
2017-12-04 19:04:08 +00:00
"github.com/containous/traefik/log"
2017-10-16 10:46:03 +00:00
"github.com/containous/traefik/whitelist"
"github.com/vulcand/oxy/forward"
)
// NewHeaderRewriter Create a header rewriter
func NewHeaderRewriter(trustedIPs []string, insecure bool) (forward.ReqRewriter, error) {
IPs, err := whitelist.NewIP(trustedIPs, insecure)
if err != nil {
return nil, err
}
h, err := os.Hostname()
if err != nil {
h = "localhost"
}
return &headerRewriter{
secureRewriter: &forward.HeaderRewriter{TrustForwardHeader: true, Hostname: h},
insecureRewriter: &forward.HeaderRewriter{TrustForwardHeader: false, Hostname: h},
ips: IPs,
insecure: insecure,
}, nil
}
type headerRewriter struct {
secureRewriter forward.ReqRewriter
insecureRewriter forward.ReqRewriter
insecure bool
ips *whitelist.IP
}
func (h *headerRewriter) Rewrite(req *http.Request) {
clientIP, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
2017-12-04 19:04:08 +00:00
log.Error(err)
2017-10-16 10:46:03 +00:00
h.secureRewriter.Rewrite(req)
2017-12-04 19:04:08 +00:00
return
2017-10-16 10:46:03 +00:00
}
authorized, _, err := h.ips.Contains(clientIP)
2017-12-04 19:04:08 +00:00
if err != nil {
log.Error(err)
h.secureRewriter.Rewrite(req)
return
}
2017-10-16 10:46:03 +00:00
if h.insecure || authorized {
h.secureRewriter.Rewrite(req)
} else {
h.insecureRewriter.Rewrite(req)
}
}