From 5ba68fae053ccabc3161ee4f80963ac0c47ddaf2 Mon Sep 17 00:00:00 2001 From: Nguyễn Gia Phong Date: Tue, 28 Jun 2022 15:27:06 +0900 Subject: Polish up for a release --- main.go | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'main.go') diff --git a/main.go b/main.go index 42db6d2..b364d20 100644 --- a/main.go +++ b/main.go @@ -37,11 +37,13 @@ var static embed.FS //go:embed templates/*.html var templates embed.FS +// Type Page represents a comic page. type Page struct { Index int Name string } +// Type Archive represents a comic book zip archive. type Archive struct { Title string Prev string @@ -49,15 +51,19 @@ type Archive struct { Entries []Page } +// Type Directory represents a library directory in file system. type Directory struct { Title string Entries []string } +// Function escape ensures that question marks in path +// are not recognized as URL parameters. func escape(name string) template.URL { return template.URL(strings.Replace(name, "?", "%3f", -1)) } +// Function find searches for the directory entry of given name. func find(entries []os.DirEntry, name string) int { for i, entry := range entries { if entry.Name() == name { @@ -67,6 +73,8 @@ func find(entries []os.DirEntry, name string) int { return -1 } +// Function main starts Phylactery serving comics from PHYLACTERY_LIBRARY +// and listening on PHYLACTERY_ADDRESS. func main() { http.Handle("/static/", http.FileServer(http.FS(static))) t, err := template.New("").Funcs(template.FuncMap{ @@ -85,12 +93,15 @@ func main() { } if stat.IsDir() { + // Redirect URL without a trailing slash + // pointing to a non-directory page if !strings.HasSuffix(r.URL.Path, "/") { http.Redirect(w, r, r.URL.Path+"/", http.StatusMovedPermanently) return } + // Render directory page entries, _ := os.ReadDir(p) var names []string for _, entry := range entries { @@ -104,12 +115,14 @@ func main() { t.ExecuteTemplate(w, "directory.html", dir) return } else if strings.HasSuffix(r.URL.Path, "/") { + // Redirect URL with a trailing slash + // pointing to a non-directory page http.Redirect(w, r, r.URL.Path[:len(r.URL.Path)-1], http.StatusMovedPermanently) return } - // TODO: LRU caching + // Check if file is a valid ZIP archive cbz, err := zip.OpenReader(p) if err != nil { http.Error(w, "invalid cbz", http.StatusNotAcceptable) @@ -117,6 +130,7 @@ func main() { } defer cbz.Close() + // Respond with an image inside the CBZ r.ParseForm() if entry, isImage := r.Form["entry"]; isImage { i, err := strconv.Atoi(entry[0]) @@ -130,6 +144,7 @@ func main() { return } + // Render archive page entries, _ := os.ReadDir(path.Join(p, "..")) index := find(entries, stat.Name()) var pages []Page -- cgit 1.4.1