1
0
dwelling-files/internal/handlers/handlers.go

70 lines
1.5 KiB
Go

package handlers
import (
"dwelling-files/pkg/files"
"dwelling-files/pkg/server"
"dwelling-files/pkg/utils"
"dwelling-files/web"
"log"
"net/http"
"strings"
"github.com/julienschmidt/httprouter"
)
type IndexData struct {
MainSite string
CurrentPath string
FilesTotalCount int64
FilesTotalSize string
DirectoryCount int64
Items []files.DirEntry
}
type FilesHandlers struct {
directoryPath string
assetsServer http.Handler
fileServer http.Handler
}
func New(directoryPath *string, assetsFS http.FileSystem) *FilesHandlers {
return &FilesHandlers{
directoryPath: *directoryPath,
assetsServer: http.FileServer(assetsFS),
fileServer: http.FileServer(http.Dir(*directoryPath))}
}
func (FilesHandlers) AssetsFS() http.FileSystem {
return web.Assets()
}
func (FilesHandlers) Robots(w http.ResponseWriter, r *http.Request) {
fc, _ := web.AssetsGetFile("robots.txt")
w.Write(fc)
}
func (h *FilesHandlers) Index(w http.ResponseWriter, r *http.Request) {
path := httprouter.CleanPath(server.GetURLParam(r, "filepath"))
if strings.HasPrefix(path, "/assets") {
h.assetsServer.ServeHTTP(w, r)
return
}
if strings.HasPrefix(path, "/file") {
r.URL.Path = path[5:]
h.fileServer.ServeHTTP(w, r)
return
}
currentPath := files.CurrentPath(path)
entries, stats, err := files.ScanDirectory(h.directoryPath+path, path)
if err != nil {
log.Println(err)
return
}
web.Index(utils.MainSite(r.Host), currentPath, &stats, &entries, r, w)
}