Goal is to embed a directory tree in my binary, then copy it to a user directory later. It consists mostly of text files. I am attempting to display contents of the files in that subdirectory within the project, named .config
(hence the use of go:embed all).
As I understand Go embedding, the following should work outside its own directory, but when executed, lists the name of the first file in the directory tree but cannot open it or display its contents. Within its own project directory it works fine.
//go:embed all:.config
var configFiles embed.FS
func main() {
ls(configFiles)
}
func ls(files embed.FS) error {
fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() {
show(path) // Display contents of file
}
return nil
})
return nil
}
(Complete code at https://go.dev/play/p/A0HzD0rbvX- but it doesn't work because there's no .config directory)
CodePudding user response:
The program walks the embedded file system, but opens files using the operating system. Fix by opening the file in the file system.
Pass the file system to show
:
if !d.IsDir() {
show(files, path) // <-- pass files here
}
Open the file using the file system:
func show(files fs.FS, filename string) { // <-- add arg here
f, err := files.Open(filename) // <-- FS.Open