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

标签 go go-http

我是 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/

相关文章:

go - 如何在调试过程中不单步执行时停止时间?

jquery - Ajax新手学习(golang jquery)

go - 使用 HTTP GET 请求调用 tcp i/o 超时

go - 当请求到达根目录时,从另一个目录提供文件

go - 为什么Golang不能下载某些网页?

unit-testing - 如何在 Go 中打印数组项的类型?

go - 修复 go 使用的工具版本

go - 如何存储去依赖?

http - 从网址中删除结尾的斜杠-转到静态服务器

go - 如何将主页和静态文件设置在同一路径