如何通过 Go 的 MaxBytesReader 确定我是否达到了大小限制

How to determine if I've reached the size limit via Go's MaxBytesReader

我是 Go 新手,使用 Mux 接受 HTTP POST 数据。我想使用 MaxBytesReader to ensure a client does not overwhelm my server. According to the code,有一个 requestBodyLimit 布尔值指示是否已达到该限制。

我的问题是:使用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)
}

我怎样才能:

在处理程序的开头调用 ParseForm。如果此方法 return 出错,则超出了大小限制或请求正文在某种程度上无效。从处理程序写入错误状态和 return。

没有一种简单的方法来检测错误是由于超出大小限制还是其他一些错误造成的。

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)
    }
}

您可以通过检查读取数据的长度是否大于(或等于)MaxBytesSize来判断是否超出限制:

maxBytesSize := 10
r.Body = http.MaxBytesReader(w, r.Body, maxBytesSize)

// check if request body is not too large
data, err := ioutil.ReadAll(r.Body)
if err != nil {
    if len(data) >= maxBytesSize {
         //exceeded
    }
    // some other error
}