58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
package spa_handler
|
|
|
|
import (
|
|
"bytes"
|
|
"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
|
|
}
|
|
modified := []byte{}
|
|
for _, a := range appender {
|
|
modified = append(modified, []byte(a)...)
|
|
}
|
|
modified = append(modified, content...)
|
|
|
|
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(modified)
|
|
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
|
|
}
|