有没有办法在go install命令中运行自定义命令?

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

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, "*"))
}

huangapple
  • 本文由 发表于 2022年3月20日 19:08:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/71546196.html
匿名

发表评论

匿名网友

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

确定