Skip to content

Commit

Permalink
Add: request_body replace directive
Browse files Browse the repository at this point in the history
  • Loading branch information
Adrien Pensart committed Sep 4, 2023
1 parent 1b73e38 commit 618ce28
Show file tree
Hide file tree
Showing 2 changed files with 12 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 @@ -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())
}
Expand Down
6 changes: 6 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"

"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
Expand All @@ -31,6 +32,7 @@ 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"`
Replace string `json:"replace,omitempty"`
}

// CaddyModule returns the Caddy module information.
Expand All @@ -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)
}
Expand Down

0 comments on commit 618ce28

Please sign in to comment.