参考 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,
	}
}
相关推荐
得帆云低代码11 小时前
不确定时代,低代码是CIO的安全感来源
低代码
o0o_-_1 天前
【go/gopls/mcp】官方gopls内置mcp server使用
开发语言·后端·golang
驰骋工作流1 天前
驰骋低代码BPM开发平台的组成部分
低代码
大翻哥哥1 天前
Python 2025:低代码开发与自动化运维的新纪元
运维·python·低代码
FlowGram1 天前
低代码设计态变量挑战与设计 — 前端变量引擎介绍
前端·低代码
Light602 天前
领码SPARK融合平台 · TS × Java 双向契约 —— 性能与治理篇|缓存分段与版本秩序
低代码·缓存·spark
又菜又爱玩呜呜呜~2 天前
go使用反射获取http.Request参数到结构体
开发语言·http·golang
xiaozhazha_2 天前
低代码与AI技术在企业ERP系统构建中的实践应用——以快鹭云平台为例
人工智能·低代码
明天再做行么2 天前
AI 时代,我们是否应该重温极限编程?
人工智能·低代码·极限编程