73 lines
1.5 KiB
Go
73 lines
1.5 KiB
Go
package http
|
|
|
|
import (
|
|
"dwelling-files/pkg/files"
|
|
"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 (h *FilesHandlers) Index(w http.ResponseWriter, r *http.Request) {
|
|
path := httprouter.CleanPath(GetURLParam(r, "filepath"))
|
|
|
|
if strings.HasPrefix(path, "/assets") {
|
|
h.assetsServer.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
if strings.HasPrefix(path, "/robots.txt") {
|
|
fc, _ := web.AssetsGetFile("robots.txt")
|
|
w.Write(fc)
|
|
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)
|
|
}
|