118 lines
2.2 KiB
Go
118 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"html/template"
|
|
"io"
|
|
"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
|
|
}
|
|
|
|
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
|
|
return t.templates.ExecuteTemplate(w, name, data)
|
|
}
|
|
|
|
func upload(c echo.Context) error {
|
|
// Source
|
|
file, err := c.FormFile("file")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
src, err := file.Open()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer src.Close()
|
|
|
|
// Destination
|
|
destinationPath := filepath.Join(DATA_DIR, file.Filename)
|
|
destinationUrl := filepath.Join(DATA_URI, file.Filename)
|
|
dst, err := os.Create(destinationPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer dst.Close()
|
|
|
|
// Copy
|
|
if _, err = io.Copy(dst, src); err != nil {
|
|
return err
|
|
}
|
|
|
|
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 remove(c echo.Context) error {
|
|
filename := c.FormValue("Filename")
|
|
os.Remove(filepath.Join(DATA_DIR, filename))
|
|
return c.Redirect(http.StatusTemporaryRedirect, "/admin")
|
|
}
|
|
|
|
func main() {
|
|
t := &Template{
|
|
templates: template.Must(template.ParseGlob("views/templates/*.html")),
|
|
}
|
|
|
|
e := echo.New()
|
|
|
|
e.Renderer = t
|
|
e.Use(middleware.Logger())
|
|
e.Use(middleware.Recover())
|
|
|
|
e.Static(DATA_URI, DATA_DIR)
|
|
e.Static("/assets", "assets")
|
|
e.GET("/admin", index)
|
|
e.POST("/admin/upload", upload)
|
|
e.GET("/admin/remove", remove)
|
|
|
|
e.Logger.Fatal(e.Start(":1323"))
|
|
}
|