Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: replace with dynamic vars #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .traefik.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,9 @@ testData:
rewrites:
- regex: "bar"
replacement: "foo"
- regex: "foo"
replacement: "{.Host}"
- regex: "bar"
replacement: "/.Host/"
delimiterLeft: "/"
delimiterRight: "/"
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ by replacing a search regex by a replacement string.

To configure the `Rewrite Body` plugin you should create a [middleware](https://docs.traefik.io/middlewares/overview/) in
your dynamic configuration as explained [here](https://docs.traefik.io/middlewares/overview/). The following example creates
and uses the `rewritebody` middleware plugin to replace all foo occurences by bar in the HTTP response body.
and uses the `rewritebody` middleware plugin to replace all foo occurences by bar in the HTTP response body.`

You can replace with variables from the `http.Request` variable. For example to get the `req.Host` variable use `{.Host}` in your
replacement string. You can change the delimiter to use something different that the brackets. See examples for more information.

If you want to apply some limits on the response body, you can chain this middleware plugin with the [Buffering middleware](https://docs.traefik.io/middlewares/buffering/) from Traefik.

Expand All @@ -42,6 +45,18 @@ If you want to apply some limits on the response body, you can chain this middle
regex = "foo"
replacement = "bar"

# Rewrites all "bar" occurences by the host requested
[[http.middlewares.rewrite-foo.plugin.rewritebody.rewrites]]
regex = "bar"
replacement = "{.Host}"

# Rewrites all "example.com" occurences by the Method requested and by changing the delimiters
[[http.middlewares.rewrite-foo.plugin.rewritebody.rewrites]]
regex = "example.com"
replacement = "/.Method/"
delimiterLeft = "/"
delimiterRight = "/"

[http.services]
[http.services.my-service]
[http.services.my-service.loadBalancer]
Expand Down
41 changes: 34 additions & 7 deletions rewritebody.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"bytes"
"context"
"fmt"
"html/template"
"log"
"net"
"net/http"
Expand All @@ -14,8 +15,10 @@ import (

// Rewrite holds one rewrite body configuration.
type Rewrite struct {
Regex string `json:"regex,omitempty"`
Replacement string `json:"replacement,omitempty"`
Regex string `json:"regex,omitempty"`
Replacement string `json:"replacement,omitempty"`
DelimiterLeft string `json:"delimiterLeft,omitempty"`
DelimiterRight string `json:"delimiterRight,omitempty"`
}

// Config holds the plugin configuration.
Expand All @@ -30,8 +33,10 @@ func CreateConfig() *Config {
}

type rewrite struct {
regex *regexp.Regexp
replacement []byte
regex *regexp.Regexp
replacement string
delimiterLeft string
delimiterRight string
}

type rewriteBody struct {
Expand All @@ -51,9 +56,19 @@ func New(_ context.Context, next http.Handler, config *Config, name string) (htt
return nil, fmt.Errorf("error compiling regex %q: %w", rewriteConfig.Regex, err)
}

if rewriteConfig.DelimiterLeft == "" {
rewriteConfig.DelimiterLeft = "{"
}

if rewriteConfig.DelimiterRight == "" {
rewriteConfig.DelimiterRight = "}"
}

rewrites[i] = rewrite{
regex: regex,
replacement: []byte(rewriteConfig.Replacement),
regex: regex,
replacement: rewriteConfig.Replacement,
delimiterLeft: rewriteConfig.DelimiterLeft,
delimiterRight: rewriteConfig.DelimiterRight,
}
}

Expand Down Expand Up @@ -86,7 +101,19 @@ func (r *rewriteBody) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
}

for _, rewrite := range r.rewrites {
bodyBytes = rewrite.regex.ReplaceAll(bodyBytes, rewrite.replacement)
tpl, err := template.New("replace").Delims(rewrite.delimiterLeft, rewrite.delimiterRight).Parse(rewrite.replacement)
if err != nil {
return
}

var buf bytes.Buffer

err = tpl.Execute(&buf, req)
if err != nil {
return
}

bodyBytes = rewrite.regex.ReplaceAll(bodyBytes, buf.Bytes())
}

if _, err := rw.Write(bodyBytes); err != nil {
Expand Down
75 changes: 75 additions & 0 deletions rewritebody_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,65 @@ func TestServeHTTP(t *testing.T) {
expResBody: "bar is the new bar",
expLastModified: true,
},
{
desc: "should replace foo by the req.Host var",
rewrites: []Rewrite{
{
Regex: "foo",
Replacement: "{.Host}",
},
},
resBody: "foo is the new bar",
expResBody: "example.com is the new bar",
},
{
desc: "should replace foo by the req.Proto/req.Method vars",
rewrites: []Rewrite{
{
Regex: "foo",
Replacement: "{.ContentLength} {.Method}",
},
},
resBody: "foo is the new bar",
expResBody: "0 GET is the new bar",
},
{
desc: "should replace foo by {}",
rewrites: []Rewrite{
{
Regex: "foo",
Replacement: "{}",
DelimiterLeft: "/",
DelimiterRight: "/",
},
},
resBody: "foo is the new bar",
expResBody: "{} is the new bar",
},
{
desc: "should replace foo by Host with delimiters /",
rewrites: []Rewrite{
{
Regex: "foo",
Replacement: "/.Host/",
DelimiterLeft: "/",
DelimiterRight: "/",
},
},
resBody: "foo is {the} new bar",
expResBody: "example.com is {the} new bar",
},
{
desc: "Replacement with unavailable var should return nothing",
rewrites: []Rewrite{
{
Regex: "foo",
Replacement: "{.Toto}",
},
},
resBody: "foo is the new bar",
expResBody: "",
},
}

for _, test := range tests {
Expand Down Expand Up @@ -147,6 +206,22 @@ func TestNew(t *testing.T) {
},
expErr: false,
},
{
desc: "should return no error when adding delimiters",
rewrites: []Rewrite{
{
Regex: "foo",
Replacement: "bar",
DelimiterLeft: "/",
DelimiterRight: "/",
},
{
Regex: "bar",
Replacement: "foo",
},
},
expErr: false,
},
{
desc: "should return an error",
rewrites: []Rewrite{
Expand Down