+// Download a book, based on the path stored in the DB
+func handleBook(w http.ResponseWriter, r *http.Request) {
+ path := r.URL.Path[1:]
+ tok := strings.Split(path, "/")
+ if 2 != len(tok) {
+ fmt.Fprintln(w, "Unexpected path for book download:", path)
+ return
+ }
+
+ bookId, err := strconv.Atoi(tok[1])
+ if (nil != err) || (0 == bookId) {
+ fmt.Fprintln(w, "Invalid id for book download:", path, err)
+ return
+ }
+
+ bookPath := queryBookPathById(bookId)
+ if 0 == len(bookPath) {
+ fmt.Fprintln(w, "No book for ID:", bookId)
+ return
+ }
+
+ bookFileName := filepath.Base(bookPath)
+
+ mimeType := bookMimeType(bookPath)
+ if 0 == len(mimeType) {
+ fmt.Fprintln(w, "Failed to determine MIME type for book:", bookPath)
+ return
+ }
+
+ var info os.FileInfo
+ info, err = os.Stat(bookPath)
+ if nil != err {
+ fmt.Fprintln(w, "Failed to read file metadata:", bookPath, err)
+ return
+ }
+ modTime := info.ModTime()
+
+ var fd *os.File
+ fd, err = os.Open(bookPath)
+ if nil != err {
+ fmt.Fprintln(w, "Failed to open file:", bookPath, err)
+ return
+ }
+ defer fd.Close()
+
+ // TODO: handle non-ASCII file names. Need to look up the permutations on how to encode that.
+ w.Header().Set("Content-Disposition", "attachment; filename=" + bookFileName)
+ w.Header().Set("Content-Type", mimeType)
+ http.ServeContent(w, r, bookFileName, modTime, fd)
+}
+