2023-01-12 04:58:54 +04:00
|
|
|
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"
|
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 {
|
2022-06-28 01:07:46 +04:00
|
|
|
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 {
|
2022-06-28 01:07:46 +04:00
|
|
|
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{
|
2022-06-28 01:07:46 +04:00
|
|
|
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-06-13 00:02:41 +04:00
|
|
|
path := "/" + httpr.Param(r, "filepath") + "/"
|
2022-06-28 00:37:50 +04:00
|
|
|
|
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
|
|
|
|
2023-08-13 02:24:36 +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 {
|
|
|
|
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)
|
|
|
|
}
|
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)
|
|
|
|
}
|