spa-handler/helper.go
2025-06-06 21:06:38 +02:00

59 lines
1.4 KiB
Go

package spa_handler
import (
"bytes"
"fmt"
"io"
"io/fs"
"net/http"
"strings"
"time"
)
func tryToDeliverFile(file fs.File, path string, w http.ResponseWriter, r *http.Request, appender ...string) {
content, err := io.ReadAll(file)
if err != nil {
file.Close()
http.Error(w, "can not read file", http.StatusInternalServerError)
return
}
merge := bytes.NewBuffer([]byte{})
for _, a := range appender {
merge.WriteString(a)
}
newContent := strings.Replace(string(content), "</html>", fmt.Sprintf("%s\n</html>", merge.String()), 1)
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)
fileSeeker := bytes.NewReader([]byte(newContent))
w.Header().Set("Content-Type", contentType)
http.ServeContent(w, r, path, time.Now(), 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
}