Skip to content

Commit

Permalink
prevent out of memory
Browse files Browse the repository at this point in the history
  • Loading branch information
codeskyblue committed May 11, 2017
1 parent e063187 commit a95e388
Showing 1 changed file with 12 additions and 24 deletions.
36 changes: 12 additions & 24 deletions httpstaticserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ func (s *HTTPStaticServer) hDelete(w http.ResponseWriter, req *http.Request) {

func (s *HTTPStaticServer) hUpload(w http.ResponseWriter, req *http.Request) {
path := mux.Vars(req)["path"]
dirpath := filepath.Join(s.Root, path)

// check auth
auth := s.readAccessConf(path)
Expand All @@ -140,37 +141,24 @@ func (s *HTTPStaticServer) hUpload(w http.ResponseWriter, req *http.Request) {
return
}

err := req.ParseMultipartForm(1 << 30) // max memory 1G
file, header, err := req.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if len(req.MultipartForm.File["file"]) == 0 {
http.Error(w, "Need multipart file", http.StatusInternalServerError)
defer file.Close()
dst, err := os.Create(filepath.Join(dirpath, header.Filename)) // BUG(ssx): There is a leak here
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

dirpath := filepath.Join(s.Root, path)

for _, mfile := range req.MultipartForm.File["file"] {
file, err := mfile.Open()
defer file.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
dst, err := os.Create(filepath.Join(dirpath, mfile.Filename)) // BUG(ssx): There is a leak here
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
log.Println("Handle upload file:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
log.Println("Handle upload file:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// runtime.GC()
w.Write([]byte("Upload success"))
}

Expand Down

0 comments on commit a95e388

Please sign in to comment.