On 29/08/23, Nagaev Boris ([email protected]) wrote:
> On Tue, Aug 29, 2023 at 5:44 PM Rory Campbell-Lange
> <[email protected]> wrote:
> >
> > I've made an http middleware that uses http.MaxBytesReader to limit the
> > accepted size of requests.
...
> > It seems sensible to send a 413 status code to any clients transgressing
> > limits. However I can't find a way of raising an
> > http.StatusRequestEntityTooLarge either from the middleware or from any
> > http endpoint handler.
...
> > testHandler := http.HandlerFunc(func(w http.ResponseWriter, ri
> > *http.Request) {
> > _, err := io.Copy(w, ri.Body)
> > if err != nil {
> > e := new(http.MaxBytesError)
> > if errors.As(err, &e) {
> > w.WriteHeader(http.StatusRequestEntityTooLarge)
> > } else {
> > t.Fatal(err)
> > }
> > }
> > })
> HTTP status is sent before the body, that is why you can not set HTTP
> status in response after you start writing the body in io.Copy(w, ...)
> call. Writes to w resulted in HTTP status and headers being sent.
Hi Boris
Thanks very much for your help.
I changed the testHander as follows to create a temporary buffer to set the 413
status header before writing the body (as you suggested) and the test passed.
(https://go.dev/play/p/Ur7RTDIBMf0). Thanks!
testHandler := http.HandlerFunc(func(w http.ResponseWriter, ri
*http.Request) {
buf := bytes.Buffer{}
_, err := io.Copy(&buf, ri.Body)
if err != nil {
e := new(http.MaxBytesError)
if errors.As(err, &e) {
w.WriteHeader(http.StatusRequestEntityTooLarge)
} else {
t.Fatal(err)
}
}
buf.WriteTo(w)
})
Cheers,
Rory
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/ZO7Gxz2bIAuZfYzH%40campbell-lange.net.