Skip to content

Commit

Permalink
Modified replace operation to use regexes in caddyfile
Browse files Browse the repository at this point in the history
  • Loading branch information
armadi1809 committed Mar 11, 2024
1 parent 2f31f58 commit 7f013d7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
2 changes: 1 addition & 1 deletion modules/caddyhttp/rewrite/caddyfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ func applyQueryOps(h httpcaddyfile.Helper, qo *queryOps, args []string) error {
qo.Rename = append(qo.Rename, queryOpsArguments{Key: renameValKey[0], Val: renameValKey[1]})

case len(args) == 3:
qo.Replace = append(qo.Replace, queryOpsReplacement{Key: key, Search: args[1], Replace: args[2]})
qo.Replace = append(qo.Replace, &queryOpsReplacement{Key: key, SearchRegexp: args[1], Replace: args[2]})

default:
if len(args) != 2 {
Expand Down
21 changes: 19 additions & 2 deletions modules/caddyhttp/rewrite/rewrite.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,12 @@ func (rewr *Rewrite) Provision(ctx caddy.Context) error {
rep.re = re
}

for _, replacementOp := range rewr.Query.Replace {
err := replacementOp.Provision(ctx)
if err != nil {
return fmt.Errorf("compiling regular expression %s in query rewrite replace operation: %v", replacementOp.SearchRegexp, err)
}
}
return nil
}

Expand Down Expand Up @@ -491,15 +497,26 @@ type queryOps struct {
Add []queryOpsArguments `json:"add,omitempty"`

// Replaces query parameters.
Replace []queryOpsReplacement
Replace []*queryOpsReplacement

// Deletes a given query key by name.
Delete []string `json:"delete,omitempty"`
}

// Provision compiles the query replace operation regex.
func (replacement *queryOpsReplacement) Provision(_ caddy.Context) error {
if replacement.SearchRegexp != "" {
re, err := regexp.Compile(replacement.SearchRegexp)
if err != nil {
return fmt.Errorf("replacement for query field '%s': %v", replacement.Key, err)
}
replacement.re = re
}
return nil
}

func (q *queryOps) do(r *http.Request, repl *caddy.Replacer) {
query := r.URL.Query()

for _, renameParam := range q.Rename {
key := repl.ReplaceAll(renameParam.Key, "")
val := repl.ReplaceAll(renameParam.Val, "")
Expand Down

0 comments on commit 7f013d7

Please sign in to comment.