Use http.MaxBytesReader to limit and control the size HTTP request body. This is a good practice to prevent abuse and save bandwidth. In the example below, I set a 20 bytes HTTP request body size limit.
package main
import (
"github.com/julienschmidt/httprouter"
"io"
"log"
"net/http"
"time"
)
func main() {
router := httprouter.New()
router.HandlerFunc(http.MethodPost, "/", func(w http.ResponseWriter, r *http.Request) {
buffer, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 20))
defer r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
log.Println(string(buffer))
return
}
log.Println(string(buffer))
})
httpServer := &http.Server{
Addr: ":8080",
Handler: router,
ReadTimeout: 120 * time.Second,
WriteTimeout: 120 * time.Second,
}
log.Fatal(httpServer.ListenAndServe())
}
Test Content Length 20 bytes
Test Content Length 24 bytes