使用 `go:embed` 注解时,可以使用 `../` 来引用上级目录。

huangapple go评论86阅读模式
英文:

using ../ at go:embed annotation

问题

我想要嵌入一个位于 golang 代码文件的上一级目录的文件。
例如:

dir1

  • file.go

dir2

  • file.txt

如何使用 go:embed 将 file.txt 嵌入到 file.go 中?

英文:

I want to embed a file placed one level above the golang file code.
for example:

dir1

  • file.go

dir2

  • file.txt

How to embed file.txt inside file.go using go:embed?

答案1

得分: 4

根据文档的说明:

>模式不能包含'.'、'..'或空路径元素,也不能以斜杠开头或结尾。

所以你正在尝试的方法不被直接支持。更多信息可以在此问题的评论中找到。

你可以做的一件事是在dir2中放置一个go文件,在其中嵌入file.txt,然后在dir1/file.go中导入/使用它(假设这些文件夹在同一个包中)。

英文:

The documentation states:

>Patterns may not contain ‘.’ or ‘..’ or empty path elements, nor may they begin or end with a slash.

So what you are trying to do is not supported directly. Further information is available in the comments on this issue.

One thing you can do is to put a go file in dir2, embed file.txt in that and then import/use that in dir1/file.go (assuming the folders are in the same package).

答案2

得分: 1

这在embed包中是不支持的,正如@Brits所说(https://pkg.go.dev/embed)

我喜欢使用的一种模式是在我的项目的internal包中创建一个resources.go文件,并将所有嵌入的资源放在其中,例如:

├── cmd\
│   └── cool.go
└── internal\
    └── resources\
        ├── resources.go
        ├── fonts\
        │   └── coolfont.ttf
        └── icons\
            └── coolicon.ico

resources.go

import _ "embed"

//go:embed fonts/coolfont.fs
var fonts byte[] // 嵌入单个文件

//go:embed icons/*
var icons embed.FS // 嵌入整个目录

也有一些库可以帮助处理这个问题,比如这里列出的https://github.com/avelino/awesome-go#resource-embedding

但我还没有遇到过使用普通的embed无法满足我的需求的情况。

英文:

This is not supported in the embed package as stated by @Brits (https://pkg.go.dev/embed)

A pattern I like to use is to create an resources.go file in my project's internal package and put all my embedded resources in there eg:

├── cmd\ 
│   └── cool.go
└── internal\
    └── resources\
        ├── resources.go
        ├── fonts\
        │   └── coolfont.ttf
        └── icons\
            └── coolicon.ico

resources.go

import _ "embed"

//go:embed fonts/coolfont.fs
var fonts byte[] // embed single file

//go:embed icons/*
var icons embed.FS // embed whole directory

There are libraries that can help with this as well such as those listed here https://github.com/avelino/awesome-go#resource-embedding

But I've not run into a use case where plain old embed wasn't enough for my needs.

huangapple
  • 本文由 发表于 2021年7月27日 14:30:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/68539972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定