From f94c28db9714ac19934b7f104780aeaa9bd0ee64 Mon Sep 17 00:00:00 2001 From: Julian Hurst Date: Sat, 25 Jan 2025 14:14:05 +0100 Subject: Disable listing resources by default and add a -i flag for enabling it --- main.go | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index 68037e8..75f958d 100644 --- a/main.go +++ b/main.go @@ -12,6 +12,8 @@ import ( "path/filepath" "flag" "bufio" + "errors" + "io/fs" "github.com/google/uuid" ) @@ -27,6 +29,7 @@ type BoxHandler struct { filesPath string token string deleteEnabled bool + index bool } func serve(w http.ResponseWriter, token string, views ...string) { @@ -50,7 +53,25 @@ func (handler BoxHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { serve(w, handler.token, "templates/index.html") } else { resourceId := path.Base(r.URL.Path) - http.ServeFile(w, r, filepath.Join(handler.filesPath, resourceId)) + resourcePath := filepath.Join(handler.filesPath, resourceId) + fi, err := os.Stat(resourcePath) + if errors.Is(err, fs.ErrNotExist) { + log.Println(err) + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, err) + return + } else if err != nil { + log.Println(err) + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err) + return + } + if fi.IsDir() && !handler.index { + log.Println("Index requested but not enabled") + w.WriteHeader(http.StatusNotFound) + return + } + http.ServeFile(w, r, resourcePath) } return case http.MethodDelete: @@ -119,6 +140,7 @@ func main() { isToken := flag.Bool("t", false, "Use a token to protect uploads/deletes") filesPath := flag.String("d", "", "The path to the files") deleteEnabled := flag.Bool("D", false, "Enable deleting resources") + index := flag.Bool("i", false, "Enable displaying the resource folder index") flag.Parse() token := "" @@ -136,6 +158,7 @@ func main() { *filesPath, token, *deleteEnabled, + *index, } if boxHandler.filesPath != "" { err := os.MkdirAll(boxHandler.filesPath, 0750) -- cgit v1.2.3