feat(encode): add mime-type headers to cache handlers

* feat(encode): add mime-type headers to cache handlers

This commit adds a simple MIME-type guessing logic to `onCacheHit` and
`onCacheMiss` handlers, which sets `Content-Type` HTTP response header based on
format specified by transcoding profile.

* Make cacheFile stat() error fatal

Co-authored-by: Senan Kelly <senan@senan.xyz>

* Make linter happy

Good morning to you too, mister linter!

Co-authored-by: Senan Kelly <senan@senan.xyz>

Co-authored-by: Senan Kelly <senan@senan.xyz>
This commit is contained in:
Serge Tkatchouk
2021-06-22 06:36:17 +08:00
committed by GitHub
parent 5444d40018
commit 4109b5b66c

View File

@@ -17,6 +17,7 @@ import (
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
"go.senan.xyz/gonic/server/db"
"go.senan.xyz/gonic/server/encode"
"go.senan.xyz/gonic/server/mime"
)
// "raw" handlers are ones that don't always return a spec response.
@@ -231,12 +232,23 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
onCacheHit := func(profile encode.Profile, path string) error {
log.Printf("serving transcode `%s`: cache [%s/%dk] hit!\n",
audioFile.AudioFilename(), profile.Format, profile.Bitrate)
cacheMime, _ := mime.FromExtension(profile.Format)
w.Header().Set("Content-Type", cacheMime)
cacheFile, err := os.Stat(path)
if err != nil {
return fmt.Errorf("failed to stat cache file `%s`: %w", path, err)
}
contentLength := fmt.Sprintf("%d", cacheFile.Size())
w.Header().Set("Content-Length", contentLength)
http.ServeFile(w, r, path)
return nil
}
onCacheMiss := func(profile encode.Profile) (io.Writer, error) {
log.Printf("serving transcode `%s`: cache [%s/%dk] miss!\n",
audioFile.AudioFilename(), profile.Format, profile.Bitrate)
encodeMime, _ := mime.FromExtension(profile.Format)
w.Header().Set("Content-Type", encodeMime)
return w, nil
}
encodeOptions := encode.Options{