2022-06-27 04:38:09 +04:00
|
|
|
package handlers
|
|
|
|
|
|
|
|
import (
|
2022-10-31 01:46:55 +04:00
|
|
|
"dwelling-files/internal/server"
|
2022-06-27 04:38:09 +04:00
|
|
|
"dwelling-files/pkg/files"
|
2022-06-27 23:37:12 +04:00
|
|
|
"dwelling-files/pkg/utils"
|
2022-06-27 04:38:09 +04:00
|
|
|
"dwelling-files/web"
|
2022-06-27 23:37:12 +04:00
|
|
|
"log"
|
2022-06-27 04:38:09 +04:00
|
|
|
"net/http"
|
2022-06-28 00:37:50 +04:00
|
|
|
"strings"
|
2022-06-27 23:37:12 +04:00
|
|
|
|
|
|
|
"github.com/julienschmidt/httprouter"
|
2022-06-27 04:38:09 +04:00
|
|
|
)
|
|
|
|
|
|
|
|
type FilesHandlers struct {
|
2022-06-28 01:07:46 +04:00
|
|
|
directoryPath string
|
|
|
|
assetsServer http.Handler
|
|
|
|
fileServer http.Handler
|
|
|
|
noFileHandling bool
|
2022-06-27 04:38:09 +04:00
|
|
|
}
|
|
|
|
|
2022-06-28 01:07:46 +04:00
|
|
|
func New(directoryPath *string, assetsFS http.FileSystem, noFileHandling bool) *FilesHandlers {
|
|
|
|
var fSrv http.Handler
|
|
|
|
if noFileHandling {
|
|
|
|
fSrv = nil
|
|
|
|
} else {
|
|
|
|
fSrv = http.FileServer(http.Dir(*directoryPath))
|
|
|
|
}
|
2022-06-27 04:38:09 +04:00
|
|
|
return &FilesHandlers{
|
2022-06-28 01:07:46 +04:00
|
|
|
directoryPath: *directoryPath,
|
|
|
|
assetsServer: http.FileServer(assetsFS),
|
|
|
|
fileServer: fSrv,
|
|
|
|
noFileHandling: noFileHandling}
|
2022-06-27 04:38:09 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (FilesHandlers) AssetsFS() http.FileSystem {
|
|
|
|
return web.Assets()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *FilesHandlers) Index(w http.ResponseWriter, r *http.Request) {
|
2022-06-27 23:37:12 +04:00
|
|
|
path := httprouter.CleanPath(server.GetURLParam(r, "filepath"))
|
|
|
|
|
2022-06-28 00:37:50 +04:00
|
|
|
if strings.HasPrefix(path, "/assets") {
|
|
|
|
h.assetsServer.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-12-17 21:46:54 +04:00
|
|
|
if strings.HasPrefix(path, "/robots.txt") {
|
|
|
|
fc, _ := web.AssetsGetFile("robots.txt")
|
|
|
|
w.Write(fc)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-06-28 00:37:50 +04:00
|
|
|
if strings.HasPrefix(path, "/file") {
|
2022-06-28 01:07:46 +04:00
|
|
|
if h.noFileHandling {
|
|
|
|
w.WriteHeader(http.StatusServiceUnavailable)
|
|
|
|
return
|
|
|
|
}
|
2022-06-28 00:37:50 +04:00
|
|
|
r.URL.Path = path[5:]
|
|
|
|
h.fileServer.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-06-27 23:37:12 +04:00
|
|
|
currentPath := files.CurrentPath(path)
|
|
|
|
|
|
|
|
entries, stats, err := files.ScanDirectory(h.directoryPath+path, path)
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
return
|
|
|
|
}
|
2022-06-27 04:38:09 +04:00
|
|
|
|
2022-06-27 23:37:12 +04:00
|
|
|
web.Index(utils.MainSite(r.Host), currentPath, &stats, &entries, r, w)
|
2022-06-27 04:38:09 +04:00
|
|
|
}
|