goveal/api/reveal.go

34 lines
855 B
Go
Raw Normal View History

package api
import (
2022-03-15 13:53:24 +00:00
"io"
"net/http"
2022-03-15 13:53:24 +00:00
"path"
"strings"
2022-03-15 13:53:24 +00:00
"time"
"github.com/baez90/goveal/assets"
"github.com/baez90/goveal/fs"
"github.com/baez90/goveal/web"
)
2022-03-15 13:53:24 +00:00
func FileSystemMiddleware(fallthroughHandler http.Handler, wdfs fs.FS) http.Handler {
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)
}
})
}