From 2943fd474a205a93c9f7d5633a7102fcd75d9ebe Mon Sep 17 00:00:00 2001 From: "Timofey.Kovalev" Date: Tue, 14 Jan 2020 15:16:03 +0300 Subject: [PATCH] add readme.txt support --- handler.go | 21 ++++++++++++++++++--- main.html | 14 ++++++++++++++ struct.go | 1 + 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/handler.go b/handler.go index 1bfe4ca..93782a2 100644 --- a/handler.go +++ b/handler.go @@ -3,10 +3,12 @@ package main import ( "fmt" "html/template" + "io/ioutil" "net/http" "net/url" "os" "path" + "path/filepath" "sort" "strings" ) @@ -58,7 +60,6 @@ func toHTTPError(err error) (msg string, httpStatus int) { } func serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, name string) { - f, err := fs.Open(name) if err != nil { msg, code := toHTTPError(err) @@ -85,7 +86,7 @@ func serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, name // Still a directory? (we didn't find an index.html file) if d.IsDir() { - dirList(w, r, f, name) + dirList(w, r, f, name, fs) return } @@ -94,7 +95,7 @@ func serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, name http.ServeContent(w, r, d.Name(), d.ModTime(), f) } -func dirList(w http.ResponseWriter, r *http.Request, f http.File, name string) { +func dirList(w http.ResponseWriter, r *http.Request, f http.File, name string, fs http.FileSystem) { dirs, err := f.Readdir(-1) if err != nil { renderError(w, "Error reading directory", http.StatusInternalServerError) @@ -119,6 +120,7 @@ func dirList(w http.ResponseWriter, r *http.Request, f http.File, name string) { Title: name, IsRoot: name == "/", Files: make([]*File, 0, len(dirs)), + Readme: loadReadmeFile(name, fs), } for _, d := range dirs { @@ -150,6 +152,19 @@ func dirList(w http.ResponseWriter, r *http.Request, f http.File, name string) { } +func loadReadmeFile(path string, fs http.FileSystem) string { + f, err := fs.Open(filepath.Join(path, "readme.txt")) + if err != nil { + return "" + } + + defer f.Close() + + data, err := ioutil.ReadAll(f) + + return string(data) +} + type fileHandler struct { root string } diff --git a/main.html b/main.html index 5b9e10a..27d42dc 100644 --- a/main.html +++ b/main.html @@ -50,6 +50,20 @@ {{end}} + + {{if .Readme}} +
+
+ readme.txt +
+
+

{{.Readme}}

+
+
+ +
+ {{end}} + diff --git a/struct.go b/struct.go index 4c6b7ee..ced44af 100644 --- a/struct.go +++ b/struct.go @@ -14,4 +14,5 @@ type Data struct { Title string IsRoot bool Files []*File + Readme string }