问题描述
我使用go:generate来自动生成一些数据库模型,我希望能通过 gofmt 来运行我的模板,但它会与所有额外的 {{...}} 动态部分。
I am using go:generate to handle automatically generating some database models and I was hoping to run my go template through gofmt, but it chokes with all the extra {{ ... }} dynamic sections.
我错过了一些明显的东西吗?我希望这是 gofmt 人已经解决的用例,给定 gofmt 和 go generate 是go工具链的重要组成部分。
Am I missing something obvious? I was hoping that this was a use case the gofmt people had addressed, given both gofmt and go generate are prominent parts of the go toolchain.
显然,它可以在 go generate $ c之后运行 go fmt $ c>但它只是觉得脏,有99%的格式不好的模板去坐在代码。
Obviously, it works to just run go fmt after go generate but it just feels dirty to have poorly formatted templates that are 99% go code sitting around.
推荐答案
大多数生成工具都会将模板执行到* bytes.Buffer,使用并将结果写入输出文件。
Most generation tools execute the template to a *bytes.Buffer, format the buffer bytes using format.Source and write the result to the output file.
模板 t 和输出编写器 w ,代码如下所示:
Given template t and output writer w, the code looks something like this:
var buf bytes.Buffer if err := t.Execute(&buf, data); err != nil { // handle error } p, err := format.Source(buf.Bytes()) if err != nil { // handle error } w.Write(p)
创建模板不能确保输出将会被gofmted。鉴于使用go / format包来输出输出是多么容易,创建gofmt模板的工具几乎没有什么价值。
Gofmting the template does not ensure that the output will be gofmted. Given how easy it is to gofmt the output using the go/format package, there's little value in creating a tool to gofmt templates.
这篇关于可以在模板上使用gofmt吗?设计用于go generate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!