-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrewriteheader.go
43 lines (37 loc) · 1.28 KB
/
rewriteheader.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
package traefik_plugin_rewriteheader
import (
"context"
"fmt"
"net/http"
"regexp"
)
// Config the plugin configuration.
type Config struct {
FromHead string `json:"fromhead,omitempty"` // target header
Regex string `json:"regex,omitempty"` // variable for creating a new header that will store data from the target header
Create string `json:"create,omitempty"` // creating a new header for store extracted data from the old
Prefix string `json:"prefix,omitempty"` // add prefix for a new header
}
// CreateConfig creates and initializes the plugin configuration.
func CreateConfig() *Config {
return &Config{}
}
// New creates and returns a plugin instance.
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if len(config.FromHead) == 0 {
return nil, fmt.Errorf("FromHead can't be empty")
}
re, err := regexp.Compile(config.Regex)
if err != nil {
return nil, fmt.Errorf("error compiling regex %q: %w", config.Regex, err)
}
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
head := req.Header.Get(config.FromHead)
result := re.FindString(head)
if config.Prefix != "" {
result = config.Prefix + result
}
req.Header.Set(config.Create, result)
next.ServeHTTP(rw, req)
}), nil
}