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

69 lines
1.5 KiB
Go

package http
import (
"dwelling-files/pkg/files"
"dwelling-files/pkg/utils"
"dwelling-files/web"
"log"
"net/http"
"strings"
"git.arav.su/Arav/httpr"
)
type FilesHandlers struct {
directoryPath string
fileServer http.Handler
noFileHandling bool
}
func New(directoryPath *string, noFileHandling bool) *FilesHandlers {
var fSrv http.Handler
if noFileHandling {
fSrv = nil
} else {
fSrv = http.FileServer(http.Dir(*directoryPath))
}
return &FilesHandlers{
directoryPath: *directoryPath,
fileServer: fSrv,
noFileHandling: noFileHandling}
}
func (h *FilesHandlers) Index(w http.ResponseWriter, r *http.Request) {
path := "/" + httpr.Param(r, "filepath")
if !strings.HasSuffix(path, "/") {
path += "/"
}
currentPath := files.CurrentPath(path)
entries, stats, err := files.ScanDirectory(h.directoryPath+path, path)
if err != nil {
log.Println(err)
Error(w, http.StatusNotFound, "", "", r.Referer())
return
}
web.Index("Files", utils.MainSite(r.Host), currentPath, &stats, &entries, r, w)
}
func (h *FilesHandlers) File(w http.ResponseWriter, r *http.Request) {
if h.noFileHandling {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
r.URL.Path = httpr.Param(r, "filepath")
h.fileServer.ServeHTTP(w, r)
}
func RobotsTxt(w http.ResponseWriter, r *http.Request) {
fc, _ := web.AssetsGetFile("robots.txt")
w.Write(fc)
}
func Error(w http.ResponseWriter, code int, reason, message, referer string) {
w.WriteHeader(code)
web.ErrorXXX("/ "+http.StatusText(code), reason, message, referer, code, w)
}