Skip to content

Commit

Permalink
perf: improve try_files matcher
Browse files Browse the repository at this point in the history
  • Loading branch information
dunglas committed Nov 24, 2024
1 parent 1d106fa commit ebf5370
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 8 deletions.
27 changes: 19 additions & 8 deletions modules/caddyhttp/fileserver/matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -416,15 +416,26 @@ func (m MatchFile) selectFile(r *http.Request) (bool, error) {

// setPlaceholders creates the placeholders for the matched file
setPlaceholders := func(candidate matchCandidate, info fs.FileInfo) {
repl.Set("http.matchers.file.relative", filepath.ToSlash(candidate.relative))
repl.Set("http.matchers.file.absolute", filepath.ToSlash(candidate.fullpath))
repl.Set("http.matchers.file.remainder", filepath.ToSlash(candidate.splitRemainder))
isDir := info.IsDir()
repl.Map(func(key string) (any, bool) {
switch key {
case "http.matchers.file.relative":
return filepath.ToSlash(candidate.relative), true
case "http.matchers.file.absolute":
return filepath.ToSlash(candidate.fullpath), true
case "http.matchers.file.remainder":
return filepath.ToSlash(candidate.splitRemainder), true
case "http.matchers.file.type":
if isDir {
return "directory", true
}

fileType := "file"
if info.IsDir() {
fileType = "directory"
}
repl.Set("http.matchers.file.type", fileType)
return "file", true

default:
return nil, false
}
})
}

// match file according to the configured policy
Expand Down
21 changes: 21 additions & 0 deletions modules/caddyhttp/fileserver/matcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -416,3 +416,24 @@ func TestMatchExpressionMatch(t *testing.T) {
})
}
}

func BenchmarkFileMatcher(b *testing.B) {
m := &MatchFile{
fsmap: &filesystems.FilesystemMap{},
Root: "./testdata",
TryFiles: []string{"{http.request.uri.path}"},
}

u, _ := url.Parse("/foo.txt")
req := &http.Request{URL: u}
caddyhttp.NewTestReplacer(req)

b.ResetTimer()

for i := 0; i < b.N; i++ {
ok, _ := m.MatchWithError(req)
if !ok {
panic("unexpected match result")
}
}
}

0 comments on commit ebf5370

Please sign in to comment.