Is there a way to capture the error by "http.MaxBytesReader"?

156 views
Skip to first unread message

Zhaoxun Yan

unread,
Apr 4, 2025, 5:01:31 AMApr 4
to golang-nuts
It used to send an error response to the client with code 405,  with log info like this:
reverseproxy.go:476: http: proxy error: readfrom tcp 127.0.0.1:35064->127.0.0.1:8006: http: request body too large

but I want to analyze the header and capture "X-Real-IP" of the client so as it happens continuously I can just block the IP.

It used to be a proposal: https://github.com/golang/go/issues/41493

Is it doable now? If so, from what version?

Thanks in advance,
Zhaoxun

Oliver Lowe

unread,
Apr 4, 2025, 5:46:57 AMApr 4
to Zhaoxun Yan, golang-nuts
> Is it doable now? If so, from what version?

https://pkg.go.dev/net/http#MaxBytesError

Available since go 1.19 according to the doc.

- Olly

Zhaoxun Yan

unread,
Apr 7, 2025, 5:15:41 AMApr 7
to golang-nuts
Thanks a lot Olly!
I tried to do some research, here is my code, does it look OK?
```
r.Body = http.MaxBytesReader(w, r.Body, con.SizeLimit)
defer r.Body.Close()

_, err := io.Copy(ioutil.Discard, r.Body)
if err != nil {
ip := r.Header.Get("X-Real-Ip")
               fmt.Println("someone just send an oversized request from", ip)
http.Error(w, "Request body exceeds the size limit", 405)
}else{
               fmt.Fprintf(w, "You just sent a legitimate request to the server!")
       }
```
Reply all
Reply to author
Forward
0 new messages