mirror of
https://github.com/caddyserver/caddy.git
synced 2026-01-16 17:20:34 +00:00
Rework Replacer loop to handle escaped braces (#3121)
Fixes #3116 * Rework Replacer loop to ignore escaped braces * Add benchmark tests for replacer * Optimise handling of escaped braces * Handle escaped closing braces * Remove additional check for closing brace This commit removes the additional check for input in which the closing brace appears before the opening brace. This check has been removed for performance reasons as it is deemed an unlikely edge case. * Check for escaped closing braces in placeholder name
This commit is contained in:
15
replacer.go
15
replacer.go
@@ -125,6 +125,14 @@ func (r *Replacer) replace(input, empty string,
|
||||
// iterate the input to find each placeholder
|
||||
var lastWriteCursor int
|
||||
for i := 0; i < len(input); i++ {
|
||||
|
||||
// check for escaped braces
|
||||
if i > 0 && input[i-1] == phEscape && (input[i] == phClose || input[i] == phOpen) {
|
||||
sb.WriteString(input[lastWriteCursor : i-1])
|
||||
lastWriteCursor = i
|
||||
continue
|
||||
}
|
||||
|
||||
if input[i] != phOpen {
|
||||
continue
|
||||
}
|
||||
@@ -135,6 +143,11 @@ func (r *Replacer) replace(input, empty string,
|
||||
continue
|
||||
}
|
||||
|
||||
// if necessary look for the first closing brace that is not escaped
|
||||
for end > 0 && end < len(input)-1 && input[end-1] == phEscape {
|
||||
end = strings.Index(input[end+1:], string(phClose)) + end + 1
|
||||
}
|
||||
|
||||
// write the substring from the last cursor to this point
|
||||
sb.WriteString(input[lastWriteCursor:i])
|
||||
|
||||
@@ -237,4 +250,4 @@ var nowFunc = time.Now
|
||||
// ReplacerCtxKey is the context key for a replacer.
|
||||
const ReplacerCtxKey CtxKey = "replacer"
|
||||
|
||||
const phOpen, phClose = '{', '}'
|
||||
const phOpen, phClose, phEscape = '{', '}', '\\'
|
||||
|
||||
Reference in New Issue
Block a user