0

0

Is an http.Request.Body Buffered in Go?

聖光之護

聖光之護

发布时间:2025-12-31 13:12:09

|

514人浏览过

|

来源于php中文网

原创

Is an http.Request.Body Buffered in Go?

go’s http server does not buffer the entire request body by default—your handler runs immediately, and `r.body` is a streaming reader; however, uncontrolled slow clients (e.g., slowloris) can exhaust resources if you don’t enforce timeouts or limit read behavior.

In Go’s net/http package, the http.Request.Body is not pre-buffered into memory. Instead, it’s an io.ReadCloser backed by the underlying network connection—essentially a lazy, on-demand stream. When your ServeHTTP method is called, the HTTP server has already parsed the request headers and started reading the body, but it does not wait for the full body to arrive before invoking your handler. This means:

  • For a GET request: r.Body is typically empty (nil or an empty io.NopCloser), so no issue.
  • For a POST/PUT with payload: r.Body remains open and readable as data arrives, and your code must explicitly read from it (e.g., via io.ReadAll, json.NewDecoder(r.Body).Decode(...), or streaming logic).

⚠️ Critical implication for security & resource usage:
If a malicious client sends a large Content-Length (e.g., 9 MB) but transmits bytes extremely slowly (one byte every 10 seconds), Go will keep the connection—and the associated goroutine and OS file descriptor—alive until the body is fully read or the connection closes. Since each active request consumes memory (stack, buffers, TLS state) and goroutines are cheap but not free, 10,000 such stalled connections can indeed exhaust memory, file descriptors, or CPU scheduler capacity, enabling Slowloris-style denial-of-service.

The correct defense is timeout configurationnot buffering logic in your handler:

server := &http.Server{
    Addr:         ":8080",
    Handler:      &MyHandler{},
    ReadTimeout:  5 * time.Second,   // terminates slow header/body reads
    WriteTimeout: 10 * time.Second,  // protects response writes
    IdleTimeout:  30 * time.Second,  // enforces keep-alive idle limits
}
log.Fatal(server.ListenAndServe())
  • ReadTimeout starts ticking as soon as the connection is accepted, covering both header parsing and body reading. If the client fails to send data fast enough (including pauses between chunks), the connection is closed automatically.
  • Note: ReadTimeout applies per-connection, not per-request body read — so even io.Copy or ioutil.ReadAll inside your handler will be interrupted if the total read time exceeds the timeout.

? Additional hardening tips:

Endel.io
Endel.io

Endel是一款可以创造个性化舒缓声音的应用程序,可帮助您集中注意力、放松身心和入睡。

下载
  • Use http.MaxBytesReader to cap total bytes read from r.Body:
    limitedBody := http.MaxBytesReader(w, r.Body, 10<<20) // max 10 MB
    data, err := io.ReadAll(limitedBody)
    if err == http.ErrBodyReadAfterClose {
        // client closed early — handle gracefully
    }
  • Avoid r.ParseForm() or r.FormValue() on untrusted, high-volume endpoints without prior size limiting — they internally call ParseMultipartForm, which may allocate large in-memory buffers for multipart data.
  • For file uploads, prefer streaming parsers (e.g., mime/multipart.Reader) and write to disk or external storage immediately, rather than accumulating in memory.

In summary: Go gives you streaming control — not automatic buffering — making your handler responsible for safe, bounded consumption of request bodies. Combine ReadTimeout, MaxBytesReader, and defensive reading patterns to build resilient, production-ready HTTP handlers.

相关专题

更多
json数据格式
json数据格式

JSON是一种轻量级的数据交换格式。本专题为大家带来json数据格式相关文章,帮助大家解决问题。

402

2023.08.07

json是什么
json是什么

JSON是一种轻量级的数据交换格式,具有简洁、易读、跨平台和语言的特点,JSON数据是通过键值对的方式进行组织,其中键是字符串,值可以是字符串、数值、布尔值、数组、对象或者null,在Web开发、数据交换和配置文件等方面得到广泛应用。本专题为大家提供json相关的文章、下载、课程内容,供大家免费下载体验。

528

2023.08.23

jquery怎么操作json
jquery怎么操作json

操作的方法有:1、“$.parseJSON(jsonString)”2、“$.getJSON(url, data, success)”;3、“$.each(obj, callback)”;4、“$.ajax()”。更多jquery怎么操作json的详细内容,可以访问本专题下面的文章。

306

2023.10.13

go语言处理json数据方法
go语言处理json数据方法

本专题整合了go语言中处理json数据方法,阅读专题下面的文章了解更多详细内容。

74

2025.09.10

resource是什么文件
resource是什么文件

Resource文件是一种特殊类型的文件,它通常用于存储应用程序或操作系统中的各种资源信息。它们在应用程序开发中起着关键作用,并在跨平台开发和国际化方面提供支持。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

140

2023.12.20

if什么意思
if什么意思

if的意思是“如果”的条件。它是一个用于引导条件语句的关键词,用于根据特定条件的真假情况来执行不同的代码块。本专题提供if什么意思的相关文章,供大家免费阅读。

711

2023.08.22

length函数用法
length函数用法

length函数用于返回指定字符串的字符数或字节数。可以用于计算字符串的长度,以便在查询和处理字符串数据时进行操作和判断。 需要注意的是length函数计算的是字符串的字符数,而不是字节数。对于多字节字符集,一个字符可能由多个字节组成。因此,length函数在计算字符串长度时会将多字节字符作为一个字符来计算。更多关于length函数的用法,大家可以阅读本专题下面的文章。

905

2023.09.19

default gateway怎么配置
default gateway怎么配置

配置default gateway的步骤:1、了解网络环境;2、获取路由器IP地址;3、登录路由器管理界面;4、找到并配置WAN口设置;5、配置默认网关;6、保存设置并退出;7、检查网络连接是否正常。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

219

2023.12.07

小游戏4399大全
小游戏4399大全

4399小游戏免费秒玩大全来了!无需下载、即点即玩,涵盖动作、冒险、益智、射击、体育、双人等全品类热门小游戏。经典如《黄金矿工》《森林冰火人》《狂扁小朋友》一应俱全,每日更新最新H5游戏,支持电脑与手机跨端畅玩。访问4399小游戏中心,重温童年回忆,畅享轻松娱乐时光!官方入口安全绿色,无插件、无广告干扰,打开即玩,快乐秒达!

30

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
WEB前端教程【HTML5+CSS3+JS】
WEB前端教程【HTML5+CSS3+JS】

共101课时 | 8.1万人学习

JS进阶与BootStrap学习
JS进阶与BootStrap学习

共39课时 | 3.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号