我是 Go 新手,使用 Mux 接受 HTTP POST 数据。我想使用 MaxBytesReader确保客户端不会压倒我的服务器。根据code ,有一个 requestBodyLimit
bool 值指示是否已达到该限制。
我的问题是:在使用 MaxBytesReader 时,如何确定我在处理请求时是否真的达到了最大值?
这是我的代码:
package main
import (
"fmt"
"log"
"html/template"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/handle", maxBytes(PostHandler)).Methods("POST")
http.ListenAndServe(":8080", r)
}
// Middleware to enforce the maximum post body size
func maxBytes(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// As an example, limit post body to 10 bytes
r.Body = http.MaxBytesReader(w, r.Body, 10)
f(w, r)
}
}
func PostHandler(w http.ResponseWriter, r *http.Request) {
// How do I know if the form data has been truncated?
book := r.FormValue("email")
fmt.Fprintf(w, "You've requested the book: %s\n", book)
}
我怎样才能:
确定我已达到最大 POST 限制(或有权访问
requestBodyLimit
我的代码可以在这种情况下分支吗?
最佳答案
调用ParseForm在处理程序的开头。如果此方法返回错误,则表明超出了大小限制或请求正文在某种程度上无效。写入错误状态并从处理程序返回。
没有一种简单的方法可以检测错误是由于超出大小限制还是其他一些错误造成的。
func PostHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
book := r.FormValue("email")
fmt.Fprintf(w, "You've requested the book: %s\n", book)
}
根据您的需要,将检查放在中间件中可能会更好:
func maxBytes(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 10)
if err := r.ParseForm(); err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
f(w, r)
}
}
关于go - 如何通过 Go 的 MaxBytesReader 确定我是否达到了大小限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52879193/