2021-12-22 10:52:02 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
2022-03-15 13:53:24 +00:00
|
|
|
"io"
|
2021-12-22 10:52:02 +00:00
|
|
|
"net/http"
|
2022-03-15 13:53:24 +00:00
|
|
|
"path"
|
2021-12-22 10:52:02 +00:00
|
|
|
"strings"
|
2022-03-15 13:53:24 +00:00
|
|
|
"time"
|
2021-12-22 10:52:02 +00:00
|
|
|
|
2022-09-25 12:23:22 +00:00
|
|
|
"code.icb4dc0.de/prskr/goveal/assets"
|
|
|
|
"code.icb4dc0.de/prskr/goveal/fs"
|
|
|
|
"code.icb4dc0.de/prskr/goveal/web"
|
2021-12-22 10:52:02 +00:00
|
|
|
)
|
|
|
|
|
2022-03-15 13:53:24 +00:00
|
|
|
func FileSystemMiddleware(fallthroughHandler http.Handler, wdfs fs.FS) http.Handler {
|
2021-12-22 10:52:02 +00:00
|
|
|
layers := []fs.FS{wdfs}
|
|
|
|
layers = append([]fs.FS{web.WebFS, assets.Assets}, layers...)
|
|
|
|
|
|
|
|
layeredFS := fs.Layered{Layers: layers}
|
2022-03-15 13:53:24 +00:00
|
|
|
return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
|
|
|
|
reqPath := strings.TrimPrefix(req.URL.Path, "/")
|
|
|
|
if f, err := layeredFS.Open(reqPath); err != nil {
|
|
|
|
fallthroughHandler.ServeHTTP(writer, req)
|
|
|
|
return
|
|
|
|
} else if readSeeker, ok := f.(io.ReadSeeker); ok {
|
|
|
|
http.ServeContent(writer, req, path.Base(reqPath), time.Now(), readSeeker)
|
|
|
|
_ = f.Close()
|
|
|
|
} else {
|
|
|
|
_ = f.Close()
|
|
|
|
fallthroughHandler.ServeHTTP(writer, req)
|
|
|
|
}
|
2021-12-22 10:52:02 +00:00
|
|
|
})
|
|
|
|
}
|