Generating go code using go templates

193 views
Skip to first unread message

Amit Lavon

unread,
Sep 7, 2021, 3:53:51 PM9/7/21
to golang-nuts

Hi gophers,
I wrote https://github.com/fluhus/goat for generating go code in my projects. I hope it can help you too. It's a minimal tool that takes a text/template template as input, runs it on the given parameters and gofmt's the output. You can also use it on non-go-source.
Feedback is welcome.

Amit

Denis Cheremisov

unread,
Sep 18, 2021, 9:33:23 PM9/18/21
to golang-nuts
Templates is the worst approach to code generation IMO. Take a look how they do this in protoc-gen-go: 

I am using very similar approach, albeit I prefer format lines, it looks like:
Screenshot from 2021-09-19 04-22-26.png

Templates may be OK only in trivial cases. Once you need something less trivial it is getting harder and harder to reason how the final code will look like with them
and you will end up with bunch of hard to manage templates. Unlike it, line-by-line code generation keep staying close to the final code.
вторник, 7 сентября 2021 г. в 22:53:51 UTC+3, amitl...@gmail.com:

Vasiliy Tolstov

unread,
Sep 20, 2021, 3:29:51 PM9/20/21
to Denis Cheremisov, golang-nuts
I'm writing a code generator from protobuf via templates and i can say - debugging it is very hard. When you have big files you can't check syntax easily, don't know how it looks and if you have errors in the template it is really hard to fix them.
So the protoc-gen-go case is preferable.

вс, 19 сент. 2021 г. в 04:33, Denis Cheremisov <denis.ch...@gmail.com>:
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/406179d9-c8f5-497d-8832-ea04ff9d03b3n%40googlegroups.com.


--
Vasiliy Tolstov,
e-mail: v.to...@selfip.ru

Chetan Gowda

unread,
Sep 20, 2021, 4:15:22 PM9/20/21
to golang-nuts
Yes. Generating large portions of code via templates is going to be hard. Especially reusing and maintaining it.
There is an excellent library called jennifer - https://github.com/dave/jennifer that lets you generate Go code by building the syntax tree. The examples make it super simple to get started. You might want to check it out.

Denis Cheremisov

unread,
Sep 20, 2021, 5:27:50 PM9/20/21
to golang-nuts
Trees although better in general than template still have one critical disadvantage: it is hard to control a code they produces.I tried approaches with templates, line by line and trees. Line by line is generally the best of them.
понедельник, 20 сентября 2021 г. в 23:15:22 UTC+3, chet...@gmail.com:
Reply all
Reply to author
Forward
0 new messages