use http.ServeFile

This commit is contained in:
Ronnie Roller 2020-02-08 17:56:29 -08:00
parent 86d3df51b7
commit c422436a29
2 changed files with 11 additions and 20 deletions

View file

@ -76,7 +76,7 @@ func FetchMediaApi(w http.ResponseWriter, r *http.Request) {
}
// just take the first one
streamFileToClientById(w, response.Medias[0].Id)
streamFileToClientById(w, r, response.Medias[0].Id)
}
func getMediaResults(r *http.Request) (MediaResults, error) {

View file

@ -2,11 +2,9 @@ package media
import (
"github.com/rs/zerolog/log"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
)
/**
@ -25,25 +23,25 @@ func ServeMedia(w http.ResponseWriter, r *http.Request) {
return
}
streamFileToClientById(w, id)
streamFileToClientById(w, r, id)
}
func streamFileToClientById(w http.ResponseWriter, id string) {
func streamFileToClientById(w http.ResponseWriter, r *http.Request, id string) {
filename, err := getFileFromId(id)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
streamFileToClient(w, filename)
streamFileToClient(w, r, filename)
}
func streamFileToClient(writer http.ResponseWriter, filename string) {
func streamFileToClient(w http.ResponseWriter, r *http.Request, filename string) {
// Check if file exists and open
Openfile, err := os.Open(filename)
defer Openfile.Close() //Close after function return
if err != nil {
//File not found, send 404
http.Error(writer, "File not found.", 404)
http.Error(w, "File not found.", 404)
return
}
@ -53,30 +51,23 @@ func streamFileToClient(writer http.ResponseWriter, filename string) {
//Copy the headers into the FileHeader buffer
if _, err = Openfile.Read(fileHeader); err != nil {
log.Error().Msgf("File not found, couldn't open for reading at %s %v", filename, err)
http.Error(writer, "File not found", 404)
http.Error(w, "File not found", 404)
return
}
// Get content type of file
fileContentType := http.DetectContentType(fileHeader)
// Get the file size as a string
fileStat, _ := Openfile.Stat()
fileSize := strconv.FormatInt(fileStat.Size(), 10)
// Send the headers
writer.Header().Set("Content-Disposition", "filename="+filepath.Base(filename))
writer.Header().Set("Content-Type", fileContentType)
writer.Header().Set("Content-Length", fileSize)
w.Header().Set("Content-Disposition", "filename="+filepath.Base(filename))
w.Header().Set("Content-Type", fileContentType)
// Send the file
// We read n bytes from the file already, so we reset the offset back to 0
if _, err = Openfile.Seek(0, 0); err != nil {
log.Error().Msgf("Error seeking into file %s %v", filename, err)
http.Error(writer, "File not found", 404)
http.Error(w, "File not found", 404)
return
}
// Copy the file to the client
_, _ = io.Copy(writer, Openfile)
http.ServeFile(w, r, filename)
}