generated from traefik/plugindemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
67 lines (56 loc) · 1.63 KB
/
plugin.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
// Package plugin contains the Traefik plugin for adding headers based on the
// [net/http.Request.RemoteAddr] field.
package plugin
import (
"context"
"errors"
"net/http"
"strings"
)
var errMissingHeaderConfig = errors.New("missing header config: must set at least one of headers.port, headers.ip, or headers.address")
// Config the plugin configuration.
type Config struct {
Headers ConfigHeaders `json:"headers,omitempty"`
}
// ConfigHeaders defines the headers to use for the different values.
type ConfigHeaders struct {
Port string `json:"port,omitempty"`
IP string `json:"ip,omitempty"`
Address string `json:"address,omitempty"`
}
// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
return &Config{
Headers: ConfigHeaders{},
}
}
// RemoteAddrPlugin is the main handler model for this Traefik plugin.
type RemoteAddrPlugin struct {
next http.Handler
headers ConfigHeaders
name string
}
// New created a new RemoteAddrPlugin.
func New(_ context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if config.Headers == (ConfigHeaders{}) {
return nil, errMissingHeaderConfig
}
return &RemoteAddrPlugin{
headers: config.Headers,
next: next,
name: name,
}, nil
}
func (a *RemoteAddrPlugin) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
ip, port, _ := strings.Cut(req.RemoteAddr, ":")
if a.headers.IP != "" {
req.Header.Set(a.headers.IP, ip)
}
if a.headers.Port != "" {
req.Header.Set(a.headers.Port, port)
}
if a.headers.Address != "" {
req.Header.Set(a.headers.Address, req.RemoteAddr)
}
a.next.ServeHTTP(rw, req)
}