corba解读

不知道之前大家有没有注意到etcdmain.Main有一个 rootCmd,这个结构体实际上是一个叫corba的在github上的开源库,它的设计目的是提供一个编写/生成交互式命令程序的框架,很多知名的开源项目都采用了该框架,简单来说,使用cobra我们可以很容易的开发类似git、go这样的交互式命令行工具。

还是简单的从etcd的项目中的gateway来说起,

// newGatewayCommand returns the cobra command for "gateway".
func newGatewayCommand() *cobra.Command {
    lpc := &cobra.Command{
        Use:   "gateway <subcommand>",
        Short: "gateway related command",
    }
    lpc.AddCommand(newGatewayStartCommand()) //添加子命令
    return lpc
}

func newGatewayStartCommand() *cobra.Command {
    cmd := cobra.Command{
        Use:   "start",
        Short: "start the gateway",
        Run:   startGateway,
    }

    cmd.Flags().StringVar(&gatewayListenAddr, "listen-addr", "127.0.0.1:23790", "listen address")
    cmd.Flags().StringVar(&gatewayDNSCluster, "discovery-srv", "", "DNS domain used to bootstrap initial cluster")
    cmd.Flags().BoolVar(&gatewayInsecureDiscovery, "insecure-discovery", false, "accept insecure SRV records")
    cmd.Flags().StringVar(&gatewayCA, "trusted-ca-file", "", "path to the client server TLS CA file.")

    cmd.Flags().StringSliceVar(&gatewayEndpoints, "endpoints", []string{"127.0.0.1:2379"}, "comma separated etcd cluster endpoints")

    cmd.Flags().DurationVar(&getewayRetryDelay, "retry-delay", time.Minute, "duration of delay before retrying failed endpoints")

    return &cmd
}

上面这个方法是通过生成一个gateway的命令,同时添加了一个子命令,当我们采用 ./etcd gateway -h :

$ ./etcd gateway -h  
gateway related command //Short

Usage:
  etcd gateway [command]

Available Commands:
  start       start the gateway

Flags:
  -h, --help   help for gateway

Use "etcd gateway [command] --help" for more information about a command.

可以很清晰的看到,Short这个字段世界上就是命令的注释,子命令集合就是在useage中显示,再次输入 ./etcd gateway start -h:

$ ./etcd gateway start -h
start the gateway

Usage:
  etcd gateway start [flags]

Flags:
      --discovery-srv string     DNS domain used to bootstrap initial cluster
      --endpoints strings        comma separated etcd cluster endpoints (default [127.0.0.1:2379])
  -h, --help                     help for start
      --insecure-discovery       accept insecure SRV records
      --listen-addr string       listen address (default "127.0.0.1:23790")
      --retry-delay duration     duration of delay before retrying failed endpoints (default 1m0s)
      --trusted-ca-file string   path to the client server TLS CA file.

可以看到./etcd gateway start 这一子命令,会把其上面设置的flags会显示出来,基于此,我们应该可以清楚的知道,corba的作用是什么。

通过观察corba的源码可以知道,corba提供一系列的属性,用于注释和介绍命令行中各个参数的使用,同时有一个parent的父命令以及commands的子命令集合,具体可以通过corba的源码去查看,同时也提供一些钩子函数,也说明钩子函数的执行顺序,分别是:

  • PersistentPreRun:在run之前发生,并且子命令会继承。
  • PreRun: 在run之前发生,并且子命令不会继承。
  • Run: 运行,大部分的命令仅仅会实现这一方法。
  • PostRun: 在run之后执行。
  • PersistentPostRun: 运行之后执行,并且子命令会继承。

同时提供一个xxxRunE的方法来注册,该方法主要是返回一个错误,run方法是真正的启动命令,如果上面所示当执行./etcd gateway start的时候,就会执行startGateway,这一方法。

总来的来说,corba提高了开发的效率,可以很高效的实现一个类似git的命令事交互工具。

猜你喜欢

转载自www.cnblogs.com/songjingsong/p/9227550.html
今日推荐