dongwopu8210 2015-02-02 16:35
浏览 39
已采纳

在使用golang时,是否建议(进一步)限制表单的大小?

I searched around and as far as I can tell, POST form requests are already limited to 10MB (http://golang.org/src/net/http/request.go#L721).

If I were to go about reducing this in my ServeHTTP method, I'm not sure how to properly do it. I would try something like this:

r.Body = http.MaxBytesReader(w, r.Body, MaxFileSize) 
err := r.ParseForm()
if err != nil {
     //redirect to some error page
     return
}

But would returning upon error close the connection as well? How would I prevent having to read everything? I found this: https://stackoverflow.com/a/26393261/2202497, but what if content length is not set and in the middle of reading I realize that the file is too big.

I'm using this as a security measure to prevent someone from hogging my server's resources.

  • 写回答

2条回答 默认 最新

  • dswmmvrg40957 2015-02-03 06:13
    关注

    The correct way to limit the size of the request body is to do as you suggested:

    r.Body = http.MaxBytesReader(w, r.Body, MaxFileSize) 
    err := r.ParseForm()
    if err != nil {
     // redirect or set error status code.
     return
    }
    

    MaxBytesReader sets a flag on the response when the limit is reached. When this flag is set, the server does not read the remainder of the request body and the server closes the connection on return from the handler.

    If you are concerned about malicious clients, then you should also set Server.ReadTimeout, Server.WriteTimeout and possibly Server.MaxHeaderBytes.

    If you want to set the request body limit for all of your handlers, then wrap root handler with a handler that sets the limit before delegating to the root handler:

     type maxBytesHandler struct {
         h http.Handler
         n int64
     }
    
     func (h *maxBytesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
         r.Body = http.MaxBytesReader(w, r.Body, h.n) 
         h.h.ServeHTTP(w, r)
     }
    

    Wrap the root handler when calling ListenAndServe:

    log.Fatal(http.ListenAndServe(":8080", &maxBytesHandler{h:mux, n:4096))
    

    or when configuring a server:

    s := http.Server{
        Addr: ":8080",
        Handler: &maxBytesReader{h:mux, n:4096},
    }
    log.Fatal(s.ListenAndServe())
    

    There's no need for a patch as suggested in another answer. MaxBytesReader is the official way to limit the size of the request body.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名