-
Notifications
You must be signed in to change notification settings - Fork 1
/
reformatheader.go
40 lines (34 loc) · 1.25 KB
/
reformatheader.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
package traefik_plugin_reformatheader
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
Format string `json:"format,omitempty"` // transform captured data on the 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.ReplaceAllString(head, config.Format)
req.Header.Set(config.Create, result)
next.ServeHTTP(rw, req)
}), nil
}