spa-handler/handler.go
2025-05-05 20:24:05 +02:00

49 lines
1.0 KiB
Go

package spa_handler
import (
"embed"
"fmt"
"net/http"
"os"
)
type handler struct {
staticFS embed.FS
indexPath string
}
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
reqPath := r.URL.Path
f, err := h.staticFS.Open(fmt.Sprintf("ng-client/browser%s", reqPath))
if f != nil {
f.Close()
}
if os.IsNotExist(err) {
indexFile, indexErr := h.staticFS.Open(h.indexPath)
if indexErr != nil {
http.Error(w, "Index file not found", http.StatusInternalServerError)
return
}
defer indexFile.Close()
tryToDeliverFile(indexFile, h.indexPath, w, r)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tryToDeliverFile(f, h.indexPath, w, r)
}
func HandleFiles(path string, options HandlerOptions) {
if options.AdditionalMimeTypeMapping != nil {
for key, value := range options.AdditionalMimeTypeMapping {
contentTypeMapping[key] = value
}
}
http.Handle(path, handler{
staticFS: options.Files,
indexPath: options.IndexPath,
})
}