-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreal_ip.go
59 lines (48 loc) · 1.42 KB
/
real_ip.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
package traefikrealip
import (
"context"
"net/http"
"strings"
)
const (
xRealIP = "X-Real-Ip"
xForwardedFor = "X-Forwarded-For"
)
// Config the plugin configuration.
type Config struct {
ForwardedForDepth int `json:"forwardedForDepth,omitempty" toml:"forwardedForDepth,omitempty" yaml:"forwardedForDepth,omitempty"`
}
// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
return &Config{
ForwardedForDepth: 1, // Default depth if not provided
}
}
// RealIPOverWriter is a plugin that extracts real IP from X-Forwarded-For header.
type RealIPOverWriter struct {
next http.Handler
name string
ForwardedForDepth int
}
// New creates a new RealIPOverWriter plugin.
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
ipOverWriter := &RealIPOverWriter{
next: next,
name: name,
ForwardedForDepth: config.ForwardedForDepth,
}
return ipOverWriter, nil
}
func (r *RealIPOverWriter) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
forwardedIPs := strings.Split(req.Header.Get(xForwardedFor), ",")
// Determine the index to use based on ForwardedForDepth
index := len(forwardedIPs) - r.ForwardedForDepth
if index < 0 {
index = 0
}
trimmedIP := strings.TrimSpace(forwardedIPs[index])
if trimmedIP != "" {
req.Header.Set(xRealIP, trimmedIP)
}
r.next.ServeHTTP(rw, req)
}