-
Notifications
You must be signed in to change notification settings - Fork 1
/
convertxff.go
69 lines (54 loc) · 1.43 KB
/
convertxff.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package traefik_convertxff
import (
"context"
"net/http"
"net/netip"
"strings"
)
const (
XFF = "X-Forwarded-For"
)
type Config struct{}
// CreateConfig creates and initializes the plugin configuration.
func CreateConfig() *Config {
return &Config{}
}
// ConvertXFF holds the necessary components of a Traefik plugin
type ConvertXFF struct {
next http.Handler
name string
}
// New instantiates and returns the required components used to handle a HTTP request
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
return &ConvertXFF{
next: next,
name: name,
}, nil
}
// ServeHTTP removes the brackets from IPv6 addresses and rewrites ipv6 mapped ipv4 to real ipv4
func (u *ConvertXFF) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
header := req.Header.Get(XFF)
req.Header.Del(XFF)
header = strings.ReplaceAll(header, "[", "")
header = strings.ReplaceAll(header, "]", "")
var ips []string
if strings.Contains(header, ",") {
for _, entry := range strings.Split(header, ",") {
entry = strings.TrimSpace(entry)
if !strings.HasPrefix(entry, "::ffff") {
ips = append(ips, entry)
continue
}
parsed, err := netip.ParseAddr(entry)
if err != nil {
ips = append(ips, entry)
continue
}
ips = append(ips, parsed.Unmap().String())
}
} else {
ips = append(ips, header)
}
req.Header.Add(XFF, strings.Join(ips, ","))
u.next.ServeHTTP(rw, req)
}