参考 GoZero 生成一段代码

Goctl 的代码生成着实有意思,提高效率的利器啊,忍不住扒了下原码,记录如下:

原代码不上了,以 main.go 的生成为例,相关的文件路径如下:

../goctl/api/gogen/main.tpl

../goctl/api/gogen/util.go 其中核心函数:genFile(c fileGenConfig) error

简单说,生成代码要3步:1.写个模板文件(.tpl);2.模板文件埋点;3.填充埋点

自己写了个 demo:

code.tpl:

Go 复制代码
package {{.pkgName}}

import (
	{{.imports}}
)

type {{.logic}} struct {
	ctx    context.Context
}

func New{{.logic}}(ctx context.Context) *{{.logic}} {
	return &{{.logic}}{
		ctx:    ctx,
	}
}

generate.go

Go 复制代码
package gen

import (
	"bytes"
	goformat "go/format"
	"os"
	"project_demo/docker/demo01/util"
	"text/template"
)

var (
	codeTempFile = "./gen/code.tpl"
	outPutFile="./gen/code.go"
	Params map[string]interface{}
)

const regularPerm = 0o666

func GenCode() {
	bt, err := os.ReadFile(codeTempFile)
	util.CheckError(err)

	// imports:=make([]string,0)
	// cimport:=`"context"`
	// imports=append(imports,cimport)

	Params=map[string]interface{}{
		"pkgName":"gen",
		"imports":`"context"`,
		"logic":"TestTemplate",
	}

	temp, err := template.New("code").Parse(string(bt))
	util.CheckError(err)
	buffer := new(bytes.Buffer)
	err= temp.Execute(buffer, Params)
	util.CheckError(err)

	formatOutput, err := goformat.Source(buffer.Bytes())
	util.CheckError(err)

	buffer.Reset()
	buffer.Write(formatOutput)

	os.WriteFile(outPutFile,buffer.Bytes(),regularPerm)
	
}

输出如下:code.go:

Go 复制代码
package gen

import (
	"context"
)

type TestTemplate struct {
	ctx context.Context
}

func NewTestTemplate(ctx context.Context) *TestTemplate {
	return &TestTemplate{
		ctx: ctx,
	}
}
相关推荐
U盘失踪了1 小时前
go 切片
golang
ん贤2 小时前
口述Map
开发语言·面试·golang
XMYX-04 小时前
12 - Go Slice:底层原理、扩容机制与常见坑位
开发语言·golang
codeejun4 小时前
每日一Go-50、Go微服务--配置中心
开发语言·微服务·golang
小高Baby@4 小时前
CGO_ENABLED=0 导致 SQLite 驱动初始化失败
数据库·sql·golang·ai编程
U盘失踪了4 小时前
go 数组
golang
王码码203514 小时前
Go语言的测试:从单元测试到集成测试
后端·golang·go·接口
王码码203514 小时前
Go语言中的测试:从单元测试到集成测试
后端·golang·go·接口
lolo大魔王15 小时前
Go语言的异常处理
开发语言·后端·golang
止语Lab1 天前
Go 内存管理优化:内联是逃逸分析的隐藏杠杆
golang