Memory leak in go http server and fasthttp

2k Views Asked by At

My code was a simple fasthttp server like its github examples but that had an unknown memory leak. Then I tried to find it and cleared my codes and it had that problem again.

Then I ran just the official example and even that had memory leak (meaning that I watch the memory usage on windows process manager and its used memory grows up in loads and go does not release even after a while until my windows crashed).

Then I used the std net/http by a very simple hello world server and I had that problem again. My memory usage grows by every request and Go does not release it.

My version is go 1.11.2 windows/amd64

and this is my code that have this problem:

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

There are 2 best solutions below

0
On BEST ANSWER

this was not cause of library and not a bug. it’s cause of GC behavior. its not a memory leak. study more about how Go’s GC works to understand and don’t worry at all.

1
On

According to Go http.Request documentation

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

So you should remove the r.Body.Close() call, as it is not needed.