I am writing a Go server which handles image uploading via Multipart Requests, but after a while i get really bad memory usages (up to 100% RAM).
I am using the basic http.ListenAndServeTLS and http.HandleFunc to do so. Below a snippet of my code and the svg i got from pprof after a lot of image uploads.
func HandleUploadImage(res http.ResponseWriter, req *http.Request) {
defer func() {
// Release mem
if req != nil {
fmt.Println("Releasing request")
if req.MultipartForm != nil {
fmt.Println("Releasing MultipartForm")
req.MultipartForm.RemoveAll()
}
if req.Body != nil {
fmt.Println("Closing req.Body")
req.Body.Close()
}
}
}()
// parse request
const _2MB = 1 << 20
if err := req.ParseMultipartForm(_2MB); nil != err {
u.Log("Error", "Couldn't parse MultiPartForm", map[string]interface{}{"Error": err}, u.GetFile_line(), "")
return
}
id := req.FormValue(formValueString)
// get the json data
if err := json.Unmarshal([]byte(id), marshalStruct); nil != err {
u.Log("Error", "Couldn't Unmarshal JSON", map[string]interface{}{"Error": err}, u.GetFile_line(), "")
return
}
// Do something with the image and save it
// Marshal the reponse to JSON.
resJSON, err := response.ToJSON()
if err != nil {
u.Log("Error", "Couldn't create JSON from response struct", map[string]interface{}{"Error": err, "ResponseStruct": response}, u.GetFile_line(), username)
return
}
}