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

69 lines
1.6 KiB
Go
Raw Normal View History

package http
2022-06-27 04:38:09 +04:00
import (
"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"
2023-08-13 03:18:17 +04:00
"strings"
2022-06-27 23:37:12 +04:00
2023-06-13 00:02:41 +04:00
"git.arav.su/Arav/httpr"
2022-06-27 04:38:09 +04:00
)
type FilesHandlers struct {
directoryPath string
fileServer http.Handler
noFileHandling bool
2022-06-27 04:38:09 +04:00
}
2023-06-13 00:02:41 +04:00
func New(directoryPath *string, 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,
fileServer: fSrv,
noFileHandling: noFileHandling}
2022-06-27 04:38:09 +04:00
}
func (h *FilesHandlers) Index(w http.ResponseWriter, r *http.Request) {
2023-08-13 03:18:17 +04:00
path := "/" + httpr.Param(r, "filepath")
if !strings.HasSuffix(path, "/") {
path += "/"
}
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)
2023-08-13 02:23:47 +04:00
Error(w, http.StatusNotFound, "", "", r.Referer())
2022-06-27 23:37:12 +04:00
return
}
2022-06-27 04:38:09 +04:00
web.Index("Files", utils.MainSite(r.Host), currentPath, &stats, &entries, r, w)
2022-06-27 04:38:09 +04:00
}
2023-06-13 00:02:41 +04:00
func (h *FilesHandlers) File(w http.ResponseWriter, r *http.Request) {
if h.noFileHandling {
Error(w, http.StatusServiceUnavailable, "File handling is turned off.", "", r.Referer())
2023-06-13 00:02:41 +04:00
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)
}
2023-08-13 02:23:47 +04:00
func Error(w http.ResponseWriter, code int, reason, message, referer string) {
w.WriteHeader(code)
web.ErrorXXX("/ "+http.StatusText(code), reason, message, referer, code, w)
}