From b42501a4f3907862af787dde74cf880bb180ea62 Mon Sep 17 00:00:00 2001 From: NotAShelf Date: Fri, 1 Dec 2023 21:36:03 +0300 Subject: [PATCH] style the root serve path --- .gitignore | 1 + main.go | 33 ++++++++++++++- public/template.html | 97 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 129 insertions(+), 2 deletions(-) create mode 100644 public/template.html diff --git a/.gitignore b/.gitignore index e7c4bf3..2e67b9a 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ *.dll *.so *.dylib +echo # Test binary, built with `go test -c` *.test diff --git a/main.go b/main.go index 10f3ba7..d5e32b9 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "html/template" "net/http" "os" "path/filepath" @@ -11,6 +12,13 @@ import ( "github.com/joho/godotenv" ) +var version string + +type PageData struct { + Files []string + Version string +} + func main() { err := godotenv.Load() if err != nil { @@ -33,8 +41,29 @@ func main() { return } - filePath := filepath.Join(basePath, r.URL.Path) - http.ServeFile(w, r, filePath) + if r.URL.Path == "/" { + files, err := os.ReadDir(basePath) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + fileNames := make([]string, len(files)) + for i, file := range files { + fileNames[i] = file.Name() + } + + data := PageData{ + Files: fileNames, + Version: version, + } + + tmpl := template.Must(template.ParseFiles("public/template.html")) + tmpl.Execute(w, data) + } else { + filePath := filepath.Join(basePath, r.URL.Path) + http.ServeFile(w, r, filePath) + } }) port, _ := strconv.Atoi(serverPort) diff --git a/public/template.html b/public/template.html new file mode 100644 index 0000000..943ff55 --- /dev/null +++ b/public/template.html @@ -0,0 +1,97 @@ + + + + Directory Listing + + + +

Directory Listing

+ + + + + + +