From a449c161761f7f8012a72fcc149196657e5c76cf Mon Sep 17 00:00:00 2001 From: Adrien Pensart Date: Mon, 4 Sep 2023 12:57:09 +0000 Subject: [PATCH] Add: request_body replace directive --- modules/caddyhttp/requestbody/caddyfile.go | 6 ++++++ modules/caddyhttp/requestbody/requestbody.go | 8 +++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/modules/caddyhttp/requestbody/caddyfile.go b/modules/caddyhttp/requestbody/caddyfile.go index 8a92909fb19d..6c9c56aa920d 100644 --- a/modules/caddyhttp/requestbody/caddyfile.go +++ b/modules/caddyhttp/requestbody/caddyfile.go @@ -42,6 +42,12 @@ func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) return nil, h.Errf("parsing max_size: %v", err) } rb.MaxSize = int64(size) + case "replace": + var replaceStr string + if !h.AllArgs(&replaceStr) { + return nil, h.ArgErr() + } + rb.Replace = replaceStr default: return nil, h.Errf("unrecognized servers option '%s'", h.Val()) } diff --git a/modules/caddyhttp/requestbody/requestbody.go b/modules/caddyhttp/requestbody/requestbody.go index dfc0fd92891b..eebeb153b9e3 100644 --- a/modules/caddyhttp/requestbody/requestbody.go +++ b/modules/caddyhttp/requestbody/requestbody.go @@ -17,6 +17,7 @@ package requestbody import ( "io" "net/http" + "strings" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" @@ -30,7 +31,8 @@ func init() { type RequestBody struct { // The maximum number of bytes to allow reading from the body by a later handler. // If more bytes are read, an error with HTTP status 413 is returned. - MaxSize int64 `json:"max_size,omitempty"` + MaxSize int64 `json:"max_size,omitempty"` + Replace string `json:"replace,omitempty"` } // CaddyModule returns the Caddy module information. @@ -42,6 +44,10 @@ func (RequestBody) CaddyModule() caddy.ModuleInfo { } func (rb RequestBody) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { + if rb.Replace != "" { + r.Body = io.NopCloser(strings.NewReader(rb.Replace)) + r.ContentLength = int64(len(rb.Replace)) + } if r.Body == nil { return next.ServeHTTP(w, r) }