Golang 的一些编程思维和思想,以及总结一些常见的优雅编程实战技巧。
作者:allendbwu,腾讯 PCG 后台开发工程师
一 Golang 编程思维
首先,我们先来看下最基本的,就是 Golang 的学习技巧,比如通读 Golang 的一些好的文章:
要通读 golang 官方的编码规范,主要是要参考官方的 CodeReviewComments 和 Effective Go 这两篇官方文章,真的非常推荐必须要好好的看完、看懂这两篇文章(英文不好的同学可以看中文翻译文档),然后按照官方编码规范来具体 coding,主要是能够在具体的编码中有迹可循。
参考业界大牛们的代码,主要是看一些开源的优质的项目,比如 Google 他们这帮人自己搞的 Kubernetes、Istio,还有一些好的项目如 Docker、CoreDNS、etcd 等等。
项目基本架构的组织 代码基本的编码封装 代码的基本原则规范 并发的设计思想 面向对象编程的设计思想 可扩展性的设计思想
然后就是实践,实实在在的跑一些代码示例,可以自己建立一个 base-code 的项目,里面就是你的各种示例,然后进行一些修改、执行。具体的代码示例可以从官方文档上来,推荐Go by Example,里面有大量非常好的例子。也可以自己网上随便搜下,重要的自己要修改并执行,查看和分析结果:Go 101
其次,要理解 Golang 编程思维,首先要理解 Golang 这门语言的创始初衷,初衷就是为了解决好 Google 内部大规模高并发服务的问题,主要核心就是围绕高并发来开展;并且同时又不想引入面向对象那种很复杂的继承关系。首先,就是可以方便的解决好并发问题(包括高并发),那么就需要有并发思维,能够并发处理就通过并发来进行任务分配
这个就是涉及到了 context、 goroutine、channel(select); 创建大量 goroutine, 但是需要能通过 context、 channel 建立 "父子"关系,保证子任务可以能够被回收、被主动控制(如 杀死)。
再者,面向对象编程思想,利用好 interface、 struct 来实现继承、多态的用法:
struct 匿名组合来实现继承; terface 和 struct 来实现多态; interface 定义接口,尽可能的保持里面的方法定义简单,然后多个 interface 进行组合。
然后,理解 Golang 语言本身的一些特性: - 强类型,语法上要注意处理;- GC,实际中要观察 GC 日志并分析;- 注意语法语义尽可能的简单、保持各种类型定义尽可能精简。
最后,从 Golang 社区的一些最佳实践来看,Golang 的各种组件需要尽可能的精简。
Golang 中用好的一些开源组件库,都是比较轻量级的,然后可以各自随意组合来达到最佳实践。 我们自己进行组件封装、模块封装的时候,也是保持这个原则,尽可能的精简,然后使用方进行组合。
二、Golang 高级编码技巧
1 优雅的实现构造函数编程思想
1 | <span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;padding: 16px;color: #333;display: -webkit-box;font-family: Operator Mono, Consolas, Monaco, Menlo, monospace;font-size: 12px;-webkit-overflow-scrolling: touch;padding-top: 15px;background: #f8f8f8;border-radius: 5px;"><span style="color: #998;font-style: italic;line-height: 26px;">/*<br/>一个更为优雅的构造函数的实现方式<br/>参考:<br/>https://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html<br/>通过这个方式可以方便构造不同对象,同时避免了大量重复代码<br/>*/</span><br/><br/><span style="font-weight: bold;line-height: 26px;">package</span> main<br/><span style="font-weight: bold;line-height: 26px;">import</span> (<br/> <span style="color: #d14;line-height: 26px;">"fmt"</span><br/> <span style="color: #d14;line-height: 26px;">"time"</span><br/><br/> <span style="color: #d14;line-height: 26px;">"golang.org/x/net/context"</span><br/>)<br/><br/><span style="font-weight: bold;line-height: 26px;">type</span> Cluster <span style="font-weight: bold;line-height: 26px;">struct</span> {<br/> opts options<br/>}<br/><br/><span style="font-weight: bold;line-height: 26px;">type</span> options <span style="font-weight: bold;line-height: 26px;">struct</span> {<br/> connectionTimeout time.Duration<br/> readTimeout time.Duration<br/> writeTimeout time.Duration<br/> logError <span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span><span style="line-height: 26px;">(ctx context.Context, err error)</span></span><br/>}<br/><br/><span style="color: #998;font-style: italic;line-height: 26px;">// 通过一个选项实现为一个函数指针来达到一个目的:设置选项中的数据的状态</span><br/><span style="color: #998;font-style: italic;line-height: 26px;">// Golang函数指针的用法</span><br/><span style="font-weight: bold;line-height: 26px;">type</span> Option <span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span><span style="line-height: 26px;">(c *options)</span></span><br/><br/><span style="color: #998;font-style: italic;line-height: 26px;">// 设置某个参数的一个具体实现,用到了闭包的用法。</span><br/><span style="color: #998;font-style: italic;line-height: 26px;">// 不仅仅只是设置而采用闭包的目的是为了更为优化,更好用,对用户更友好</span><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">LogError</span><span style="line-height: 26px;">(f <span style="font-weight: bold;line-height: 26px;">func</span>(ctx context.Context, err error)</span>) <span style="color: #900;font-weight: bold;line-height: 26px;">Option</span></span> {<br/> <span style="font-weight: bold;line-height: 26px;">return</span> <span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span><span style="line-height: 26px;">(opts *options)</span></span> {<br/> opts.logError = f<br/> }<br/>}<br/><br/><span style="color: #998;font-style: italic;line-height: 26px;">// 对关键数据变量的赋值采用一个方法来实现而不是直接设置</span><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">ConnectionTimeout</span><span style="line-height: 26px;">(d time.Duration)</span> <span style="color: #900;font-weight: bold;line-height: 26px;">Option</span></span> {<br/> <span style="font-weight: bold;line-height: 26px;">return</span> <span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span><span style="line-height: 26px;">(opts *options)</span></span> {<br/> opts.connectionTimeout = d<br/> }<br/>}<br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">WriteTimeout</span><span style="line-height: 26px;">(d time.Duration)</span> <span style="color: #900;font-weight: bold;line-height: 26px;">Option</span></span> {<br/> <span style="font-weight: bold;line-height: 26px;">return</span> <span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span><span style="line-height: 26px;">(opts *options)</span></span> {<br/> opts.writeTimeout = d<br/> }<br/>}<br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">ReadTimeout</span><span style="line-height: 26px;">(d time.Duration)</span> <span style="color: #900;font-weight: bold;line-height: 26px;">Option</span></span> {<br/> <span style="font-weight: bold;line-height: 26px;">return</span> <span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span><span style="line-height: 26px;">(opts *options)</span></span> {<br/> opts.readTimeout = d<br/> }<br/>}<br/><br/><span style="color: #998;font-style: italic;line-height: 26px;">// 构造函数具体实现,传入相关Option,new一个对象并赋值</span><br/><span style="color: #998;font-style: italic;line-height: 26px;">// 如果参数很多,也不需要传入很多参数,只需要传入opts ...Option即可</span><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">NewCluster</span><span style="line-height: 26px;">(opts ...Option)</span> *<span style="color: #900;font-weight: bold;line-height: 26px;">Cluster</span></span> {<br/> clusterOpts := options{}<br/> <span style="font-weight: bold;line-height: 26px;">for</span> _, opt := <span style="font-weight: bold;line-height: 26px;">range</span> opts {<br/> <span style="color: #998;font-style: italic;line-height: 26px;">// 函数指针的赋值调用</span><br/> opt(&clusterOpts)<br/> }<br/><br/> cluster := <span style="color: #0086b3;line-height: 26px;">new</span>(Cluster)<br/> cluster.opts = clusterOpts<br/><br/> <span style="font-weight: bold;line-height: 26px;">return</span> cluster<br/>}<br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">main</span><span style="line-height: 26px;">()</span></span> {<br/><br/> <span style="color: #998;font-style: italic;line-height: 26px;">// 前期储备,设定相关参数</span><br/> commonsOpts := []Option{<br/> ConnectionTimeout(<span style="color: #008080;line-height: 26px;">1</span> * time.Second),<br/> ReadTimeout(<span style="color: #008080;line-height: 26px;">2</span> * time.Second),<br/> WriteTimeout(<span style="color: #008080;line-height: 26px;">3</span> * time.Second),<br/> LogError(<span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span><span style="line-height: 26px;">(ctx context.Context, err error)</span></span> {<br/> }),<br/> }<br/><br/> <span style="color: #998;font-style: italic;line-height: 26px;">// 终极操作,构造函数</span><br/> cluster := NewCluster(commonsOpts...)<br/><br/> <span style="color: #998;font-style: italic;line-height: 26px;">// 测试验证</span><br/> fmt.Println(cluster.opts.connectionTimeout)<br/> fmt.Println(cluster.opts.writeTimeout)<br/><br/>}<br/> |
除了构造函数这个思想之外,还有一个思想,就是我们要善于利用 struct 封装对象方法,然后再 new 一个对象出来,如下:
1 | <span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;padding: 16px;color: #333;display: -webkit-box;font-family: Operator Mono, Consolas, Monaco, Menlo, monospace;font-size: 12px;-webkit-overflow-scrolling: touch;padding-top: 15px;background: #f8f8f8;border-radius: 5px;"><span style="font-weight: bold;line-height: 26px;">type</span> Cluster <span style="font-weight: bold;line-height: 26px;">struct</span> {<br/> opts options<br/>}<br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">NewCluster</span><span style="line-height: 26px;">(opts ...Option)</span> *<span style="color: #900;font-weight: bold;line-height: 26px;">Cluster</span></span> {<br/> ....<br/><br/> cluster := <span style="color: #0086b3;line-height: 26px;">new</span>(Cluster)<br/> cluster.opts = clusterOpts<br/><br/> <span style="font-weight: bold;line-height: 26px;">return</span> cluster<br/>}<br/> |
2 优雅的实现继承编程思想
Golang 里面没有 C++ 、Java 那种继承的实现方式,但是,我们可以通过 Golang 的匿名组合来实现继承,这里要注意,这个是实际编程中经常用到的一种姿势。具体实现就是一个 struct 里面包含一个匿名的 struct,也就是通过匿名组合,这最基础的基类就是一个 struct 结构,然后定义相关成员变量,然后再定义一个子类,也是一个 struct,里面包含前面的 struct,即可实现继承。
示例代码如下,代码里面有详细的解释:
1 | <span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;padding: 16px;color: #333;display: -webkit-box;font-family: Operator Mono, Consolas, Monaco, Menlo, monospace;font-size: 12px;-webkit-overflow-scrolling: touch;padding-top: 15px;background: #f8f8f8;border-radius: 5px;"><span style="font-weight: bold;line-height: 26px;">package</span> main<br/><span style="font-weight: bold;line-height: 26px;">import</span> (<br/> <span style="color: #d14;line-height: 26px;">"fmt"</span><br/>)<br/><br/><span style="color: #998;font-style: italic;line-height: 26px;">// 【基类】</span><br/><span style="color: #998;font-style: italic;line-height: 26px;">//定义一个最基础的struct类MsgModel,里面包含一个成员变量msgId</span><br/><span style="font-weight: bold;line-height: 26px;">type</span> MsgModel <span style="font-weight: bold;line-height: 26px;">struct</span> {<br/> msgId <span style="font-weight: bold;line-height: 26px;">int</span><br/> msgType <span style="font-weight: bold;line-height: 26px;">int</span><br/>}<br/><br/><span style="color: #998;font-style: italic;line-height: 26px;">// MsgModel的一个成员方法,用来设置msgId</span><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="line-height: 26px;">(msg *MsgModel)</span> <span style="color: #900;font-weight: bold;line-height: 26px;">SetId</span><span style="line-height: 26px;">(msgId <span style="font-weight: bold;line-height: 26px;">int</span>)</span></span> {<br/> msg.msgId = msgId<br/>}<br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="line-height: 26px;">(msg *MsgModel)</span> <span style="color: #900;font-weight: bold;line-height: 26px;">SetType</span><span style="line-height: 26px;">(msgType <span style="font-weight: bold;line-height: 26px;">int</span>)</span></span> {<br/> msg.msgType = msgType<br/>}<br/><br/><span style="color: #998;font-style: italic;line-height: 26px;">//【子类】</span><br/><span style="color: #998;font-style: italic;line-height: 26px;">// 再定义一个struct为GroupMsgModel,包含了MsgModel,即组合,但是并没有给定MsgModel任何名字,因此是匿名组合</span><br/><span style="font-weight: bold;line-height: 26px;">type</span> GroupMsgModel <span style="font-weight: bold;line-height: 26px;">struct</span> {<br/> MsgModel<br/><br/> <span style="color: #998;font-style: italic;line-height: 26px;">// 如果子类也包含一个基类的一样的成员变量,那么通过子类设置和获取得到的变量都是基类的</span><br/> msgId <span style="font-weight: bold;line-height: 26px;">int</span><br/>}<br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="line-height: 26px;">(group *GroupMsgModel)</span> <span style="color: #900;font-weight: bold;line-height: 26px;">GetId</span><span style="line-height: 26px;">()</span> <span style="color: #900;font-weight: bold;line-height: 26px;">int</span></span> {<br/> <span style="font-weight: bold;line-height: 26px;">return</span> group.msgId<br/>}<br/><br/><span style="color: #998;font-style: italic;line-height: 26px;">/*<br/>func (group *GroupMsgModel) SetId(msgId int) {<br/> group.msgId = msgId<br/>}<br/>*/</span><br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">main</span><span style="line-height: 26px;">()</span></span> {<br/> group := &GroupMsgModel{}<br/><br/> group.SetId(<span style="color: #008080;line-height: 26px;">123</span>)<br/> group.SetType(<span style="color: #008080;line-height: 26px;">1</span>)<br/><br/> fmt.Println(<span style="color: #d14;line-height: 26px;">"group.msgId ="</span>, group.msgId, <span style="color: #d14;line-height: 26px;">"tgroup.MsgModel.msgId ="</span>, group.MsgModel.msgId)<br/> fmt.Println(<span style="color: #d14;line-height: 26px;">"group.msgType ="</span>, group.msgType, <span style="color: #d14;line-height: 26px;">"tgroup.MsgModel.msgType ="</span>, group.MsgModel.msgType)<br/>}<br/><br/> |
3 优雅的实现虚多态编程思想
面向对象编程中,我们很多情况下,都会定义一个虚基类,然后利用多态去实现各种相似的场景或者说任务。
Golang 里面可以通过 interface + struct 来实现虚基类的用法。interface 用来定义一个 "虚基类",然后一个 struct 结构定义,用来实现这个 interface 中定义的方法,并且可以有多个类似的 struct 来实现这个 interface,只要实现了这个 interface 中定义的方法即可。这也是典型的多态的一种编程思想,也就是说 Golang 通过接口去实现了多态。
具体流程如下,这个是我实际项目(大型 IM 架构)中的实现方式:
定义一个 interface 接口 MsgModel,包含了一些方法,这个就相当于 "虚基类"
1<span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;display: -webkit-box;padding: 15px 4px 2px;margin-right: 2px;margin-left: 2px;color: rgb(30, 107, 184);word-break: break-all;font-family: "Microsoft YaHei";background: rgb(248, 248, 248);border-radius: 5px;"><span style="color: #333;font-weight: bold;line-height: 26px;">type</span> MsgModel <span style="color: #333;font-weight: bold;line-height: 26px;">interface</span> {<br/> Persist(context context.Context, msg <span style="color: #333;font-weight: bold;line-height: 26px;">interface</span>{}) <span style="color: #333;font-weight: bold;line-height: 26px;">bool</span><br/> PersistOnSensitive(context context.Context, session_type, level, SensitiveStatus <span style="color: #333;font-weight: bold;line-height: 26px;">int32</span>, msg <span style="color: #333;font-weight: bold;line-height: 26px;">interface</span>{}) <span style="color: #333;font-weight: bold;line-height: 26px;">bool</span><br/>}<br/>定义一个类型 msgModelImpl struct{},用来实现上面的 interface 接口
1<span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;display: -webkit-box;padding: 15px 4px 2px;margin-right: 2px;margin-left: 2px;color: rgb(30, 107, 184);word-break: break-all;font-family: "Microsoft YaHei";background: rgb(248, 248, 248);border-radius: 5px;">定义一个<span style="color: #333;font-weight: bold;line-height: 26px;">struct</span>用来实现接口类型<br/><span style="color: #333;font-weight: bold;line-height: 26px;">type</span> msgModelImpl <span style="color: #333;font-weight: bold;line-height: 26px;">struct</span>{}<br/><br/><br/>定义一个变量MsgModelImpl等于msgModelImpl,相当于可以通过MsgModelImpl来调用msgModelImpl的成员<br/><span style="color: #333;font-weight: bold;line-height: 26px;">var</span> MsgModelImpl = msgModelImpl{}<br/><br/>实现接口的两个方法<br/><span style="line-height: 26px;"><span style="color: #333;font-weight: bold;line-height: 26px;">func</span> <span style="line-height: 26px;">(m msgModelImpl)</span> <span style="color: #900;font-weight: bold;line-height: 26px;">Persist</span><span style="line-height: 26px;">(context context.Context, msgIface <span style="color: #333;font-weight: bold;line-height: 26px;">interface</span>{})</span> <span style="color: #900;font-weight: bold;line-height: 26px;">bool</span></span> {<br/><span style="color: #998;font-style: italic;line-height: 26px;">// 具体实现省略</span><br/>}<br/><br/><span style="line-height: 26px;"><span style="color: #333;font-weight: bold;line-height: 26px;">func</span> <span style="line-height: 26px;">(m msgModelImpl)</span> <span style="color: #900;font-weight: bold;line-height: 26px;">UpdateDbContent</span><span style="line-height: 26px;">(context context.Context, msgIface <span style="color: #333;font-weight: bold;line-height: 26px;">interface</span>{})</span> <span style="color: #900;font-weight: bold;line-height: 26px;">bool</span></span> {<br/><span style="color: #998;font-style: italic;line-height: 26px;">// 具体实现省略</span><br/>}<br/>
再定义一个 struct 类型的 msgService,包含上述接口类型 MsgModel,相当于组合了。这样的话,这个类型就需要要实现接口方法。
1<span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;display: -webkit-box;padding: 15px 4px 2px;margin-right: 2px;margin-left: 2px;color: rgb(30, 107, 184);word-break: break-all;font-family: "Microsoft YaHei";background: rgb(248, 248, 248);border-radius: 5px;"><span style="color: #333;font-weight: bold;line-height: 26px;">type</span> msgService <span style="color: #333;font-weight: bold;line-height: 26px;">struct</span> {<br/> msgModel MsgModel<br/>}<br/>
再定义一个变量 MsgService,首字母大写,并且赋值为 msgService 对象,同时给成员 msgModel 赋值为上述已经实现了接口的 struct 对象 MsgModelImpl。
1<span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;display: -webkit-box;padding: 15px 4px 2px;margin-right: 2px;margin-left: 2px;color: rgb(30, 107, 184);word-break: break-all;font-family: "Microsoft YaHei";background: rgb(248, 248, 248);border-radius: 5px;">将上述已经实现接口类型的类型(MsgModelImpl) 赋值给此变量(此变量并且要是包含了接口类型的类型), 然后这个变量就可以供外部调用<br/><span style="color: #333;font-weight: bold;line-height: 26px;">var</span> MsgService = msgService{<br/> msgModel: MsgModelImpl,<br/>}<br/>这样就全部实现了,后面只要通过 MsgService 中的接口方法就可以调用 interface 中定义的方法
注意,定义个 MsgService,里面的成员变量 msgModel 赋值为 MsgModelImpl 的目的是为了做封装,对外暴露接口的都是 MsgService,隐藏了内部具体的 MsgModelImpl 实现。
小结:
MsgModel 是一个 interface interface 是一组抽象方法的集合,interface 未具体实现的方法,仅包含方法名参数返回值的方法 msgModelImpl 是一个 struct,它实现了 MsgModel 这个 interface 的所有方法 如果实现了 interface 中的所有方法,即该类/对象就实现了该接口 MsgModelImpl 是 msgModelImpl 这个 struct 的对象 msgService 是一个 struct,它包含了 MsgModel,相当于组合 MsgService 是 msgService 这个 struct 的对象,并对成员变量赋值 后面就通过 MsgService 对外提供服务,隐藏内部具体的 MsgModelImpl 实现。
4 Golang 的 model service 模型【类 MVC 模型】
在一个项目工程中,为了使得代码更优雅,需要抽象出一些模型出来,同时基于 C++面向对象编程的思想,需要考虑到一些类、继承相关。在 Golang 中,没有类、继承的概念,但是我们完全可以通过 struct 和 interface 来建立我们想要的任何模型。在我们的工程中,抽象出一种我自认为是类似 MVC 的模型,但是不完全一样,个人觉得这个模型抽象的比较好,容易扩展,模块清晰。对于使用 java 和 PHP 编程的同学对这个模型应该是再熟悉不过了,我这边通过代码来说明下这个模型
首先一个 model 包,通过 interface 来实现,包含一些基础方法,需要被外部引用者来具体实现
1<span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;display: -webkit-box;padding: 15px 4px 2px;margin-right: 2px;margin-left: 2px;color: rgb(30, 107, 184);word-break: break-all;font-family: "Microsoft YaHei";background: rgb(248, 248, 248);border-radius: 5px;"><span style="color: #333;font-weight: bold;line-height: 26px;">package</span> model<br/><br/><span style="color: #998;font-style: italic;line-height: 26px;">// 定义一个基础model</span><br/><span style="color: #333;font-weight: bold;line-height: 26px;">type</span> MsgModel <span style="color: #333;font-weight: bold;line-height: 26px;">interface</span> {<br/> Persist(context context.Context, msg <span style="color: #333;font-weight: bold;line-height: 26px;">interface</span>{}) <span style="color: #333;font-weight: bold;line-height: 26px;">bool</span><br/> UpdateDbContent(context context.Context, msgIface <span style="color: #333;font-weight: bold;line-height: 26px;">interface</span>{}) <span style="color: #333;font-weight: bold;line-height: 26px;">bool</span><br/> GetList(context context.Context, uid, peerId, sinceMsgId, maxMsgId <span style="color: #333;font-weight: bold;line-height: 26px;">int64</span>, count <span style="color: #333;font-weight: bold;line-height: 26px;">int</span>) (<span style="color: #333;font-weight: bold;line-height: 26px;">interface</span>{}, <span style="color: #333;font-weight: bold;line-height: 26px;">bool</span>)]<br/><br/>再定义一个 msg 包,用来具体实现 model 包中 MsgModel 模型的所有方法
1<span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;display: -webkit-box;padding: 15px 4px 2px;margin-right: 2px;margin-left: 2px;color: rgb(30, 107, 184);word-break: break-all;font-family: "Microsoft YaHei";background: rgb(248, 248, 248);border-radius: 5px;"><span style="color: #333;font-weight: bold;line-height: 26px;">package</span> msg<br/><span style="color: #333;font-weight: bold;line-height: 26px;">type</span> msgModelImpl <span style="color: #333;font-weight: bold;line-height: 26px;">struct</span>{}<br/><span style="color: #333;font-weight: bold;line-height: 26px;">var</span> MsgModelImpl = msgModelImpl{}<br/><span style="line-height: 26px;"><span style="color: #333;font-weight: bold;line-height: 26px;">func</span> <span style="line-height: 26px;">(m msgModelImpl)</span> <span style="color: #900;font-weight: bold;line-height: 26px;">Persist</span><span style="line-height: 26px;">(context context.Context, msgIface <span style="color: #333;font-weight: bold;line-height: 26px;">interface</span>{})</span> <span style="color: #900;font-weight: bold;line-height: 26px;">bool</span></span> {<br/> <span style="color: #998;font-style: italic;line-height: 26px;">// 具体实现</span><br/>}<br/><br/><span style="line-height: 26px;"><span style="color: #333;font-weight: bold;line-height: 26px;">func</span> <span style="line-height: 26px;">(m msgModelImpl)</span> <span style="color: #900;font-weight: bold;line-height: 26px;">UpdateDbContent</span><span style="line-height: 26px;">(context context.Context, msgIface <span style="color: #333;font-weight: bold;line-height: 26px;">interface</span>{})</span> <span style="color: #900;font-weight: bold;line-height: 26px;">bool</span></span> {<br/> <span style="color: #998;font-style: italic;line-height: 26px;">// 具体实现</span><br/>}<br/><br/><span style="line-height: 26px;"><span style="color: #333;font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">GetList</span><span style="line-height: 26px;">(context context.Context, uid, peerId, sinceMsgId, maxMsgId <span style="color: #333;font-weight: bold;line-height: 26px;">int64</span>, count <span style="color: #333;font-weight: bold;line-height: 26px;">int</span>)</span> <span style="line-height: 26px;">(<span style="color: #333;font-weight: bold;line-height: 26px;">interface</span>{}, <span style="color: #333;font-weight: bold;line-height: 26px;">bool</span>)</span>]</span>{<br/> <span style="color: #998;font-style: italic;line-height: 26px;">// 具体实现</span><br/>}<br/><br/>
model 和 具体实现方定义并实现 ok 后,那么就还需要一个 service 来统筹管理
1<span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;display: -webkit-box;padding: 15px 4px 2px;margin-right: 2px;margin-left: 2px;color: rgb(30, 107, 184);word-break: break-all;font-family: "Microsoft YaHei";background: rgb(248, 248, 248);border-radius: 5px;"><span style="color: #333;font-weight: bold;line-height: 26px;">package</span> service<br/><br/><span style="color: #998;font-style: italic;line-height: 26px;">// 定义一个msgService struct包含了model里面的UserModel和MsgModel两个model</span><br/><span style="color: #333;font-weight: bold;line-height: 26px;">type</span> msgService <span style="color: #333;font-weight: bold;line-height: 26px;">struct</span> {<br/> userModel model.UserModel<br/> msgModel model.MsgModel<br/>}<br/><br/><span style="color: #998;font-style: italic;line-height: 26px;">// 定义一个MsgService的变量,并初始化,这样通过MsgService,就能引用并访问model的所有方法</span><br/><span style="color: #333;font-weight: bold;line-height: 26px;">var</span> (<br/> MsgService = msgService{<br/> userModel: user.UserModelImpl,<br/> msgModel: msg.MsgModelImpl,<br/> }<br/>)<br/>调用访问
1<span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;display: -webkit-box;padding: 15px 4px 2px;margin-right: 2px;margin-left: 2px;color: rgb(30, 107, 184);word-break: break-all;font-family: "Microsoft YaHei";background: rgb(248, 248, 248);border-radius: 5px;"><span style="color: #333;font-weight: bold;line-height: 26px;">import</span> service<br/>service.MsgService.Persist(ctx, xxx)<br/>
总结一下,model 对应 MVC 的 M,service 对应 MVC 的 C, 调用访问的地方对应 MVC 的 V
5 Golang 单例模式
单例模式是一种常用的软件设计模式,在它的核心结构中只包含一个被称为单例的特殊类,通过单例模式可以保证系统中一个类有且仅有一个实例且该实例可以被外界访问。
在 Golang 中有一种非常优雅的姿势可以实现,就是通过 sync.Once 来实现,这个也是我在实际项目中所应用的,示例如下:
1 | <span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;padding: 16px;color: #333;display: -webkit-box;font-family: Operator Mono, Consolas, Monaco, Menlo, monospace;font-size: 12px;-webkit-overflow-scrolling: touch;padding-top: 15px;background: #f8f8f8;border-radius: 5px;"><span style="font-weight: bold;line-height: 26px;">import</span> <span style="color: #d14;line-height: 26px;">"github.com/dropbox/godropbox/singleton"</span><br/><span style="font-weight: bold;line-height: 26px;">var</span> SingleService = singleton.NewSingleton(<span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span><span style="line-height: 26px;">()</span> <span style="line-height: 26px;">(<span style="font-weight: bold;line-height: 26px;">interface</span>{}, error)</span></span> {<br/> <span style="font-weight: bold;line-height: 26px;">return</span> &singleMsgProxy{<br/> MsgModel: msg.MsgModelImpl,<br/> }, <span style="color: #008080;line-height: 26px;">nil</span><br/>})<br/> |
singleton.NewSingleton 就是具体单例模式的实现,然后赋值给 SingleService,这样,在程序中任何需要获取这个对象的时候,就直接通过 SingleService 来调用,这个调用,系统会保证,里面的 singleMsgProxy 只会被初始化对象一次,这个 singleMsgProxy 就是 new 了一个对象,并且这个对象是只需要被初始化一次的。
6 Golang layout
Golang 工程 Layout 规范,网上有较多探讨,每个人的理解也会不一致,但是有些基础的理解是可以保持统一的:
cmd
main 函数文件目录,这个目录下面,每个文件在编译之后都会生成一个可执行的文件。如果只有一个 app 文件,那就是 main.go。这里面的代码尽可能简单。 conf
配置文件,如 toml、yaml 等文件 config
配置文件的解析 docs
文档 pkg
底层各种实现,每一种实现封装一个文件夹 业界知名开源项目如 Kubernetes、Istio 都是这样的姿势 build
编译脚本 CI 脚本 上下线脚本 vendor
依赖库
一个简单示例如下:
1 | <span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;padding: 16px;color: #333;display: -webkit-box;font-family: Operator Mono, Consolas, Monaco, Menlo, monospace;font-size: 12px;-webkit-overflow-scrolling: touch;padding-top: 15px;background: #f8f8f8;border-radius: 5px;">$ tree -d -L 2<br/>├── build<br/>├── cmd<br/>│ ├── apply<br/>│ └── check<br/>├── conf<br/>├── config<br/>├── docs<br/>├── pkg<br/>│ ├── apply<br/>│ ├── check<br/>│ ├── files<br/>│ ├── k8s<br/>│ └── options<br/>└── vendor<br/> |
7 cmd & command & flag
大家看 Kubernetes 的源码就可以发现,会有这么一个现象,Kubernetes 中会有很多二进制程序,然后每个程序,可能会有不同的指令,然后每个指令都会有很多命令行参数。如果大家对 Kubernetes 有一定了解,那么就知道 kubectl 会有如下命令:
1 | <span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;padding: 16px;color: #333;display: -webkit-box;font-family: Operator Mono, Consolas, Monaco, Menlo, monospace;font-size: 12px;-webkit-overflow-scrolling: touch;padding-top: 15px;background: #f8f8f8;border-radius: 5px;">kubectl apply -f 进行部署<br/>kubectl delete -f 删除部署<br/>kubectl get pod 获取 Pod<br/> |
那么 kubectl 这个二进制程序,如何能够优雅的支持不同的参数呢?
下面,还是以我实际项目工程中的应用为例,来进行演示。效果如下,程序 example 包含两个命令 apply 和 check,还有一个 help 命令:
1 | <span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;padding: 16px;color: #333;display: -webkit-box;font-family: Operator Mono, Consolas, Monaco, Menlo, monospace;font-size: 12px;-webkit-overflow-scrolling: touch;padding-top: 15px;background: #f8f8f8;border-radius: 5px;">$ ./example<br/>Usage:<br/> example[<span style="color: #0086b3;line-height: 26px;">command</span>]<br/><br/>Available Commands:<br/> apply apply request by json file<br/> check check request validity by json file<br/> <span style="color: #0086b3;line-height: 26px;">help</span> Help about any <span style="color: #0086b3;line-height: 26px;">command</span><br/><br/>Flags:<br/> --config string config file[/.xx.yaml] (default <span style="color: #d14;line-height: 26px;">"none"</span>)<br/> -h, --<span style="color: #0086b3;line-height: 26px;">help</span> <span style="color: #0086b3;line-height: 26px;">help</span> <span style="font-weight: bold;line-height: 26px;">for</span> example<br/> --mode string mode[cpu or all] (default <span style="color: #d14;line-height: 26px;">"cpu"</span>)<br/><br/>Use <span style="color: #d14;line-height: 26px;">"example[command] --help"</span> <span style="font-weight: bold;line-height: 26px;">for</span> more information about a <span style="color: #0086b3;line-height: 26px;">command</span>.<br/> |
代码示例如下:
main 入口
1 | <span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;padding: 16px;color: #333;display: -webkit-box;font-family: Operator Mono, Consolas, Monaco, Menlo, monospace;font-size: 12px;-webkit-overflow-scrolling: touch;padding-top: 15px;background: #f8f8f8;border-radius: 5px;"><span style="font-weight: bold;line-height: 26px;">package</span> main<br/><br/><span style="font-weight: bold;line-height: 26px;">import</span> (<br/> log <span style="color: #d14;line-height: 26px;">"github.com/sirupsen/logrus"</span><br/> <span style="color: #d14;line-height: 26px;">"github.com/spf13/cobra"</span><br/> <span style="color: #d14;line-height: 26px;">"github.com/spf13/pflag"</span><br/> <span style="color: #d14;line-height: 26px;">"os"</span><br/><br/> <span style="color: #d14;line-height: 26px;">"example/cmd/apply"</span><br/> <span style="color: #d14;line-height: 26px;">"example/cmd/check"</span><br/> <span style="color: #d14;line-height: 26px;">"example/config"</span><br/>)<br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">main</span><span style="line-height: 26px;">()</span></span> {<br/> <span style="font-weight: bold;line-height: 26px;">var</span> cmdCheck = check.NewVPARequestCheck()<br/> <span style="font-weight: bold;line-height: 26px;">var</span> cmdApply = apply.NewVPARequestApply()<br/><br/> <span style="font-weight: bold;line-height: 26px;">var</span> rootCmd = &cobra.Command{Use: <span style="color: #d14;line-height: 26px;">"example"</span>}<br/><br/> flags := rootCmd.PersistentFlags()<br/> addFlags(flags)<br/><br/> rootCmd.AddCommand(cmdApply, cmdCheck)<br/> <span style="font-weight: bold;line-height: 26px;">if</span> err := rootCmd.Execute(); err != <span style="color: #008080;line-height: 26px;">nil</span> {<br/> <span style="color: #0086b3;line-height: 26px;">panic</span>(err)<br/> }<br/>}<br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">addFlags</span><span style="line-height: 26px;">(flags *pflag.FlagSet)</span></span> {<br/> flags.StringVar(&config.Cfg.KubeConfig, <span style="color: #d14;line-height: 26px;">"config"</span>, <span style="color: #d14;line-height: 26px;">"none"</span>, <span style="color: #d14;line-height: 26px;">"config file[/.xx.yaml]"</span>)<br/> flags.StringVar(&config.Cfg.Mode, <span style="color: #d14;line-height: 26px;">"mode"</span>, <span style="color: #d14;line-height: 26px;">"cpu"</span>, <span style="color: #d14;line-height: 26px;">"mode[cpu or all]"</span>)<br/>}<br/> |
check 命令实现如下,具体 check 相关的 Run 方法忽略:
1 | <span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;padding: 16px;color: #333;display: -webkit-box;font-family: Operator Mono, Consolas, Monaco, Menlo, monospace;font-size: 12px;-webkit-overflow-scrolling: touch;padding-top: 15px;background: #f8f8f8;border-radius: 5px;"><span style="font-weight: bold;line-height: 26px;">package</span> check<br/><br/><span style="font-weight: bold;line-height: 26px;">import</span> (<br/> <span style="color: #d14;line-height: 26px;">"fmt"</span><br/> log <span style="color: #d14;line-height: 26px;">"github.com/sirupsen/logrus"</span><br/> <span style="color: #d14;line-height: 26px;">"github.com/spf13/cobra"</span><br/> <span style="color: #d14;line-height: 26px;">"example/config"</span><br/> <span style="color: #d14;line-height: 26px;">"example/pkg/check"</span><br/> <span style="color: #d14;line-height: 26px;">"example/pkg/files"</span><br/>)<br/><br/><span style="font-weight: bold;line-height: 26px;">type</span> RequestCheckOptions <span style="font-weight: bold;line-height: 26px;">struct</span> {<br/> configPath <span style="font-weight: bold;line-height: 26px;">string</span><br/>}<br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">NewRequestCheckOptions</span><span style="line-height: 26px;">()</span> *<span style="color: #900;font-weight: bold;line-height: 26px;">RequestCheckOptions</span></span> {<br/> o := &RequestCheckOptions{}<br/><br/> <span style="font-weight: bold;line-height: 26px;">return</span> o<br/>}<br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">NewVPARequestCheck</span><span style="line-height: 26px;">()</span> *<span style="color: #900;font-weight: bold;line-height: 26px;">cobra</span>.<span style="color: #900;font-weight: bold;line-height: 26px;">Command</span></span> {<br/> o := NewRequestCheckOptions()<br/> cmd := &cobra.Command{<br/> Use: <span style="color: #d14;line-height: 26px;">"check [json file]"</span>,<br/> Short: <span style="color: #d14;line-height: 26px;">"check request validity by json file"</span>,<br/> Long: <span style="color: #d14;line-height: 26px;">"check request by new request json file"</span>,<br/> Args: cobra.MinimumNArgs(<span style="color: #008080;line-height: 26px;">1</span>),<br/> RunE: <span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span><span style="line-height: 26px;">(c *cobra.Command, args []<span style="font-weight: bold;line-height: 26px;">string</span>)</span> <span style="color: #900;font-weight: bold;line-height: 26px;">error</span></span> {<br/> <span style="font-weight: bold;line-height: 26px;">if</span> err := o.Run(args); err != <span style="color: #008080;line-height: 26px;">nil</span> {<br/> <span style="font-weight: bold;line-height: 26px;">return</span> err<br/> }<br/> <span style="font-weight: bold;line-height: 26px;">return</span> <span style="color: #008080;line-height: 26px;">nil</span><br/> },<br/> }<br/><br/> <span style="font-weight: bold;line-height: 26px;">return</span> cmd<br/>}<br/> |
apply 命令如下,具体 apply 相关的 Run 方法忽略:
1 | <span style="display: block;background: url("https://mmbiz.qpic.cn/mmbiz_svg/Iic9WLWEQMg0xFBwAjJ2zTbZp8CEJMcEu5tTG7n8IStxzpiaxFnmiagcZJ7oyQKaSJvHcvbKxvJibnccxt0JLPko0TJn7pqeK1yv/640?wx_fmt=svg") 10px 10px / 40px no-repeat rgb(248, 248, 248);height: 30px;width: 100%;margin-bottom: -7px;border-radius: 5px;"/><code style="overflow-x: auto;padding: 16px;color: #333;display: -webkit-box;font-family: Operator Mono, Consolas, Monaco, Menlo, monospace;font-size: 12px;-webkit-overflow-scrolling: touch;padding-top: 15px;background: #f8f8f8;border-radius: 5px;"><span style="font-weight: bold;line-height: 26px;">package</span> apply<br/><br/><span style="font-weight: bold;line-height: 26px;">import</span> (<br/> <span style="color: #d14;line-height: 26px;">"fmt"</span><br/> <span style="color: #d14;line-height: 26px;">"github.com/spf13/cobra"</span><br/> <span style="color: #d14;line-height: 26px;">"example/pkg/apply"</span><br/> <span style="color: #d14;line-height: 26px;">"example/pkg/files"</span><br/>)<br/><br/><span style="font-weight: bold;line-height: 26px;">type</span> RequestApplyOptions <span style="font-weight: bold;line-height: 26px;">struct</span> {<br/> configPath <span style="font-weight: bold;line-height: 26px;">string</span><br/>}<br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">NewRequestApplyOptions</span><span style="line-height: 26px;">()</span> *<span style="color: #900;font-weight: bold;line-height: 26px;">RequestApplyOptions</span></span> {<br/> o := &RequestApplyOptions{}<br/><br/> <span style="font-weight: bold;line-height: 26px;">return</span> o<br/>}<br/><br/><span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span> <span style="color: #900;font-weight: bold;line-height: 26px;">NewVPARequestApply</span><span style="line-height: 26px;">()</span> *<span style="color: #900;font-weight: bold;line-height: 26px;">cobra</span>.<span style="color: #900;font-weight: bold;line-height: 26px;">Command</span></span> {<br/> o := NewRequestApplyOptions()<br/><br/> cmd := &cobra.Command{<br/> Use: <span style="color: #d14;line-height: 26px;">"apply [json file]"</span>,<br/> Short: <span style="color: #d14;line-height: 26px;">"apply request by json file"</span>,<br/> Long: <span style="color: #d14;line-height: 26px;">"apply request by new request json file"</span>,<br/> Args: cobra.MinimumNArgs(<span style="color: #008080;line-height: 26px;">1</span>),<br/> RunE: <span style="line-height: 26px;"><span style="font-weight: bold;line-height: 26px;">func</span><span style="line-height: 26px;">(c *cobra.Command, args []<span style="font-weight: bold;line-height: 26px;">string</span>)</span> <span style="color: #900;font-weight: bold;line-height: 26px;">error</span></span> {<br/> <span style="font-weight: bold;line-height: 26px;">if</span> err := o.Run(args); err != <span style="color: #008080;line-height: 26px;">nil</span> {<br/> <span style="font-weight: bold;line-height: 26px;">return</span> err<br/> }<br/> <span style="font-weight: bold;line-height: 26px;">return</span> <span style="color: #008080;line-height: 26px;">nil</span><br/> },<br/> }<br/><br/> <span style="font-weight: bold;line-height: 26px;">return</span> cmd<br/>}<br/> |
然后只需要在各自的 Run 方法中实现对应的逻辑即可。
腾讯程序员视频号最新视频