I embed some files in my application and access them using a embed.FS
. At some point I use fs.Glob(embedFS, ...)
in my code. Everything is working as expected. Now I have the requirement to replace newlines with whitespaces before proceeding to process a files contents. I could read the whole file and do something like bytes.ReplaceAll(...)
but I wanted to make this a bit nicer and not inflict the requirement of doing the replacement when working with my package (although I could hide that from the user). I decided to implement a wrapper around fs.FS
(and fs.File
) that deals with the replacing while reading the file. But my implementation breaks fs.Glob()
as it does not return any matches:
type noLineBreakFile struct {
file fs.File
}
func (f *noLineBreakFile) Stat() (fs.FileInfo, error) {
return f.file.Stat()
}
func (f *noLineBreakFile) Read(p []byte) (n int, err error) {
n, err = f.file.Read(p)
pp := bytes.ReplaceAll(p, []byte{'\n'}, []byte{' '})
copy(p, pp)
return
}
func (f *noLineBreakFile) Close() error {
return f.file.Close()
}
type noLineBreakFS struct {
fs fs.FS
}
func (fs *noLineBreakFS) Open(name string) (fs.File, error) {
f, err := fs.fs.Open(name)
if err != nil {
return nil, err
}
return &noLineBreakFile{f}, nil // <- returning f without the wrapper works fine
}
//go:embed *.tmpl
var embedFS embed.FS
func main() {
matches, err := fs.Glob(embedFS) // Works fine ...
fmt.Println(matches, err)
matches, err = fs.Glob(&noLineBreakFS{embedFS}) // No matches!
fmt.Println(matches, err)
}
What is the problem with my implementation of fs.File
(noLineBreakFile
)?
CodePudding user response:
Implement ReadDirFile so that Glob can read the directory entries.
func (nfs *noLineBreakFS) ReadDir(name string) ([]fs.DirEntry, error) {
return fs.ReadDir(nfs.fs, name)
}