I've made an http middleware that uses http.MaxBytesReader to limit the 
accepted size of requests.

The middleware is as follows:

    func bodyLimitMiddleware(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            r.Body = http.MaxBytesReader(w, r.Body, 1<<2) // example limited 
size
            next.ServeHTTP(w, r)
        })
    }

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. 

For example the test below fails with a 200 status, as shown at 
https://go.dev/play/p/bcU20WP9Op0.

Advice gratefully received.

    func TestBodyLimit(t *testing.T) {
        r := httptest.NewRequest(http.MethodPost, "http://www.example.com/";, 
strings.NewReader(bodyMaker(1<<3)))
        w := httptest.NewRecorder()
        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)
                }
            }
        })
        bodyLimitMiddleware(testHandler).ServeHTTP(w, r)
        if got, want := w.Result().StatusCode, 
http.StatusRequestEntityTooLarge; got != want {
            t.Fatalf("bad status: got %v want %v", got, want)
        }
    }

-- 
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/ZO5YoHWGg6H5/DFO%40campbell-lange.net.

Reply via email to