Files
MusicServer/pkg/helpers/helpers.go

75 lines
2.0 KiB
Go

package helpers
import (
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
)
func SetCorsAndNoCacheHeaders(w *http.ResponseWriter, r *http.Request) {
var etagHeaders = []string{
"ETag",
"If-Modified-Since",
"If-Match",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
}
(*w).Header().Set("Expires", "Tue, 03 Jul 2001 06:00:00 GMT")
(*w).Header().Set("Last-Modified", time.Now().String()+" GMT")
(*w).Header().Set("Cache-Control", "no-cache, no-store, private, max-age=0")
(*w).Header().Set("Pragma", "no-cache")
(*w).Header().Set("X-Accel-Expires", "0")
(*w).Header().Set("Access-Control-Allow-Origin", "*")
for _, v := range etagHeaders {
if r.Header.Get(v) != "" {
r.Header.Del(v)
}
}
}
func SendSong(writer http.ResponseWriter, Filename string) {
fmt.Println("Client requests: " + Filename)
//Check if file exists and open
openFile, err := os.Open(Filename)
if err != nil {
//File not found, send 404
http.Error(writer, "Song not found.", 404)
return
}
defer func(openFile *os.File) {
_ = openFile.Close()
}(openFile) //Close after function return
//File is found, create and send the correct headers
//Get the Content-Type of the file
//Create a buffer to store the header of the file in
FileHeader := make([]byte, 512)
//Copy the headers into the FileHeader buffer
_, _ = openFile.Read(FileHeader)
//Get content type of file
//FileContentType := http.DetectContentType(FileHeader)
//Get the file size
FileStat, _ := openFile.Stat() //Get info from file
FileSize := strconv.FormatInt(FileStat.Size(), 10) //Get file size as a string
//Send the headers
//writer.Header().Set("Content-Disposition", "attachment; filename="+Filename)
writer.Header().Set("Content-Type", "audio/mpeg")
writer.Header().Set("Content-Length", FileSize)
//Send the file
//We read 512 bytes from the file already, so we reset the offset back to 0
_, _ = openFile.Seek(0, 0)
_, _ = io.Copy(writer, openFile) //'Copy' the file to the client
return
}