🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The http.MaxBytesReader function in Golang is part of the net/http package and is used to limit the size of a request body that can be read by a handler. This function helps prevent clients from sending excessively large requests that could consume server resources, potentially leading to denial of service (DoS) attacks.
Table of Contents
- Introduction
http.MaxBytesReaderFunction Syntax- Examples
- Basic Usage
- Handling Request Body Limits
- Custom Error Handling
- Real-World Use Case
- Conclusion
Introduction
The http.MaxBytesReader function wraps an http.Request.Body with a reader that returns an error if the body exceeds a specified size. This is useful for protecting your server from large payloads that could overwhelm it.
http.MaxBytesReader Function Syntax
The syntax for the http.MaxBytesReader function is as follows:
func MaxBytesReader(w http.ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
Parameters:
w: Thehttp.ResponseWriterused to write the HTTP response if the limit is exceeded.r: Theio.ReadCloserrepresenting the original request body.n: The maximum number of bytes that can be read from the request body.
Returns:
io.ReadCloser: A reader that enforces the specified byte limit on the request body.
Examples
Basic Usage
This example demonstrates how to use http.MaxBytesReader to limit the size of a request body to 1 MB.
Example
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MB limit
// Attempt to read the body
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Request body too large", http.StatusRequestEntityTooLarge)
return
}
// Process the body (for demonstration, just print it)
fmt.Fprintf(w, "Received: %s", body)
})
http.ListenAndServe(":8080", nil)
}
Explanation:
- The server limits the request body size to 1 MB for the
/uploadendpoint. - If the body exceeds this limit, the server responds with a 413 status code (
RequestEntityTooLarge).
Handling Request Body Limits
This example shows how to gracefully handle the situation when the request body exceeds the specified limit.
Example
package main
import (
"fmt"
"net/http"
"io"
)
func main() {
http.HandleFunc("/submit", func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 512<<10) // 512 KB limit
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "The request body is too large", http.StatusRequestEntityTooLarge)
return
}
fmt.Fprintf(w, "Received %d bytes", len(body))
})
http.ListenAndServe(":8080", nil)
}
Explanation:
- The server sets a 512 KB limit on the request body for the
/submitendpoint. - If the limit is exceeded, the server responds with a 413 status code.
Custom Error Handling
This example demonstrates how to customize the error response when the request body exceeds the limit.
Example
package main
import (
"fmt"
"net/http"
"io"
)
func main() {
http.HandleFunc("/data", func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 256<<10) // 256 KB limit
body, err := io.ReadAll(r.Body)
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusRequestEntityTooLarge)
fmt.Fprintln(w, `{"error": "Request body exceeds the 256 KB limit"}`)
return
}
fmt.Fprintf(w, "Data received: %d bytes", len(body))
})
http.ListenAndServe(":8080", nil)
}
Explanation:
- The server enforces a 256 KB limit on the request body.
- If the limit is exceeded, it sends a JSON response with a custom error message.
Real-World Use Case
http.MaxBytesReader is commonly used in APIs to limit the size of incoming JSON or file uploads, protecting the server from large payloads that could impact performance.
Conclusion
The http.MaxBytesReader function in Go is essential for controlling the size of incoming request bodies, helping to protect your server from large or malicious requests.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment