Compare commits

...

4 commits

2 changed files with 15 additions and 7 deletions

View file

@ -1,6 +1,7 @@
package server
import (
"fmt"
"log"
"os"
"regexp"
@ -102,12 +103,14 @@ func serveMediaDirectory(w http.ResponseWriter, req *http.Request) {
http.Error(w, "is a directory; maybe you are looking for " + path, http.StatusForbidden)
return
}
f, err := os.Open(filePath)
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
util.DoChunks(f, func (buf []byte) { w.Write(buf) })
defer f.Close()
util.DoChunks(f, 4, func (buf []byte) { w.Write(buf) })
}
func handleArtistAlbumPage(w http.ResponseWriter, req *http.Request) {
@ -163,15 +166,19 @@ func handleArtistAlbumPage(w http.ResponseWriter, req *http.Request) {
if musicindex.ArtistExists(artist) {
album, ok := musicindex.FindArtist(artist).Albums[albumName]
if ok {
contents, err := os.ReadFile(album.Tarball)
f, err := os.Open(album.Tarball)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
http.Error(w, "internal server error: " + err.Error(),
http.StatusInternalServerError)
return
}
defer f.Close()
w.Header().Set("Content-Disposition", `attachment; filename="` +
strings.ReplaceAll(album.Name, `"`, `'`) + `.tar.gz"`)
w.Write(contents)
w.Header().Set("Content-Length",
fmt.Sprintf("%d", album.TarballSize))
util.DoChunks(f, 4 * 1024, func (buf []byte) { w.Write(buf) })
return
}
}

View file

@ -26,6 +26,7 @@ func Dirents(dir string) (entries []string, err error) {
if err != nil {
return nil, errors.New(err.Error())
}
defer d.Close()
names, err := d.Readdirnames(0)
if err != nil {
@ -39,11 +40,11 @@ func Dirents(dir string) (entries []string, err error) {
return
}
func DoChunks(f io.Reader, fun func (buf []byte)) (err error) {
func DoChunks(f io.Reader, kib uint, fun func (buf []byte)) (err error) {
err = nil
bytes, chunks := int64(0), int64(0)
r := bufio.NewReader(f)
buf := make([]byte, 0, 4*1024)
buf := make([]byte, 0, kib * 1024)
for {
var n int