up create path

This commit is contained in:
julien 2025-06-19 15:26:09 +02:00
parent 2fa93dd5e0
commit cf891428b3
2 changed files with 82 additions and 151 deletions

View File

@ -40,113 +40,87 @@ func CreateSavePath(db *gorm.DB) http.HandlerFunc {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
var pathDownload models.PathDownload var pathDownload models.PathDownload
// Décoder les données de la requête
if err := json.NewDecoder(r.Body).Decode(&pathDownload); err != nil { if err := json.NewDecoder(r.Body).Decode(&pathDownload); err != nil {
http.Error(w, `{"error": "Invalid JSON format"}`, http.StatusBadRequest) http.Error(w, `{"error": "Invalid JSON format"}`, http.StatusBadRequest)
return return
} }
q := query.Use(db) if pathDownload.PathName == "" {
if err := q.PathDownload.Create(&pathDownload); err != nil { http.Error(w, `{"error": "PathName cannot be empty"}`, http.StatusBadRequest)
http.Error(w, `{"error": "Failed to create path"}`, http.StatusInternalServerError)
return return
} }
// Retourner un élément HTML dynamique pour HTMX // Création du dossier physique
fullPath := "/app/upload/" + pathDownload.PathName
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
if err := os.MkdirAll(fullPath, 0755); err != nil {
http.Error(w, `{"error": "Failed to create directory"}`, http.StatusInternalServerError)
return
}
}
// Enregistrement en base
pathDownload.Path = fullPath
if err := db.Create(&pathDownload).Error; err != nil {
http.Error(w, `{"error": "Failed to save path"}`, http.StatusInternalServerError)
return
}
// Recharge la liste
ReadAllSavePath(db)(w, r)
}
}
func ReadAllSavePath(db *gorm.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
// Récupérer tous les chemins
var paths []models.PathDownload var paths []models.PathDownload
if err := db.Find(&paths).Error; err != nil { if err := db.Find(&paths).Error; err != nil {
http.Error(w, `{"error": "Failed to retrieve paths"}`, http.StatusInternalServerError) http.Error(w, `{"error": "Failed to retrieve paths"}`, http.StatusInternalServerError)
return return
} }
// Construire les lignes HTML
var response strings.Builder var response strings.Builder
for _, path := range paths { for _, path := range paths {
log.Println(path)
response.WriteString(fmt.Sprintf(` response.WriteString(fmt.Sprintf(`
<div class="column"> <div class="column">
<form>
<div id="path-%d" class="path-update grid is-col-min-1">
<input class="input is-primary cell" name="id" disabled value="%d"></input>
<input class="input is-primary fff cell" name="pathName" value="%s" disabled></span>
<button class="button is-primary is-dark" id="btn-path-edit-%d" hx-trigger="click" hx-target="#path-%d" hx-swap="outerHTML" onclick="enableAllInputPath(%d)">Edit</button>
<button class="button is-danger" type="button" id="btn-path-annuler-%d" onclick="disableAllInputPath(%d)" style="display:none" >Annuler</button>
<button class="button is-primary is-dark" id="btn-path-valider-%d" hx-put="/api/pathDownload/update/%d" hx-trigger="click[checkGlobalState()]" hx-target="#path-%d" hx-swap="outerHTML" hx-ext="json-enc" style="display:none">Valider</button>
<button class="button is-danger" hx-delete="/api/pathDownload/delete/%d" hx-trigger="click" hx-target="#path-%d" hx-swap="outerHTML" hx-confirm="Are you sure?" hx-swap="outerHTML swap:1s">Delete</button>
</div>
</form>
</div>`,
path.ID, path.ID, path.PathName,
path.ID, path.ID, path.ID,
path.ID, path.ID,
path.ID, path.ID, path.ID,
path.ID, path.ID))
}
<form>
<div id="path-%d" class="path-update grid is-col-min-1">
<input class="input is-primary cell" name="id" disabled value="%d"></input>
<input class="input is-primary fff cell" name="path" value="%s" disabled></span>
<input class="input is-primary fff cell" name="pathName" value="%s" disabled></span>
<button class="button is-primary type="button" is-dark" id="btn-path-edit-%d" hx-trigger="click" hx-target="#path-%d" hx-swap="outerHTML" onclick="enableAllInputPath(%d)">Edit</button>
<button class="button is-danger" type="button" id="btn-path-annuler-%d" onclick="disableAllInputPath(%d)" style="display:none" >Annuler</button>
<button class="button is-primary is-dark" id="btn-path-valider-%d" hx-put="/api/pathDownload/update/%d" hx-trigger="click[checkGlobalState()]" hx-target="#path-%d" hx-swap="outerHTML" hx-ext="json-enc" style="display:none">Valider</button>
<button class="button is-danger" hx-delete="/api/pathDownload/delete/%d" hx-trigger="click" hx-target="#path-%d" hx-swap="outerHTML" hx-confirm="Are you sure?" hx-swap="outerHTML swap:1s">Delete</button>
</div>
</form></div>
`, path.ID, path.ID, path.Path, path.PathName,path.ID,path.ID,path.ID,path.ID ,path.ID,path.ID,path.ID,path.ID, path.ID,path.ID))
}
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
fmt.Fprint(w, response.String()) fmt.Fprint(w, response.String())
} }
} }
func ReadAllSavePath(db *gorm.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
// Récupérer tous les chemins
var paths []models.PathDownload
if err := db.Find(&paths).Error; err != nil {
http.Error(w, `{"error": "Failed to retrieve paths"}`, http.StatusInternalServerError)
return
}
// Construire les lignes HTML
var response strings.Builder
for _, path := range paths {
response.WriteString(fmt.Sprintf(`
<div class="column">
<form>
<div id="path-%d" class="path-update grid is-col-min-1">
<input class="input is-primary cell" name="id" disabled value="%d"></input>
<input class="input is-primary fff cell" name="path" value="%s" disabled></span>
<input class="input is-primary fff cell" name="pathName" value="%s" disabled></span>
<button class="button is-primary is-dark" id="btn-path-edit-%d" hx-trigger="click" hx-target="#path-%d" hx-swap="outerHTML" onclick="enableAllInputPath(%d)">Edit</button>
<button class="button is-danger" type="button" id="btn-path-annuler-%d" onclick="disableAllInputPath(%d)" style="display:none" >Annuler</button>
<button class="button is-primary hx-trigger="click[checkGlobalState()]" type="button" is-dark" id="btn-path-valider-%d" hx-put="/api/pathDownload/update/%d" hx-target="#path-%d" hx-swap="outerHTML" hx-ext="json-enc" style="display:none">Valider</button>
<button class="button is-danger" hx-delete="/api/pathDownload/delete/%d" hx-trigger="click" hx-target="#path-%d" hx-swap="outerHTML" hx-confirm="Are you sure?" hx-swap="outerHTML swap:1s">Delete</button>
</div>
</form></div>
`, path.ID, path.ID, path.Path, path.PathName,path.ID,path.ID,path.ID,path.ID, path.ID,path.ID,path.ID,path.ID, path.ID,path.ID))
}
// Retourner les lignes HTML
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, response.String())
}
}
func UpdateSavePath(db *gorm.DB) http.HandlerFunc { func UpdateSavePath(db *gorm.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
// Récupérer l'ID depuis les paramètres de l'URL
id := mux.Vars(r)["id"] id := mux.Vars(r)["id"]
var pathDownload models.PathDownload var pathDownload models.PathDownload
log.Println(pathDownload);
// Décoder les données de la requête
if err := json.NewDecoder(r.Body).Decode(&pathDownload); err != nil { if err := json.NewDecoder(r.Body).Decode(&pathDownload); err != nil {
http.Error(w, `{"error": "Invalid JSON format"}`, http.StatusBadRequest) http.Error(w, `{"error": "Invalid JSON format"}`, http.StatusBadRequest)
return return
} }
// Vérifier si la ressource existe
var existingPath models.PathDownload var existingPath models.PathDownload
if err := db.First(&existingPath, "id = ?", id).Error; err != nil { if err := db.First(&existingPath, "id = ?", id).Error; err != nil {
if err == gorm.ErrRecordNotFound { if err == gorm.ErrRecordNotFound {
@ -157,75 +131,34 @@ func UpdateSavePath(db *gorm.DB) http.HandlerFunc {
return return
} }
// Mettre à jour les champs souhaités // Renommage physique du dossier
existingPath.Path = pathDownload.Path oldFullPath := "/app/upload/" + existingPath.PathName
newFullPath := "/app/upload/" + pathDownload.PathName
if oldFullPath != newFullPath {
if err := os.Rename(oldFullPath, newFullPath); err != nil {
http.Error(w, `{"error": "Failed to rename directory"}`, http.StatusInternalServerError)
return
}
}
existingPath.PathName = pathDownload.PathName existingPath.PathName = pathDownload.PathName
existingPath.Path = newFullPath
if err := db.Save(&existingPath).Error; err != nil { if err := db.Save(&existingPath).Error; err != nil {
http.Error(w, `{"error": "Failed to update path"}`, http.StatusInternalServerError) http.Error(w, `{"error": "Failed to update path"}`, http.StatusInternalServerError)
return return
} }
response := fmt.Sprintf(`
<form> ReadAllSavePath(db)(w, r)
<div id="path-%d" class="path-update grid is-col-min-1">
<input class="input is-primary cell" name="id" disabled value="%d"></input>
<input class="input is-primary fff cell" name="path" value="%s" disabled></span>
<input class="input is-primary fff cell" name="pathName" value="%s" disabled></span>
<button class="button is-primary is-dark" id="btn-path-edit-%d" hx-trigger="click" hx-target="#path-%d" hx-swap="outerHTML" onclick="enableAllInputPath(%d)">Edit</button>
<button class="button is-danger" type="button" id="btn-path-annuler-%d" onclick="disableAllInputPath(%d)" style="display:none" >Annuler</button>
<button class="button is-primary type="button" is-dark" id="btn-path-valider-%d" hx-put="/api/pathDownload/update/%d" hx-trigger="click[checkGlobalState()]" hx-target="#path-%d" hx-swap="outerHTML" hx-ext="json-enc" style="display:none">Valider</button>
<button class="button is-danger" hx-delete="/api/pathDownload/delete/%d" hx-trigger="click" hx-target="#path-%d" hx-swap="outerHTML" hx-confirm="Are you sure?" hx-swap="outerHTML swap:1s">Delete</button>
</div>
</form>
`, existingPath.ID, existingPath.ID, existingPath.Path, existingPath.PathName, existingPath.ID, existingPath.ID, existingPath.ID, existingPath.ID, existingPath.ID, existingPath.ID, existingPath.ID, existingPath.ID, existingPath.ID, existingPath.ID)
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, response)
// // Retourner le nouvel élément HTML
// var paths []models.PathDownload
// if err := db.Find(&paths).Error; err != nil {
// http.Error(w, `{"error": "Failed to retrieve paths"}`, http.StatusInternalServerError)
// return
// }
// // Construire les lignes HTML
// var response strings.Builder
// for _, path := range paths {
// log.Println(path)
// response.WriteString(fmt.Sprintf(`
// <form>
// <div id="path-%d" class="path-update grid is-col-min-1">
// <input class="input is-primary cell" name="id" disabled value="%d"></input>
// <input class="input is-primary fff cell" name="path" value="%s" disabled></span>
// <input class="input is-primary fff cell" name="pathName" value="%s" disabled></span>
// <button class="button is-primary is-dark" type="button" id="btn-path-edit-%d" hx-trigger="click" hx-target="#path-%d" hx-swap="outerHTML" onclick="enableAllInputPath(%d)">Edit</button>
// <button class="button is-danger" id="btn-path-annuler-%d" type="button" onclick="disableAllInputPath(%d)" style="display:none" >Annuler</button>
// <button class="button is-primary is-dark" id="btn-path-valider-%d" hx-put="/api/pathDownload/update/%d" hx-trigger="click" hx-target="#path-%d" hx-swap="outerHTML" hx-ext="json-enc" style="display:none">Valider</button>
// <button class="button is-danger" hx-delete="/api/pathDownload/delete/%d" hx-trigger="click" hx-target="#path-%d" hx-swap="outerHTML">Delete</button>
// </div>
// </form>
// `, path.ID, path.ID, path.Path, path.PathName,path.ID,path.ID,path.ID, path.ID,path.ID ,path.ID,path.ID,path.ID, path.ID,path.ID))
// }
w.WriteHeader(http.StatusOK)
//fmt.Fprint(w, response.String())
} }
} }
func DeleteSavePath(db *gorm.DB) http.HandlerFunc { func DeleteSavePath(db *gorm.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
// Récupérer l'ID depuis les paramètres de l'URL
id := mux.Vars(r)["id"] id := mux.Vars(r)["id"]
// Vérifier si la ressource existe
var pathDownload models.PathDownload var pathDownload models.PathDownload
if err := db.First(&pathDownload, "id = ?", id).Error; err != nil { if err := db.First(&pathDownload, "id = ?", id).Error; err != nil {
if err == gorm.ErrRecordNotFound { if err == gorm.ErrRecordNotFound {
@ -236,38 +169,38 @@ func DeleteSavePath(db *gorm.DB) http.HandlerFunc {
return return
} }
// Supprimer la ressource // Supprimer physiquement le dossier
fullPath := "/app/upload/" + pathDownload.PathName
if err := os.RemoveAll(fullPath); err != nil {
http.Error(w, `{"error": "Failed to delete directory"}`, http.StatusInternalServerError)
return
}
if err := db.Delete(&pathDownload).Error; err != nil { if err := db.Delete(&pathDownload).Error; err != nil {
http.Error(w, `{"error": "Failed to delete path"}`, http.StatusInternalServerError) http.Error(w, `{"error": "Failed to delete path"}`, http.StatusInternalServerError)
return return
} }
// Répondre avec succès ReadAllSavePath(db)(w, r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, ` <div class="notification is-primary" id="notificationPath" style="display:block">
<button class="delete" type="button" onclick="hide('notificationPath')"></button>
Delete ok
</div>`)
} }
} }
func IsPathValid(path string) error {
if path == "" { func IsPathValid(subPath string) error {
if subPath == "" {
return errors.New("path is empty") return errors.New("path is empty")
} }
fullPath := "/app/upload/" + subPath
info, err := os.Stat(path) info, err := os.Stat(fullPath)
if os.IsNotExist(err) { if os.IsNotExist(err) {
return errors.New("path does not exist") return errors.New("path does not exist")
} }
if err != nil { if err != nil {
return errors.New("unable to access path: " + err.Error()) return errors.New("unable to access path: " + err.Error())
} }
if !info.IsDir() {
if !info.IsDir() && !info.Mode().IsRegular() { return errors.New("path is not a directory")
return errors.New("path is neither a file nor a directory")
} }
return nil
return nil // Path is valid
} }
// PathValidationHandler handles HTTP requests to validate a path // PathValidationHandler handles HTTP requests to validate a path

View File

@ -38,12 +38,10 @@
</div> </div>
<form hx-post="/api/pathDownload/create" hx-trigger="click" hx-target="#path-list" hx-ext="json-enc" style="width: min-content;"> <form hx-post="/api/pathDownload/create" hx-trigger="click" hx-target="#path-list" hx-ext="json-enc" style="width: min-content;">
<input type="hidden" id="path" name="path">
<input type="hidden" id="pathName" name="pathName"> <input type="hidden" id="pathName" name="pathName">
<button id="validate-btn" class="button is-primary" disabled type="submit"> <button id="validate-btn" class="button is-primary" disabled type="submit">Validate</button>
Validate
</button>
</form> </form>
</div> </div>
<div class="column"> <div class="column">
<div hx-get="/api/pathDownload/all/" hx-trigger="load" hx-target="#path-list"> </div> <div hx-get="/api/pathDownload/all/" hx-trigger="load" hx-target="#path-list"> </div>