diff --git a/handlers.go b/handlers.go index 5b82349..9c1bd25 100644 --- a/handlers.go +++ b/handlers.go @@ -45,8 +45,7 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc { mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil { - // not sure whether this should be a bad request or server error - http.Error(w, "failed to find or parse Content-Type", http.StatusInternalServerError) + http.Error(w, "failed to find or parse Content-Type", http.StatusBadRequest) return } @@ -92,7 +91,7 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc { http.Error(w, "unsupported Content-Type", http.StatusUnsupportedMediaType) return } - // todo: clean up after failure, maybe defer a function before any of this, that checks if everything passed? + id := generateId(idLength) path := getStoragePath(cfg.UploadDir, id) if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { @@ -108,6 +107,16 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc { return } + saved := false + defer func() { + dest.Close() + if !saved { + if err := os.Remove(path); err != nil { + log.Printf("remove incomplete upload %s: %v", id, err) + } + } + }() + hasher := sha256.New() size, err := io.Copy(io.MultiWriter(dest, hasher), input.Reader) if err != nil { @@ -118,6 +127,7 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc { if err := dest.Close(); err != nil { log.Println("close file:", err) http.Error(w, "failed to save upload", http.StatusInternalServerError) + return } createdAt := time.Now().UTC().Unix() if utf8.RuneCountInString(input.Filename) > 255 { @@ -145,7 +155,7 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc { http.Error(w, "failed to save upload", http.StatusInternalServerError) return } - + saved = true w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) if err := json.NewEncoder(w).Encode(upload); err != nil {