+// Download a book, based on the path stored in the DB
+func handleBook(w http.ResponseWriter, r *http.Request) {
+ fmt.Println("handleBook:", r.URL.Path)
+ path := r.URL.Path[1:]
+ tok := strings.Split(path, "/")
+ if 2 != len(tok) {
+ handleError(w, fmt.Sprintf("Unexpected path for book download: %s\n", path))
+ return
+ }
+
+ bookId, err := strconv.Atoi(tok[1])
+ if (nil != err) || (0 == bookId) {
+ msg := fmt.Sprintf("Invalid id for book download: \"%s\" (%s)\n", path, err.Error())
+ handleError(w, msg)
+ return
+ }
+
+ bookPath := queryBookPathById(bookId)
+ if 0 == len(bookPath) {
+ handleError(w, fmt.Sprintf("No book for ID: %s\n", bookId))
+ return
+ }
+
+ bookFileName := filepath.Base(bookPath)
+
+ mimeType := bookMimeType(bookPath)
+ if 0 == len(mimeType) {
+ handleError(w, fmt.Sprintf("Failed to determine MIME type for book: %s\n", bookPath))
+ return
+ }
+
+ var info os.FileInfo
+ info, err = os.Stat(bookPath)
+ if nil != err {
+ handleError(w, fmt.Sprintf("Failed to read file metadata: \"%s\" (%s)\n", bookPath, err.Error()))
+ return
+ }
+ modTime := info.ModTime()
+
+ var fd *os.File
+ fd, err = os.Open(bookPath)
+ if nil != err {
+ handleError(w, fmt.Sprintf("Failed to open file: \"%s\" (%s)\n", bookPath, err.Error()))
+ 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)
+}
+
+func handleDownload(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 download:", path)
+ return
+ }
+ efsId, err := strconv.Atoi(tok[1])
+ if (nil != err) || (0 == efsId) {
+ fmt.Fprintln(w, "Invalid id for download:", path, err)
+ return
+ }
+
+ mimeType := queryMimeTypeByEfsId(efsId)
+ if 0 == len(mimeType) {
+ fmt.Fprintln(w, "No MIME type found for id:", efsId)
+ return
+ }
+
+ efsPath := efsPathForId(efsId)
+
+ var fd *os.File
+ fd, err = os.Open(efsPath)
+ if nil != err {
+ fmt.Fprintln(w, "Failed to read file for id:", efsId, err)
+ return
+ }
+ defer fd.Close()
+
+ w.Header().Set("Content-Type", mimeType)
+ io.Copy(w, fd)
+}
+
+func handleError(w http.ResponseWriter, msg string) {
+ fmt.Printf("ERROR: %s", msg)
+ http.Error(w, msg, http.StatusInternalServerError)
+}
+