-
Notifications
You must be signed in to change notification settings - Fork 1
/
rewrite.go
51 lines (43 loc) · 1.43 KB
/
rewrite.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package forward
import (
"net"
"net/http"
"strings"
"gopkg.in/vinxi/utils.v0"
)
// HeaderRewriter is responsible for removing hop-by-hop headers and setting forwarding headers.
type HeaderRewriter struct {
TrustForwardHeader bool
Hostname string
}
// Rewrite rewrites the given request removing hop-by-hop headers and setting forwarding headers.
func (rw *HeaderRewriter) Rewrite(req *http.Request) {
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
if rw.TrustForwardHeader {
if prior, ok := req.Header[XForwardedFor]; ok {
clientIP = strings.Join(prior, ", ") + ", " + clientIP
}
}
req.Header.Set(XForwardedFor, clientIP)
}
if xfp := req.Header.Get(XForwardedProto); xfp != "" && rw.TrustForwardHeader {
req.Header.Set(XForwardedProto, xfp)
} else if req.TLS != nil {
req.Header.Set(XForwardedProto, "https")
} else {
req.Header.Set(XForwardedProto, "http")
}
if xfh := req.Header.Get(XForwardedHost); xfh != "" && rw.TrustForwardHeader {
req.Header.Set(XForwardedHost, xfh)
} else if req.Host != "" {
req.Header.Set(XForwardedHost, req.Host)
}
if rw.Hostname != "" {
req.Header.Set(XForwardedServer, rw.Hostname)
}
// Remove hop-by-hop headers to the backend.
// Especially important is "Connection" because we want a persistent
// connection, regardless of what the client sent to us.
// fmt.Printf(">> %#v \n", req.Header)
utils.RemoveHeaders(req.Header, HopHeaders...)
}