Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

requestbody: Add replace for optional body replacement #5795

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions modules/caddyhttp/requestbody/caddyfile.go
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
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"`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would need a helpful godoc comment on this field.

}

// 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))
Comment on lines +47 to +48
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're completely replacing the request body, we miiiight want to call r.Body.Close() before re-assigning a new body. Yes the std lib will close it for us when the request is over, but would closing it early (and releasing those resources) cause any problems?

Also, I wonder if we should add placeholder support and expand those when doing the body replacement.

r.ContentLength = int64(len(rb.Replace))
}
if r.Body == nil {
return next.ServeHTTP(w, r)
}
Expand Down