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

requestbody: Add replace for optional body replacement #5795

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
8 changes: 7 additions & 1 deletion modules/caddyhttp/requestbody/caddyfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,14 @@ 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())
return nil, h.Errf("unrecognized set_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 @@ -17,6 +17,7 @@ package requestbody
import (
"io"
"net/http"
"strings"
"time"

"go.uber.org/zap"
Expand All @@ -41,6 +42,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 @@ -58,6 +61,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