在第一部分我们已经添加了show命令,现在我们修改show.go文件。
1)首先我们实现输出当前时间的功能。
下面是初始化的内容:
// showCmd represents the show command
var showCmd = &cobra.Command{
Use: "show",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("show called")
},
}
// ShowTime 显示当前时间
func ShowTime(cmd *cobra.Command, args []string) {
fmt.Println(time.Now())
}
然后将函数给Command.Run赋值:
// showCmd represents the show command
var showCmd = &cobra.Command{
Use: "show",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: ShowTime, // 这里改为函数名称
}
2)修改help命令。
help命令有两个,一个是short一个是lang,很明显short命令用来定义简短的说明,lang命令用来定义详细说明,下面我们修改show命令的help:
// showCmd represents the show command
var showCmd = &cobra.Command{
Use: "show",
Short: "Displays the current time",
Long: `You can use the time show command to view the current time. For example:
$ ./time show
2020-07-03 15:01:59.6035666 +0800 CST m=+0.013998501`,
Run: ShowTime,
}
修改完成,我们编译代码:
$ go build -o time main.go
执行time命令,我们可以看到show命令后面的说明变成了我们定义的简短说明:
$ ./time
A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.
Usage:
time [command]
Available Commands:
help Help about any command
show Displays the current time
Flags:
--config string config file (default is $HOME/.time.yaml)
-h, --help help for time
-t, --toggle Help message for toggle
Use "time [command] --help" for more information about a command.
我们再执行time show --help命令,可以看到现在展示了show命令的详细说明:
$ ./time show --help
You can use the time show command to view the current time. For example:
$ ./time show
2020-07-03 15:01:59.6035666 +0800 CST m=+0.013998501
Usage:
time show [flags]
Flags:
-h, --help help for show
Global Flags:
--config string config file (default is $HOME/.time.yaml)