英文:
Is there any way to run custom commands with go install command?
问题
我写了一个简单的代码生成工具。在这个工具中,我使用了text/template包。当我使用go build
命令安装它时,安装成功了。我面临的唯一问题是如何在安装程序时安装模板。目前它无法获取模板。
我应该在.go文件中使用模板文本,还是有其他方法可以指示在特定位置安装二进制文件和模板?我认为将模板文本作为原始字符串插入代码中是不错的。但是有没有特定的方法来做同样的事情?
英文:
I've written a simple code generation tool. I've used text/template package in this tool. When I installed it with go build
command, it installed successfully. The only problem I'm facing is how to install templates when you install the program. Currently It is unable to get templates.
Shall I use template text in .go files or Is there any other way we can give instructions to install binary and templates at a particular location? I think it's good to have template text in between code as a raw string. But is there any particular way to doing the same?
答案1
得分: 1
你可以使用embed包。
embed包提供了访问嵌入在运行中的Go程序中的文件的功能。
导入"embed"的Go源文件可以使用//go:embed指令,在编译时从包目录或子目录中读取文件的内容来初始化string、[]byte或FS类型的变量。
import (
"embed"
"text/template"
)
//go:embed templates/*
var mytemplateFS embed.FS
func main() {
t := template.New("")
t = template.Must(t.ParseFS(mytemplateFS, "*"))
}
英文:
You can use the embed package.
>Package embed provides access to files embedded in the running Go program.
>
>Go source files that import "embed" can use the //go:embed directive to initialize a variable of type string, []byte, or FS with the contents of files read from the package directory or subdirectories at compile time.
import (
"embed"
"text/template"
)
//go:embed templates/*
var mytemplateFS embed.FS
func main() {
t := template.New("")
t = template.Must(t.ParseFS(mytemplateFS, "*"))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论