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 May 31, 2024
1 parent 40c582c commit 4a1cba4
Show file tree
Hide file tree
Showing 2 changed files with 17 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 "replace":
var replaceStr string
if !h.AllArgs(&replaceStr) {
return nil, h.ArgErr()
}
rb.Replace = replaceStr
default:
return nil, h.Errf("unrecognized request_body subdirective '%s'", h.Val())
}
Expand Down
11 changes: 11 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"`

Replace string `json:"replace,omitempty"`

logger *zap.Logger
}

Expand All @@ -58,6 +61,14 @@ func (rb *RequestBody) Provision(ctx caddy.Context) error {
}

func (rb RequestBody) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
if rb.Replace != "" {
err := r.Body.Close()
if err != nil {
return err
}
r.Body = io.NopCloser(strings.NewReader(rb.Replace))
r.ContentLength = int64(len(rb.Replace))
}
if r.Body == nil {
return next.ServeHTTP(w, r)
}
Expand Down

0 comments on commit 4a1cba4

Please sign in to comment.