Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 12, 02:00 UTC
requestbody: Add set option to replace request body (#5795)
Co-authored-by: Matt Holt <mholt@users.noreply.github.com>
Adrien Pensart committed
Mar 12, 2025 at 15:38 UTC
dccf3d8982d1b428e840d43f71fa5c3becf6ea8f
2 files changed
+23
modules/caddyhttp/requestbody/caddyfile.go
+6
@@ -68,6 +68,12 @@ func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error)
68
}
69
rb.WriteTimeout = timeout
70
71
+ case "set":
72
+ var setStr string
73
+ if !h.AllArgs(&setStr) {
74
+ return nil, h.ArgErr()
75
+ }
76
+ rb.Set = setStr
77
default:
78
return nil, h.Errf("unrecognized request_body subdirective '%s'", h.Val())
79
}
modules/caddyhttp/requestbody/requestbody.go
+17
@@ -18,6 +18,7 @@ import (
18
"errors"
19
"io"
20
"net/http"
21
+ "strings"
22
"time"
23
24
"go.uber.org/zap"
@@ -43,6 +44,10 @@ type RequestBody struct {
44
// EXPERIMENTAL. Subject to change/removal.
45
WriteTimeout time.Duration `json:"write_timeout,omitempty"`
46
47
+ // This field permit to replace body on the fly
48
+ // EXPERIMENTAL. Subject to change/removal.
49
+ Set string `json:"set,omitempty"`
50
+
51
logger *zap.Logger
52
}
53
@@ -60,6 +65,18 @@ func (rb *RequestBody) Provision(ctx caddy.Context) error {
65
}
66
67
func (rb RequestBody) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
68
+ if rb.Set != "" {
69
+ if r.Body != nil {
70
+ err := r.Body.Close()
71
+ if err != nil {
72
+ return err
73
+ }
74
+ }
75
+ repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
76
+ replacedBody := repl.ReplaceAll(rb.Set, "")
77
+ r.Body = io.NopCloser(strings.NewReader(replacedBody))
78
+ r.ContentLength = int64(len(rb.Set))
79
+ }
80
if r.Body == nil {
81
return next.ServeHTTP(w, r)
82
}