-
Notifications
You must be signed in to change notification settings - Fork 17.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: embed: allow map[string]string
, map[string][]byte
, and/or map[string]any
types
#68909
Comments
|
You can use this function to convert an import (
"embed"
"path"
)
func ToDict(fsys embed.FS) map[string]string {
m := make(map[string]string)
dirs := []string{"."}
for len(dirs) > 0 {
i := len(dirs) - 1
d := dirs[i]
dirs = dirs[:i]
dlist, _ := fsys.ReadDir(d)
for _, dentry := range dlist {
p := path.Join(d, dentry.Name())
if dentry.IsDir() {
dirs = append(dirs, p)
} else {
data, err := fsys.ReadFile(p)
if err == nil {
m[p] = string(data)
}
}
}
}
return m
} https://play.golang.org/p/itTm4SbhpEW EDIT: shorter version by mvdan import (
"embed"
"io/fs"
)
func ToDict(fsys embed.FS) map[string]string {
m := make(map[string]string)
fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
if !d.IsDir() {
content, _ := fsys.ReadFile(path)
m[path] = string(content)
}
return nil
})
return m
} |
If |
That manual walking of directories isn't even needed if you use This ignores errors, but I personally think that's fine for |
//go:embed *
var filesFS embed.FS
var files = filesFS.ToDict()
func main() {
for fname := range files {
fmt.Println(fname)
}
} |
Closing in favor of #69595 |
Proposal Details
Currently,
go:embed
allows embedding individual files asstring
s or[]byte
s, but directories must go through theembed.FS
interface.Allowing directories to be represented as
map
s would improve the ergonomics of walking through embedded filesystem trees, since there would no longer be any (nonexistent) errors to handle (or ignore).Options:
map[string]string
and/ormap[string][]byte
would represent flattened directory hierarchies (similar to how S3 buckets work)map[string]any
would represent the full tree, where keys are directory/file names without slashes, and values aremap[string]any | []byte
sThe text was updated successfully, but these errors were encountered: