| 1 |
package util |
| 2 |
|
| 3 |
import ( |
| 4 |
"embed" |
| 5 |
"errors" |
| 6 |
"io" |
| 7 |
"io/fs" |
| 8 |
"time" |
| 9 |
) |
| 10 |
|
| 11 |
// CachingEmbedFS is a wrapper around embed.FS that allows setting a ModTime, so that the |
| 12 |
// default static file server can send 304s back. It can be used like this: |
| 13 |
// |
| 14 |
// var ( |
| 15 |
// //go:embed docs |
| 16 |
// docsStaticFs embed.FS |
| 17 |
// docsStaticCached = &util.CachingEmbedFS{ModTime: time.Now(), FS: docsStaticFs} |
| 18 |
// ) |
| 19 |
// |
| 20 |
// http.FileServer(http.FS(docsStaticCached)).ServeHTTP(w, r) |
| 21 |
type CachingEmbedFS struct { |
| 22 |
ModTime time.Time |
| 23 |
FS embed.FS |
| 24 |
} |
| 25 |
|
| 26 |
// Open opens a file in the embedded filesystem and returns a fs.File with the static ModTime |
| 27 |
func (f CachingEmbedFS) Open(name string) (fs.File, error) { |
| 28 |
file, err := f.FS.Open(name) |
| 29 |
if err != nil { |
| 30 |
return nil, err |
| 31 |
} |
| 32 |
stat, err := file.Stat() |
| 33 |
if err != nil { |
| 34 |
return nil, err |
| 35 |
} |
| 36 |
return &cachingEmbedFile{file, f.ModTime, stat}, nil |
| 37 |
} |
| 38 |
|
| 39 |
type cachingEmbedFile struct { |
| 40 |
file fs.File |
| 41 |
modTime time.Time |
| 42 |
fs.FileInfo |
| 43 |
} |
| 44 |
|
| 45 |
func (f cachingEmbedFile) Stat() (fs.FileInfo, error) { |
| 46 |
return f, nil |
| 47 |
} |
| 48 |
|
| 49 |
func (f cachingEmbedFile) Read(bytes []byte) (int, error) { |
| 50 |
return f.file.Read(bytes) |
| 51 |
} |
| 52 |
|
| 53 |
func (f *cachingEmbedFile) Seek(offset int64, whence int) (int64, error) { |
| 54 |
if seeker, ok := f.file.(io.Seeker); ok { |
| 55 |
return seeker.Seek(offset, whence) |
| 56 |
} |
| 57 |
return 0, errors.New("io.Seeker not implemented") |
| 58 |
} |
| 59 |
|
| 60 |
func (f cachingEmbedFile) ModTime() time.Time { |
| 61 |
return f.modTime // We override this! |
| 62 |
} |
| 63 |
|
| 64 |
func (f cachingEmbedFile) Close() error { |
| 65 |
return f.file.Close() |
| 66 |
} |