Skip to content

Commit 0526334

Browse files
Use generic fs (#63)
* Use generic fs * Expose MountEmbeddedFS
1 parent 4fadb73 commit 0526334

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

static/static.go

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
package static
1616

1717
import (
18-
"embed"
1918
"fmt"
2019
"io/fs"
2120
"net/http"
@@ -24,11 +23,11 @@ import (
2423

2524
const PublicFSDirSegment = "public"
2625

27-
// PublicHandler returns an http.Handler that serves embedded files under the
28-
// "public/" subdirectory of the provided embed.FS. URL prefix should begin and
26+
// PublicHandler returns an http.Handler that serves files under the
27+
// "public/" subdirectory of the provided fs.FS. URL prefix should begin and
2928
// end with "/" e.g. /v1/public/
30-
func PublicHandler(staticFS embed.FS, mountPrefix string) (http.Handler, error) {
31-
return publicContentHandler(staticFS, PublicFSDirSegment, CleanPathPrefix(mountPrefix))
29+
func PublicHandler(staticFS fs.FS, mountPrefix string) (http.Handler, error) {
30+
return MountEmbeddedFS(staticFS, PublicFSDirSegment, CleanPathPrefix(mountPrefix))
3231
}
3332

3433
// CleanPathPrefix normalizes a URL path prefix, ensuring it starts
@@ -42,7 +41,7 @@ func CleanPathPrefix(prefix string) string {
4241
return p
4342
}
4443

45-
// staticContentHandlerreturns an http.Handler that serves embedded files from a
44+
// MountEmbeddedFS an http.Handler that serves embedded files from a
4645
// subdirectory within the embed.FS (e.g., "static") and maps them to a given URL prefix.
4746
//
4847
// For example:
@@ -54,15 +53,22 @@ func CleanPathPrefix(prefix string) string {
5453
// staticContentHandler(staticFS, "static", "assets")
5554
//
5655
// Then a request to /assets/index.html will serve embedded file "static/index.html".
57-
func publicContentHandler(embeddedFS embed.FS, subdir, urlPrefix string) (http.Handler, error) {
58-
56+
func MountEmbeddedFS(embeddedFS fs.FS, subdir, urlPrefix string) (http.Handler, error) {
5957
cleanStaticDir := strings.Trim(subdir, "/")
6058
cleanURLPrefix := strings.Trim(urlPrefix, "/")
61-
subFS, err := fs.Sub(embeddedFS, cleanStaticDir)
62-
if err != nil {
63-
return nil, fmt.Errorf("cannot create sub FS: %w", err)
59+
60+
// if no subdir was specified, use the root FS directly
61+
var serveFS fs.FS
62+
if cleanStaticDir == "" {
63+
serveFS = embeddedFS
64+
} else {
65+
var err error
66+
serveFS, err = fs.Sub(embeddedFS, cleanStaticDir)
67+
if err != nil {
68+
return nil, fmt.Errorf("cannot create sub FS: %w", err)
69+
}
6470
}
6571

6672
prefix := fmt.Sprintf("/%s/", cleanURLPrefix)
67-
return http.StripPrefix(prefix, http.FileServer(http.FS(subFS))), nil
73+
return http.StripPrefix(prefix, http.FileServer(http.FS(serveFS))), nil
6874
}

0 commit comments

Comments
 (0)