参考 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,
	}
}
相关推荐
ttwuai3 天前
Go开源后台管理系统推荐:怎么按技术栈和边界比较4个官方仓库?
golang·gin
codeejun3 天前
每日一Go·MySQL-5、锁机制全解析
云原生·golang
Achou.Wang3 天前
k8s中nginx worker process自动设置
后端·golang
许彰午4 天前
55-字典缓存与通知SPI
java·低代码·架构
HUIBUR科技4 天前
十多份业务Excel台账各自独立,数据汇总越做越累
低代码
葡萄城技术团队4 天前
你的设备管理系统过得了等保和信创验收吗?——国产化适配与安全合规清单
低代码
SL_staff5 天前
项目延期时如何用四类角色机制实现责任锚定?一线技术实践拆解
java·低代码·团队管理
米软科技5 天前
高校信息化团队实践:利用AI低代码缩短零散业务交付周期
人工智能·科技·低代码·汽车·制造
指尖的爷5 天前
ARM 架构 Ubuntu(RK3588/aarch64)go开发环境安装手册
ubuntu·架构·golang
名字还没想好☜5 天前
Go 实现指数退避重试:context 取消、抖动 jitter 与什么时候别重试
后端·golang·go