54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
package staticssterver
|
|
|
|
import (
|
|
"fmt"
|
|
"io/fs"
|
|
"net/http"
|
|
"os"
|
|
|
|
"git.maronato.dev/maronato/goshort/internal/config"
|
|
)
|
|
|
|
type StaticHandler struct {
|
|
assetServer http.Handler
|
|
}
|
|
|
|
func NewStaticHandler(_ *config.Config, prefix string, assets fs.FS) *StaticHandler {
|
|
// Create the root filesystem
|
|
root := http.FS(assets)
|
|
|
|
// Create the SPA filesystem
|
|
root = &spaFileSystem{root}
|
|
|
|
// Build the asset server
|
|
assetServer := http.StripPrefix(prefix, http.FileServer(root))
|
|
|
|
return &StaticHandler{
|
|
assetServer: assetServer,
|
|
}
|
|
}
|
|
|
|
func (h *StaticHandler) ServeFiles(w http.ResponseWriter, r *http.Request) {
|
|
// Serve the files
|
|
h.assetServer.ServeHTTP(w, r)
|
|
}
|
|
|
|
// spaFileSystem overrides the Open method to use index.html as the default file.
|
|
type spaFileSystem struct {
|
|
root http.FileSystem
|
|
}
|
|
|
|
func (spa *spaFileSystem) Open(name string) (http.File, error) {
|
|
file, err := spa.root.Open(name)
|
|
|
|
if os.IsNotExist(err) {
|
|
file, err = spa.root.Open("index.html")
|
|
}
|
|
|
|
if err != nil {
|
|
return nil, fmt.Errorf("could not open filesystem file: %w", err)
|
|
}
|
|
|
|
return file, nil
|
|
}
|