spa-handler/spa/helper.go
2025-05-05 20:08:29 +02:00

47 lines
1.1 KiB
Go

package spa
import (
"io"
"io/fs"
"net/http"
"strings"
)
func tryToDeliverFile(file fs.File, path string, w http.ResponseWriter, r *http.Request) {
fileSeeker, ok := file.(io.ReadSeeker)
if !ok {
file.Close()
http.Error(w, "Index file does not implement ReadSeeker", http.StatusInternalServerError)
return
}
stats, statErr := file.Stat()
if statErr != nil {
http.Error(w, "Cannot stat index file", http.StatusInternalServerError)
return
}
contentType, contentTypeErr := detectContentType(file)
if contentTypeErr != nil {
contentType = "text/html"
}
contentType = getContentTypeDetail(contentType, stats)
w.Header().Set("Content-Type", contentType)
http.ServeContent(w, r, path, stats.ModTime(), fileSeeker)
}
func detectContentType(file fs.File) (string, error) {
buffer := []byte{}
_, err := file.Read(buffer)
if err != nil {
return "", err
}
return http.DetectContentType(buffer), nil
}
func getContentTypeDetail(contentType string, info fs.FileInfo) string {
for ending, realContentType := range contentTypeMapping {
if strings.HasSuffix(info.Name(), ending) {
return realContentType
}
}
return contentType
}