Skip to content

Instantly share code, notes, and snippets.

@rekby
Created October 19, 2022 21:27
Show Gist options
  • Save rekby/9629c2d8cf85efee72cbe9b1b7fc4634 to your computer and use it in GitHub Desktop.
Save rekby/9629c2d8cf85efee72cbe9b1b7fc4634 to your computer and use it in GitHub Desktop.
limit max request size example
package main
import (
"io"
"net/http"
)
const maxLen = 10
func handler(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(io.LimitReader(r.Body, maxLen+1))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
defer r.Body.Close()
if len(body) > maxLen {
w.WriteHeader(http.StatusBadRequest)
return
}
io.WriteString(w, "OK")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe("localhost:8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment