cleanup; return on error; content-type failure is bad request

This commit is contained in:
2026-11-08 21:33:47 -05:00
parent 673c039d1c
commit fc45fe8bd7
+14 -4
View File
@@ -45,8 +45,7 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil { 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.StatusBadRequest)
http.Error(w, "failed to find or parse Content-Type", http.StatusInternalServerError)
return return
} }
@@ -92,7 +91,7 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
http.Error(w, "unsupported Content-Type", http.StatusUnsupportedMediaType) http.Error(w, "unsupported Content-Type", http.StatusUnsupportedMediaType)
return return
} }
// todo: clean up after failure, maybe defer a function before any of this, that checks if everything passed?
id := generateId(idLength) id := generateId(idLength)
path := getStoragePath(cfg.UploadDir, id) path := getStoragePath(cfg.UploadDir, id)
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
@@ -108,6 +107,16 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
return 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() hasher := sha256.New()
size, err := io.Copy(io.MultiWriter(dest, hasher), input.Reader) size, err := io.Copy(io.MultiWriter(dest, hasher), input.Reader)
if err != nil { if err != nil {
@@ -118,6 +127,7 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
if err := dest.Close(); err != nil { if err := dest.Close(); err != nil {
log.Println("close file:", err) log.Println("close file:", err)
http.Error(w, "failed to save upload", http.StatusInternalServerError) http.Error(w, "failed to save upload", http.StatusInternalServerError)
return
} }
createdAt := time.Now().UTC().Unix() createdAt := time.Now().UTC().Unix()
if utf8.RuneCountInString(input.Filename) > 255 { 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) http.Error(w, "failed to save upload", http.StatusInternalServerError)
return return
} }
saved = true
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(upload); err != nil { if err := json.NewEncoder(w).Encode(upload); err != nil {