show files

This commit is contained in:
Laurent Evrard 2025-12-05 06:34:16 +01:00
parent 1567908f0e
commit e92b19351b
2 changed files with 76 additions and 6 deletions

51
main.go
View file

@ -6,11 +6,20 @@ import (
"net/http"
"os"
"path/filepath"
"strings"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
const DATA_DIR = "files"
const DATA_URI = "/files"
type File struct {
Filename string
URL string
}
type Template struct {
templates *template.Template
}
@ -36,8 +45,8 @@ func upload(c echo.Context) error {
defer src.Close()
// Destination
destinationPath := filepath.Join("files", file.Filename)
destinationUrl := filepath.Join("/files", file.Filename)
destinationPath := filepath.Join(DATA_DIR, file.Filename)
destinationUrl := filepath.Join(DATA_URI, file.Filename)
dst, err := os.Create(destinationPath)
if err != nil {
return err
@ -52,6 +61,40 @@ func upload(c echo.Context) error {
return c.Render(http.StatusOK, "uploaded", map[string]string{"URI": destinationUrl})
}
func listFiles() ([]File, error) {
files := make([]File, 0)
dirEntries, err := os.ReadDir(DATA_DIR)
if err != nil {
return files, err
}
for _, dirEntry := range dirEntries {
if dirEntry.IsDir() {
continue
}
if strings.HasPrefix(dirEntry.Name(), ".") {
continue
}
files = append(files, File{
Filename: dirEntry.Name(),
URL: filepath.Join(DATA_URI, dirEntry.Name()),
})
}
return files, nil
}
func index(c echo.Context) error {
files, err := listFiles()
if err != nil {
return err
}
return c.Render(http.StatusOK, "index", map[string][]File{"Files": files})
}
func main() {
t := &Template{
templates: template.Must(template.ParseGlob("views/templates/*.html")),
@ -63,9 +106,9 @@ func main() {
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Static("/files", "files")
e.Static(DATA_URI, DATA_DIR)
e.Static("/assets", "assets")
e.File("/admin", "views/index.html")
e.GET("/admin", index)
e.POST("/admin/upload", upload)
e.Logger.Fatal(e.Start(":1323"))

View file

@ -1,3 +1,4 @@
{{define "index"}}
<!DOCTYPE html>
<html>
<head>
@ -10,7 +11,7 @@
<body>
<section class="section">
<div class="container">
<h1 class="title">Upload de fichiers</h1>
<h1 class="title is-1">Upload de fichiers</h1>
<p class="subtitle">
Enfin une solution simple que vous gérez vous même
</p>
@ -36,6 +37,31 @@
</form>
</div>
</section>
<section class="section">
<div class="container">
<h1 class="title is-4">Liste des fichiers</h1>
<table class="table is-striped is-hoverable is-fullwidth">
<thead>
<tr>
<th>Nom de fichier</th>
<th>URL</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{{ range .Files }}
<tr>
<th>{{ .Filename }}</th>
<td><a href="{{ .URL }}">{{ .URL }}</a></td>
<td></td>
</tr>
{{ end }}
</tbody>
</table>
</div>
</section>
</body>
<script>
const fileInput = document.querySelector("#file-js-example input[type=file]");
@ -47,3 +73,4 @@
};
</script>
</html>
{{end}}