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

59 lines
1.2 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"
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-06-13 00:02:41 +04:00
path := "/" + httpr.Param(r, "filepath") + "/"
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)
return
}
2022-06-27 04:38:09 +04:00
2022-06-27 23:37:12 +04:00
web.Index(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)
}