英文:
Is it possible to use gofmt on templates that are designed to be used with go generate?
问题
我正在使用go:generate来自动生成一些数据库模型,并希望通过gofmt
运行我的go模板,但是由于额外的{{ ... }}
动态部分,它无法正常工作。
我是否漏掉了一些明显的东西?我希望gofmt
的开发人员已经解决了这个问题,因为gofmt
和go generate
都是go工具链的重要组成部分。
显然,在go generate
之后运行go fmt
是可行的,但是让格式不良的模板(其中99%是go代码)存在感觉不太好。
英文:
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.
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.
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.
答案1
得分: 17
大多数生成工具将模板执行到*bytes.Buffer中,使用format.Source格式化缓冲区字节,并将结果写入输出文件。
给定模板t
和输出写入器w
,代码大致如下:
var buf bytes.Buffer
if err := t.Execute(&buf, data); err != nil {
// 处理错误
}
p, err := format.Source(buf.Bytes())
if err != nil {
// 处理错误
}
w.Write(p)
对模板进行gofmt操作并不能确保输出结果是经过gofmt格式化的。考虑到使用go/format包很容易对输出进行gofmt操作,因此创建一个用于对模板进行gofmt的工具的价值很小。
英文:
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.
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)
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论