解析golang 标准库template的代码生成方法
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《解析golang 标准库template的代码生成方法》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
curd-gen 项目
curd-gen 项目的创建本来是为了做为 illuminant 项目的一个工具,用来生成前端增删改查页面中的基本代码。
最近,随着 antd Pro v5 的升级,将项目进行了升级,现在生成的都是 ts 代码。这个项目的自动生成代码都是基于 golang 的标准库 template 的,所以这篇博客也算是对使用 template 库的一次总结。
自动生成的配置
curd-gen 项目的自动代码生成主要是3部分:
- 类型定义:用于API请求和页面显示的各个类型
- API请求:graphql 请求语句和函数
- 页面:列表页面,新增页面和编辑页面。新增和编辑是用弹出 modal 框的方式。
根据要生成的内容,定义了一个json格式文件,做为代码生成的基础。 json文件的说明在:https://gitee.com/wangyubin/curd-gen#curdjson
生成类型定义
类型是API请求和页面显示的基础,一般开发流程也是先根据业务定义类型,才开始API和页面的开发的。
自动生成类型定义就是根据 json 文件中的字段列表,生成 ts 的类型定义。模板定义如下:
const TypeDTmpl = `// @ts-ignore /* eslint-disable */ declare namespace API { type {{.Model.Name}}Item = { {{- with .Model.Fields}} {{- range .}} {{- if .IsRequired}} {{.Name}}: {{.ConvertTypeForTs}}; {{- else}} {{.Name}}?: {{.ConvertTypeForTs}}; {{- end}}{{- /* end for if .IsRequired */}} {{- end}}{{- /* end for range */}} {{- end}}{{- /* end for with .Model.Fields */}} }; type {{.Model.Name}}ListResult = CommonResponse & { data: { {{.Model.GraphqlName}}: {{.Model.Name}}Item[]; {{.Model.GraphqlName}}_aggregate: { aggregate: { count: number; }; }; }; }; type Create{{.Model.Name}}Result = CommonResponse & { data: { insert_{{.Model.GraphqlName}}: { affected_rows: number; }; }; }; type Update{{.Model.Name}}Result = CommonResponse & { data: { update_{{.Model.GraphqlName}}_by_pk: { id: string; }; }; }; type Delete{{.Model.Name}}Result = CommonResponse & { data: { delete_{{.Model.GraphqlName}}_by_pk: { id: string; }; }; }; }`
除了主要的类型,还包括了增删改查 API 返回值的定义。
其中用到 text/template 库相关的知识点有:
- 通过 **with **限制访问范围,这样,在 {{- with xxx}} 和 {{- end}} 的代码中,不用每个字段前再加 .Model.Fields 前缀了
- 通过 range 循环访问数组,根据数组中每个元素来生成相应的代码
- 通过 if 判断,根据json文件中的属性的不同的定义生成不同的代码
- 自定义函数 **ConvertTypeForTs **,这个函数是将json中定义的 graphql type 转换成 typescript 中对应的类型。用自定义函数是为了避免在模板中写过多的逻辑代码
生成API
这里只生成 graphql 请求的 API,是为了配合 illuminant 项目。 API的参数和返回值用到的对象就在上面自动生成的类型定义中。
const APITmpl = `// @ts-ignore /* eslint-disable */ import { Graphql } from '../utils'; const gqlGet{{.Model.Name}}List = ` + "`" + `query get_item_list($limit: Int = 10, $offset: Int = 0{{- with .Model.Fields}}{{- range .}}{{- if .IsSearch}}, ${{.Name}}: {{.Type}}{{- end}}{{- end}}{{- end}}) { {{.Model.GraphqlName}}(order_by: {updated_at: desc}, limit: $limit, offset: $offset{{.Model.GenGraphqlSearchWhere false}}) { {{- with .Model.Fields}} {{- range .}} {{.Name}} {{- end}} {{- end}} } {{.Model.GraphqlName}}_aggregate({{.Model.GenGraphqlSearchWhere true}}) { aggregate { count } } }` + "`" + `; const gqlCreate{{.Model.Name}} = ` + "`" + `mutation create_item({{.Model.GenGraphqlInsertParamDefinations}}) { insert_{{.Model.GraphqlName}}(objects: { {{.Model.GenGraphqlInsertParams}} }) { affected_rows } }` + "`" + `; const gqlUpdate{{.Model.Name}} = ` + "`" + `mutation update_item_by_pk($id: uuid!, {{.Model.GenGraphqlUpdateParamDefinations}}) { update_{{.Model.GraphqlName}}_by_pk(pk_columns: {id: $id}, _set: { {{.Model.GenGraphqlUpdateParams}} }) { id } }` + "`" + `; const gqlDelete{{.Model.Name}} = ` + "`" + `mutation delete_item_by_pk($id: uuid!) { delete_{{.Model.GraphqlName}}_by_pk(id: $id) { id } }` + "`" + `; export async function get{{.Model.Name}}List(params: API.{{.Model.Name}}Item & API.PageInfo) { const gqlVar = { limit: params.pageSize ? params.pageSize : 10, offset: params.current && params.pageSize ? (params.current - 1) * params.pageSize : 0, {{- with .Model.Fields}} {{- range .}} {{- if .IsSearch}} {{.Name}}: params.{{.Name}} ? '%' + params.{{.Name}} + '%' : '%%', {{- end}} {{- end}} {{- end}} }; return Graphql<api.>(gqlGet{{.Model.Name}}List, gqlVar); } export async function create{{.Model.Name}}(params: API.{{.Model.Name}}Item) { const gqlVar = { {{- with .Model.Fields}} {{- range .}} {{- if not .NotInsert}} {{- if .IsPageRequired}} {{.Name}}: params.{{.Name}}, {{- else}} {{.Name}}: params.{{.Name}} ? params.{{.Name}} : null, {{- end}} {{- end}} {{- end}} {{- end}} }; return Graphql<api.create>(gqlCreate{{.Model.Name}}, gqlVar); } export async function update{{.Model.Name}}(params: API.{{.Model.Name}}Item) { const gqlVar = { id: params.id, {{- with .Model.Fields}} {{- range .}} {{- if not .NotUpdate}} {{- if .IsPageRequired}} {{.Name}}: params.{{.Name}}, {{- else}} {{.Name}}: params.{{.Name}} ? params.{{.Name}} : null, {{- end}} {{- end}} {{- end}} {{- end}} }; return Graphql<api.update>(gqlUpdate{{.Model.Name}}, gqlVar); } export async function delete{{.Model.Name}}(id: string) { return Graphql<api.delete>(gqlDelete{{.Model.Name}}, { id }); }`</api.delete></api.update></api.create></api.>
这个模板中也使用了几个自定义函数,GenGraphqlSearchWhere,GenGraphqlInsertParams,**GenGraphqlUpdateParams **等等。
生成列表页面,新增和编辑页面
最后一步,就是生成页面。列表页面是主要页面:
const PageListTmpl = `import { useRef, useState } from 'react'; import { PageContainer } from '@ant-design/pro-layout'; import { Button, Modal, Popconfirm, message } from 'antd'; import { PlusOutlined } from '@ant-design/icons'; import type { ActionType, ProColumns } from '@ant-design/pro-table'; import ProTable from '@ant-design/pro-table'; import { get{{.Model.Name}}List, create{{.Model.Name}}, update{{.Model.Name}}, delete{{.Model.Name}} } from '{{.Page.ApiImport}}'; import {{.Model.Name}}Add from './{{.Model.Name}}Add'; import {{.Model.Name}}Edit from './{{.Model.Name}}Edit'; export default () => { const tableRef = useRef<actiontype>(); const [modalAddVisible, setModalAddVisible] = useState(false); const [modalEditVisible, setModalEditVisible] = useState(false); const [record, setRecord] = useState<api.>({}); const columns: ProColumns<api.>[] = [ {{- with .Model.Fields}} {{- range .}} {{- if .IsColumn}} { title: '{{.Title}}', dataIndex: '{{.Name}}', {{- if not .IsSearch}} hideInSearch: true, {{- end}} }, {{- end }}{{- /* end for if .IsColumn */}} {{- end }}{{- /* end for range . */}} {{- end }}{{- /* end for with */}} { title: '操作', valueType: 'option', render: (_, rd) => [ <button type="primary" size="small" key="edit" onclick="{()"> { setModalEditVisible(true); setRecord(rd); }} > 修改 </button>, <popconfirm placement="topRight" title="是否删除?" oktext="Yes" canceltext="No" key="delete" onconfirm="{async"> { const response = await delete{{.Model.Name}}(rd.id as string); if (response.code === 10000) message.info(` + "`" + `TODO: 【${rd.TODO}】 删除成功` + "`" + `); else message.warn(` + "`" + `TODO: 【${rd.TODO}】 删除失败` + "`" + `); tableRef.current?.reload(); }} > <button danger size="small"> 删除 </button> </popconfirm>, ], }, ]; const addItem = async (values: any) => { console.log(values); const response = await create{{.Model.Name}}(values); if (response.code !== 10000) { message.error('创建TODO失败'); } if (response.code === 10000) { setModalAddVisible(false); tableRef.current?.reload(); } }; const editItem = async (values: any) => { values.id = record.id; console.log(values); const response = await update{{.Model.Name}}(values); if (response.code !== 10000) { message.error('编辑TODO失败'); } if (response.code === 10000) { setModalEditVisible(false); tableRef.current?.reload(); } }; return ( <pagecontainer fixedheader header='{{"{{"}}' title:><protable> columns={columns} rowKey="id" actionRef={tableRef} search={{"{{"}} labelWidth: 'auto', }} toolBarRender={() => [ <button key="button" icon="{<PlusOutlined"></button>} type="primary" onClick={() => { setModalAddVisible(true); }} > 新建 , ]} request={async (params: API.{{.Model.Name}}Item & API.PageInfo) => { const resp = await get{{.Model.Name}}List(params); return { data: resp.data.{{.Model.GraphqlName}}, total: resp.data.{{.Model.GraphqlName}}_aggregate.aggregate.count, }; }} /> <modal destroyonclose title="新增" visible="{modalAddVisible}" footer="{null}" oncancel="{()"> setModalAddVisible(false)} > </modal><modal destroyonclose title="编辑" visible="{modalEditVisible}" footer="{null}" oncancel="{()"> setModalEditVisible(false)} > </modal></protable></pagecontainer> ); };`</api.></api.></actiontype>
新增页面和编辑页面差别不大,分开定义是为了以后能分别扩展。新增页面:
const PageAddTmpl = `import ProForm, {{.Model.GenPageImportCtrls}} import { formLayout } from '@/common'; import { Row, Col, Space } from 'antd'; export default (props: any) => { return ( <proform layout="horizontal" onfinish="{props.onFinish}" submitter='{{"{{"}}' resetbuttonprops: style: display: render: dom> ( <row><col offset="{10}"><space>{dom}</space></row> ), }} > {{- with .Model.Fields}} {{- range .}} {{- .GenPageCtrl}} {{- end}} {{- end}} </proform> ); };`
页面生成中有个地方困扰了我一阵,就是页面中有个和 text/template 标记冲突的地方,也就是 {{ 的显示。比如上面的 submitter={{"{{"}} ,页面中需要直接显示 {{ 2个字符,但 {{ }} 框住的部分是模板中需要替换的部分。
所以,模板中需要显示 {{ 的地方,可以用 {{"{{"}} 代替。
总结
上面的代码生成虽然需要配合 illuminant 项目一起使用,但是其思路可以参考。
代码生成无非就是找出重复代码的规律,将其中变化的部分定义出来,然后通过模板来生成不同的代码。通过模板来生成代码,跟拷贝相似代码来修改相比,可以有效减少很多人为造成的混乱,比如拷贝过来后漏改,或者有些多余代码未删除等等。
本篇关于《解析golang 标准库template的代码生成方法》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

- 上一篇
- 使用Go语言解决Scan空格结束输入问题

- 下一篇
- 解析golang中的并发安全和锁问题
-
- 阳光的康乃馨
- 好细啊,码起来,感谢老哥的这篇技术文章,我会继续支持!
- 2023-03-13 21:29:20
-
- 活力的黄蜂
- 很棒,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,帮助很大,总算是懂了,感谢大佬分享文章内容!
- 2023-02-28 22:00:42
-
- 友好的酒窝
- 这篇文章真及时,作者大大加油!
- 2023-02-26 16:01:49
-
- 疯狂的乌龟
- 这篇技术文章太及时了,好细啊,写的不错,码住,关注作者大大了!希望作者大大能多写Golang相关的文章。
- 2023-02-23 22:10:03
-
- 昏睡的发夹
- 这篇博文太及时了,太详细了,很好,收藏了,关注up主了!希望up主能多写Golang相关的文章。
- 2023-02-17 06:40:31
-
- 等待的硬币
- 这篇文章太及时了,细节满满,很棒,mark,关注师傅了!希望师傅能多写Golang相关的文章。
- 2023-02-17 03:23:14
-
- 激情的眼神
- 这篇技术贴出现的刚刚好,太详细了,太给力了,mark,关注博主了!希望博主能多写Golang相关的文章。
- 2022-12-28 08:45:48
-
- Golang · Go教程 | 17小时前 |
- TigervncDebian多用户共享桌面超简单教程
- 482浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Go语言新手必看!切片vs数组,一次搞定这两个核心知识点
- 472浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Docker在Debian上运行超简单教程(保姆级教学)
- 210浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Debian设置hostname踩坑记录:权限问题大揭秘
- 334浏览 收藏
-
- Golang · Go教程 | 1天前 |
- Debian装SQLServer?这些问题你一定要注意!
- 284浏览 收藏
-
- Golang · Go教程 | 2天前 |
- Debian系统下Jenkins自动化部署脚本教学
- 367浏览 收藏
-
- Golang · Go教程 | 2天前 |
- DebianSwap服务器应用实测,这些场景真的用得上!
- 319浏览 收藏
-
- Golang · Go教程 | 2天前 |
- Debian跑TigerVNC实测!真香警告,快来看看性能咋样~
- 171浏览 收藏
-
- Golang · Go教程 | 2天前 |
- 在Debian上玩转SQLServer备份还原,手把手教你一步步操作
- 498浏览 收藏
-
- Golang · Go教程 | 2天前 |
- DebianOverlay不会玩?手把手教你轻松定制化安装
- 258浏览 收藏
-
- Golang · Go教程 | 2天前 |
- Go语言实战:time.Ticker&time.After用法区别及避坑技巧
- 240浏览 收藏
-
- Golang · Go教程 | 2天前 |
- Debian系统如何快速定位&干掉那些讨厌的僵尸进程
- 317浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 茅茅虫AIGC检测
- 茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
- 18次使用
-
- 赛林匹克平台(Challympics)
- 探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
- 50次使用
-
- 笔格AIPPT
- SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
- 57次使用
-
- 稿定PPT
- 告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
- 53次使用
-
- Suno苏诺中文版
- 探索Suno苏诺中文版,一款颠覆传统音乐创作的AI平台。无需专业技能,轻松创作个性化音乐。智能词曲生成、风格迁移、海量音效,释放您的音乐灵感!
- 57次使用
-
- GScript 编写标准库示例详解
- 2022-12-30 369浏览
-
- 关于Golang标准库flag的全面讲解
- 2023-02-25 344浏览
-
- Golang template 包基本原理分析
- 2022-12-31 500浏览
-
- Golang标准库unsafe源码解读
- 2022-12-29 464浏览
-
- 快速掌握Go语言HTTP标准库的实现方法
- 2022-12-30 327浏览