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

73 lines
1.5 KiB
Go
Raw Normal View History

2022-06-27 04:38:09 +04:00
package handlers
import (
"dwelling-files/pkg/files"
2022-06-27 23:37:12 +04:00
"dwelling-files/pkg/server"
"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"
"strings"
2022-06-27 23:37:12 +04:00
"github.com/julienschmidt/httprouter"
2022-06-27 04:38:09 +04:00
)
type FilesHandlers struct {
directoryPath string
assetsServer http.Handler
fileServer http.Handler
noFileHandling bool
2022-06-27 04:38:09 +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{
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 (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) {
2022-06-27 23:37:12 +04:00
path := httprouter.CleanPath(server.GetURLParam(r, "filepath"))
if strings.HasPrefix(path, "/assets") {
h.assetsServer.ServeHTTP(w, r)
return
}
if strings.HasPrefix(path, "/file") {
if h.noFileHandling {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
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
}