参考 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,
	}
}
相关推荐
wenzhangli71 天前
[特殊字符] 告别“玩具级”AI开发!Scene-Engine:为企业而生的下一代低代码智能引擎
人工智能·低代码
Vect__2 天前
C++转go之map、面向对象深度剖析
开发语言·c++·golang
codeejun2 天前
每日一Go-68、基于 Kind 的 Istio 本地实战(完整可跑)
golang·istio·kind
geovindu2 天前
go: N-Barrier Pattern
开发语言·后端·设计模式·golang·屏障模式
喵了几个咪2 天前
Go + Vue/React 全栈开发实践
vue.js·react.js·golang·elementplus·vben·go-kratos
驰骋工作流2 天前
CCFast 驰骋低代码BPM-积木菜单设计思想
低代码·工作流引擎·工程引擎·菜单体系
姚不倒2 天前
从零实现一个基于 Ollama + Go + MySQL 的 Text-to-SQL 智能体(M1 实战)
sql·mysql·云原生·golang
盟接之桥2 天前
制造业电子数据交换(EDI)应用 | 汽车零配件方案
网络·安全·低代码·汽车·制造
wlsh152 天前
Go 泛型笔记
golang
姚不倒3 天前
从「LeetCode LRU 缓存」到「生产级 Go Web 服务」:我如何迈出工程化第一步
leetcode·缓存·云原生·golang