-2

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)
    }
}
abgr
  • 63
  • 9
  • Describe the workload. Are you using a testing tool, hitting from a web browser or something else? To be clear, are you saying that running this program crashed Windows? – Charlie Tumahai Nov 26 '18 at 01:37
  • no i just use the insomnia for testing and opera browser but i request several times. and yes when i try to serve a big file for downloading my windows hangs cause of full memory – abgr Nov 26 '18 at 01:42
  • The code in the question does not serve big files. Please post your actual code. – Charlie Tumahai Nov 26 '18 at 02:02
  • i can't put my code but the leaking reason of this code is the answer of why my code is leaking too and so my code is like the http serveContent – abgr Nov 26 '18 at 03:09
  • 1
    The code in the question does not leak. Please update the question with [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Charlie Tumahai Nov 26 '18 at 05:52
  • You say that when using the Hello-world example "Go does release it." Do you mean "Go does not release it"? – Jonathan Hall Nov 26 '18 at 06:38
  • yes I edited that. – abgr Nov 26 '18 at 12:47

2 Answers2

0

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.

Maxian Nicu
  • 2,166
  • 3
  • 17
  • 31
0

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.

abgr
  • 63
  • 9