参考 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,
	}
}
相关推荐
会跑的葫芦怪12 小时前
Go语言操作Redis
开发语言·redis·golang
静谧之心15 小时前
在 K8s 上可靠运行 PD 分离推理:RBG 的设计与实现
云原生·容器·golang·kubernetes·开源·pd分离
大模型真好玩1 天前
低代码Agent开发框架使用指南(一)—主流开发框架对比介绍
人工智能·低代码·agent
赴前尘1 天前
Go 微服务框架排行榜(按 GitHub Star 排序)
微服务·golang·github
自学AI的鲨鱼儿2 天前
ubuntu22.04安装gvm管理go
开发语言·后端·golang
数据知道2 天前
Go基础:正则表达式 regexp 库详解
开发语言·mysql·golang·正则表达式·go语言
Paul_09202 天前
golang面经——内存相关模块
服务器·网络·golang
gopyer2 天前
180课时吃透Go语言游戏后端开发6:Go语言的循环语句
开发语言·游戏·golang·循环语句
canonical_entropy2 天前
DDD本质论:从哲学到数学,再到工程实践的完整指南之理论篇
后端·低代码·领域驱动设计