0

I have a code that has this structure:

package main

import (
    "html/template"
    "net/http"
    "log"
)

func main() {
    http.HandleFunc("/",myFunction)
    http.HandleFunc("/route2",mySecondFunction)
    http.HandleFunc("/route3",myThirdFunction)
    http.ListenAndServe(":8080",nil)
}

func check(err error){
    if err != nil{
        log.Fatal(err)
    }
}

func myFunction(w http.ResponseWriter, r *http.Request){
    if r.Method == "GET"{
        t,err := template.ParseFiles("request.html")
        check(err)
        t.Execute(w,nil)
    }
}

This code simply creates a server with whatever it has in request.html file and it runs in localhost: 8080, see the routes I set in http.HandleFunc("/", myFunction).

I could see that in task manager, even when the server was idle, memory usage never decreased, only increasing according to the amount of calls I made to the server.

Init state:

enter image description here

After some requests:

enter image description here

And this working set never decreased

How can I do to free up the memory that has already been used and at the same time not disable the server?

MarceloBoni
  • 241
  • 1
  • 7
  • 16
  • 1
    Possible duplicate of [Golang - Cannot free memory once occupied by bytes.Buffer](http://stackoverflow.com/questions/37382600/golang-cannot-free-memory-once-occupied-by-bytes-buffer/37383604#37383604). – icza Mar 26 '17 at 16:18
  • @icza after `http.ListenAndServe(":8080", nil)` I set it `defer debug.FreeOSMemory()` does not seem to work, I did a test, it was about 10 minutes ago and it looks like the garbage collector did not work =[ – MarceloBoni Mar 26 '17 at 16:34
  • 1
    What is the problem exactly? Your app uses like 10 MB of RAM, that's not much for a web server... – icza Mar 26 '17 at 16:37
  • The idea is to free space when resource is no longer being used on the server, I am testing locally, but the service will run on a server that will have hundreds of access. – MarceloBoni Mar 26 '17 at 16:40
  • 2
    Just because in production you'll have a hundred times more requests it doesn't mean a hundred times more memory will be used. Go is a garbage collected language, you shouldn't worry about memory usage until it proves to be an issue. – icza Mar 26 '17 at 16:55
  • 3
    One thing you should avoid is parsing templates in handlers (during serving requests). For details see [It takes too much time when using "template" package to generate a dynamic web page to client in golang](http://stackoverflow.com/questions/28451675/it-takes-too-much-time-when-using-template-package-to-generate-a-dynamic-web-p/28453523#28453523). – icza Mar 26 '17 at 16:58

0 Answers0