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

caddyhttp: performance improvement in Regex Match #4143

Merged
merged 1 commit into from
May 2, 2021
Merged
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
5 changes: 3 additions & 2 deletions modules/caddyhttp/matchers.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"

"github.com/caddyserver/caddy/v2"
Expand Down Expand Up @@ -935,14 +936,14 @@ func (mre *MatchRegexp) Match(input string, repl *caddy.Replacer) bool {

// save all capture groups, first by index
for i, match := range matches {
key := fmt.Sprintf("%s.%d", mre.phPrefix, i)
key := mre.phPrefix + "." + strconv.Itoa(i)
repl.Set(key, match)
}

// then by name
for i, name := range mre.compiled.SubexpNames() {
if i != 0 && name != "" {
key := fmt.Sprintf("%s.%s", mre.phPrefix, name)
key := mre.phPrefix + "." + name
repl.Set(key, matches[i])
}
}
Expand Down
26 changes: 26 additions & 0 deletions modules/caddyhttp/matchers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,32 @@ func TestHeaderREMatcher(t *testing.T) {
}
}

func BenchmarkHeaderREMatcher(b *testing.B) {

i := 0
match := MatchHeaderRE{"Field": &MatchRegexp{Pattern: "^foo(.*)$", Name: "name"}}
input := http.Header{"Field": []string{"foobar"}}
var host string
err := match.Provision(caddy.Context{})
if err != nil {
b.Errorf("Test %d %v: Provisioning: %v", i, match, err)
}
err = match.Validate()
if err != nil {
b.Errorf("Test %d %v: Validating: %v", i, match, err)
}

// set up the fake request and its Replacer
req := &http.Request{Header: input, URL: new(url.URL), Host: host}
repl := caddy.NewReplacer()
ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
req = req.WithContext(ctx)
addHTTPVarsToReplacer(repl, req, httptest.NewRecorder())
for run := 0; run < b.N; run++ {
match.Match(req)
}
}

func TestVarREMatcher(t *testing.T) {
for i, tc := range []struct {
desc string
Expand Down