@@ -16,6 +16,10 @@ import (
1616type filesystem struct {
1717 // Filesystem is file system used by Static and File handlers to access files.
1818 // Defaults to os.DirFS(".")
19+ //
20+ // When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary
21+ // prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths
22+ // including `assets/images` as their prefix.
1923 Filesystem fs.FS
2024}
2125
@@ -26,12 +30,8 @@ func createFilesystem() filesystem {
2630}
2731
2832// Static registers a new route with path prefix to serve static files from the provided root directory.
29- func (e * Echo ) Static (pathPrefix , root string ) * Route {
30- subFs , err := subFS (e .Filesystem , root )
31- if err != nil {
32- // happens when `root` contains invalid path according to `fs.ValidPath` rules and we are unable to create FS
33- panic (fmt .Errorf ("invalid root given to echo.Static, err %w" , err ))
34- }
33+ func (e * Echo ) Static (pathPrefix , fsRoot string ) * Route {
34+ subFs := MustSubFS (e .Filesystem , fsRoot )
3535 return e .Add (
3636 http .MethodGet ,
3737 pathPrefix + "*" ,
@@ -40,11 +40,15 @@ func (e *Echo) Static(pathPrefix, root string) *Route {
4040}
4141
4242// StaticFS registers a new route with path prefix to serve static files from the provided file system.
43- func (e * Echo ) StaticFS (pathPrefix string , fileSystem fs.FS ) * Route {
43+ //
44+ // When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary
45+ // prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths
46+ // including `assets/images` as their prefix.
47+ func (e * Echo ) StaticFS (pathPrefix string , filesystem fs.FS ) * Route {
4448 return e .Add (
4549 http .MethodGet ,
4650 pathPrefix + "*" ,
47- StaticDirectoryHandler (fileSystem , false ),
51+ StaticDirectoryHandler (filesystem , false ),
4852 )
4953}
5054
@@ -125,3 +129,17 @@ func subFS(currentFs fs.FS, root string) (fs.FS, error) {
125129 }
126130 return fs .Sub (currentFs , root )
127131}
132+
133+ // MustSubFS creates sub FS from current filesystem or panic on failure.
134+ // Panic happens when `fsRoot` contains invalid path according to `fs.ValidPath` rules.
135+ //
136+ // MustSubFS is helpful when dealing with `embed.FS` because for example `//go:embed assets/images` embeds files with
137+ // paths including `assets/images` as their prefix. In that case use `fs := echo.MustSubFS(fs, "rootDirectory") to
138+ // create sub fs which uses necessary prefix for directory path.
139+ func MustSubFS (currentFs fs.FS , fsRoot string ) fs.FS {
140+ subFs , err := subFS (currentFs , fsRoot )
141+ if err != nil {
142+ panic (fmt .Errorf ("can not create sub FS, invalid root given, err: %w" , err ))
143+ }
144+ return subFs
145+ }
0 commit comments