在参考go语言编程之旅使用cobra编写命令行工具运行时出现如下错误:
$ go run main.go time now
Error: unknown command "time" for "time"
Run 'time --help' for usage.
具体代码如下:
package main
import (
"github.com/spf13/cobra"
"log"
"time"
)
func GetNowTime() time.Time {
return time.Now()
}
func main() {
var NowTimeCmd = &cobra.Command{
Use: "now",
Short: "获取当前时间",
Long: "马上获取当前时间",
Run: func(cmd *cobra.Command, args []string) {
nowTime := GetNowTime()
log.Printf("当前时间为:%s, %d", nowTime.Format("2006-01-02 15:04:05"), nowTime.Unix())
},
}
var timeCmd = &cobra.Command{
Use: "time",
Short: "时间格式处理",
Long: "时间格式处理,能够处理各种时间格式",
Run: func(cmd *cobra.Command, args []string) {},
}
timeCmd.AddCommand(NowTimeCmd)
timeCmd.Execute()
}
解决错误的方法是按照如下命令运行程序,去掉第一个root命令:
go run main.go now
运行结果如下: