Add file save and delete api endpoints

This commit is contained in:
2024-09-26 15:34:24 +02:00
parent b2e99fa39e
commit 9faa212043
3 changed files with 53 additions and 0 deletions

View File

@@ -2,6 +2,7 @@ package api
import (
"encoding/json"
"io"
"net/http"
"strings"
@@ -34,3 +35,37 @@ func GetFileContent(fs *filesystem.FileSystem) http.HandlerFunc {
w.Write(content)
}
}
func SaveFile(fs *filesystem.FileSystem) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
filePath := strings.TrimPrefix(r.URL.Path, "/api/v1/files/")
content, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
err = fs.SaveFile(filePath, content)
if err != nil {
http.Error(w, "Failed to save file", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("File saved successfully"))
}
}
func DeleteFile(fs *filesystem.FileSystem) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
filePath := strings.TrimPrefix(r.URL.Path, "/api/v1/files/")
err := fs.DeleteFile(filePath)
if err != nil {
http.Error(w, "Failed to delete file", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("File deleted successfully"))
}
}