首页 > 解决方案 > go http 服务器和 fasthttp 中的内存泄漏

问题描述

我的代码是一个简单的 fasthttp 服务器,就像它的 github 示例一样,但是存在未知的内存泄漏。然后我试图找到它并清除我的代码,它又遇到了这个问题。

然后我只运行了官方示例,甚至出现了内存泄漏(这意味着我在 Windows 进程管理器上观察内存使用情况,并且它使用的内存在负载中增长,并且即使在我的 Windows 崩溃之前一段时间后 go 也不会释放)。

然后我通过一个非常简单的hello world服务器使用了std net/http,我又遇到了这个问题。每个请求都会增加我的内存使用量,而 Go 不会释放它。

我的版本是 go 1.11.2 windows/amd64

这是我有这个问题的代码:

package main

import (
    "net/http"
    "strings"
)

func sayHello(w http.ResponseWriter, r *http.Request) {
    message := r.URL.Path
    message = strings.TrimPrefix(message, "/")
    message = "Hello " + message
    w.Write([]byte(message))
    r.Body.Close()
}
func main() {
    http.HandleFunc("/", sayHello)
    if err := http.ListenAndServe(":8080", nil); err != nil {
        panic(err)
    }
}

标签: debugginggomemory-leaksserverfasthttp

解决方案


根据Go http.Request 文档

// The Server will close the request body. The ServeHTTP
// Handler does not need to.

因此,您应该删除r.Body.Close()呼叫,因为它不是必需的。


推荐阅读