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 FilesHandlers struct { directoryPath string assetsServer http.Handler fileServer http.Handler noFileHandling bool } 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)) } return &FilesHandlers{ directoryPath: *directoryPath, assetsServer: http.FileServer(assetsFS), fileServer: fSrv, noFileHandling: noFileHandling} } 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") { if h.noFileHandling { w.WriteHeader(http.StatusServiceUnavailable) return } 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) }