From 3b324a97332720b9f8ffd377ae22417b0973e7bb Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Tue, 28 Jun 2022 01:07:46 +0400 Subject: [PATCH] Added ability to disable file serving if it is handled by some other service (e.g. NGiNX). --- cmd/dwelling-files/main.go | 3 ++- internal/handlers/handlers.go | 26 +++++++++++++++++++------- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/cmd/dwelling-files/main.go b/cmd/dwelling-files/main.go index b64d8a7..5a67f7e 100644 --- a/cmd/dwelling-files/main.go +++ b/cmd/dwelling-files/main.go @@ -16,6 +16,7 @@ import ( var listenAddress *string = flag.String("listen", "/var/run/dwelling-files/f.sock", "listen address (ip:port|unix_path)") var directoryPath *string = flag.String("path", "/srv/ftp", "path to file share") +var disableFileHandler *bool = flag.Bool("no-file-handling", false, "disable file handling if it is handled by something else (e.g. NGiNX)") var showVersion *bool = flag.Bool("v", false, "show version") func main() { @@ -27,7 +28,7 @@ func main() { return } - hand := handlers.New(directoryPath, web.Assets()) + hand := handlers.New(directoryPath, web.Assets(), *disableFileHandler) srv := server.NewHttpServer() srv.GET("/*filepath", hand.Index) diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go index 7741eb0..5927188 100644 --- a/internal/handlers/handlers.go +++ b/internal/handlers/handlers.go @@ -22,16 +22,24 @@ type IndexData struct { } type FilesHandlers struct { - directoryPath string - assetsServer http.Handler - fileServer http.Handler + directoryPath string + assetsServer http.Handler + fileServer http.Handler + noFileHandling bool } -func New(directoryPath *string, assetsFS http.FileSystem) *FilesHandlers { +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: http.FileServer(http.Dir(*directoryPath))} + directoryPath: *directoryPath, + assetsServer: http.FileServer(assetsFS), + fileServer: fSrv, + noFileHandling: noFileHandling} } func (FilesHandlers) AssetsFS() http.FileSystem { @@ -52,6 +60,10 @@ func (h *FilesHandlers) Index(w http.ResponseWriter, r *http.Request) { } if strings.HasPrefix(path, "/file") { + if h.noFileHandling { + w.WriteHeader(http.StatusServiceUnavailable) + return + } r.URL.Path = path[5:] h.fileServer.ServeHTTP(w, r) return