mirror of
https://github.com/caddyserver/caddy.git
synced 2025-03-13 17:18:50 +01:00
requestbody: Add set option to replace request body (#5795)
Co-authored-by: Matt Holt <mholt@users.noreply.github.com>
This commit is contained in:
parent
af2d33afbb
commit
dccf3d8982
2 changed files with 23 additions and 0 deletions
|
@ -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())
|
||||
}
|
||||
|
|
|
@ -18,6 +18,7 @@ import (
|
|||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
@ -43,6 +44,10 @@ type RequestBody struct {
|
|||
// EXPERIMENTAL. Subject to change/removal.
|
||||
WriteTimeout time.Duration `json:"write_timeout,omitempty"`
|
||||
|
||||
// This field permit to replace body on the fly
|
||||
// EXPERIMENTAL. Subject to change/removal.
|
||||
Set string `json:"set,omitempty"`
|
||||
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
|
@ -60,6 +65,18 @@ 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 != "" {
|
||||
if r.Body != nil {
|
||||
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)
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue