Skip to content

Commit

Permalink
Add: request_body replace directive
Browse files Browse the repository at this point in the history
  • Loading branch information
AdrienPensart committed Dec 8, 2024
1 parent 57ae9c3 commit 03175f0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
6 changes: 6 additions & 0 deletions modules/caddyhttp/requestbody/caddyfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error)
}
rb.WriteTimeout = timeout

case "set":
var setStr string
if !h.AllArgs(&setStr) {
return nil, h.ArgErr()
}
rb.Set = setStr
default:
return nil, h.Errf("unrecognized request_body subdirective '%s'", h.Val())
}
Expand Down
13 changes: 13 additions & 0 deletions modules/caddyhttp/requestbody/requestbody.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"errors"
"io"
"net/http"
"strings"
"time"

"go.uber.org/zap"
Expand All @@ -43,6 +44,8 @@ type RequestBody struct {
// EXPERIMENTAL. Subject to change/removal.
WriteTimeout time.Duration `json:"write_timeout,omitempty"`

Set string `json:"set,omitempty"`

logger *zap.Logger
}

Expand All @@ -60,6 +63,16 @@ func (rb *RequestBody) Provision(ctx caddy.Context) error {
}

func (rb RequestBody) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
if rb.Set != "" {
err := r.Body.Close()
if err != nil {
return err
}
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
replacedBody := repl.ReplaceAll(rb.Set, "")
r.Body = io.NopCloser(strings.NewReader(replacedBody))
r.ContentLength = int64(len(rb.Set))
}
if r.Body == nil {
return next.ServeHTTP(w, r)
}
Expand Down

0 comments on commit 03175f0

Please sign in to comment.