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 Sep 13, 2023
1 parent 1e0dea5 commit a449c16
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
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
8 changes: 7 additions & 1 deletion 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 @@ -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.
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 a449c16

Please sign in to comment.